diff options
Diffstat (limited to 'common/tests/org.eclipse.jpt.common.utility.tests/src')
197 files changed, 0 insertions, 52042 deletions
diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ArrayToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ArrayToolsTests.java deleted file mode 100644 index b5f840729f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ArrayToolsTests.java +++ /dev/null @@ -1,3523 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.Range; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.ReverseComparator; -import org.eclipse.jpt.common.utility.internal.iterators.EmptyIterator; - -@SuppressWarnings("nls") -public class ArrayToolsTests extends TestCase { - - public ArrayToolsTests(String name) { - super(name); - } - - - // ********** instantiation ********** - - public void testNewArrayObjectArray() { - String[] array1 = new String[2]; - String[] array2 = ArrayTools.newArray(array1); - array2[0] = "foo"; - array2[1] = "bar"; - assertEquals(String.class, array2.getClass().getComponentType()); - assertEquals(2, array2.length); - } - - public void testNewArrayObjectArrayInt() { - String[] array1 = new String[2]; - String[] array2 = ArrayTools.newArray(array1, 5); - array2[0] = "foo"; - array2[4] = "bar"; - assertEquals(String.class, array2.getClass().getComponentType()); - assertEquals(5, array2.length); - } - - public void testNewArrayObjectArrayInt_Exception() { - String[] array1 = new String[2]; - Object[] array2 = ArrayTools.newArray(array1, 5); - boolean exCaught = false; - try { - array2[1] = Integer.valueOf(7); - fail("bogus array: " + Arrays.toString(array2)); - } catch (ArrayStoreException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testComponentType() { - String[] array = new String[2]; - Class<? extends String> javaClass = ArrayTools.componentType(array); - assertEquals(String.class, javaClass); - } - - public void testNewArrayClassInt() { - String[] array = ArrayTools.newArray(String.class, 5); - array[0] = "foo"; - array[4] = "bar"; - assertEquals(String.class, array.getClass().getComponentType()); - assertEquals(5, array.length); - } - - public void testNewArrayClassInt_Exception() { - Object[] array = ArrayTools.newArray(String.class, 5); - boolean exCaught = false; - try { - array[1] = Integer.valueOf(7); - fail("bogus array: " + Arrays.toString(array)); - } catch (ArrayStoreException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testNewArrayClassInt_Primitive() { - boolean exCaught = false; - try { - Object[] array = ArrayTools.newArray(int.class, 5); - fail("bogus array: " + Arrays.toString(array)); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - // ********** conversion ********** - - public void testArrayIterable() { - Iterable<String> iterable = this.buildStringList1(); - Object[] a = ArrayTools.array(iterable); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIterableInt() { - Iterable<String> iterable = this.buildStringList1(); - Object[] a = ArrayTools.array(iterable, 3); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIterableObjectArray_String() { - Iterable<String> iterable = this.buildStringList1(); - String[] a = ArrayTools.array(iterable, new String[0]); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIterableObjectArray_Object() { - Iterable<String> iterable = this.buildStringList1(); - Object[] a = ArrayTools.array(iterable, new Object[0]); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIterableIntObjectArray() { - Iterable<String> iterable = this.buildStringList1(); - String[] a = ArrayTools.array(iterable, 3, new String[0]); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIterator() { - Object[] a = ArrayTools.array(this.buildStringList1().iterator()); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIterator_Empty() { - Object[] a = ArrayTools.array(EmptyIterator.instance()); - assertEquals(0, a.length); - } - - public void testArrayIteratorInt() { - Object[] a = ArrayTools.array(this.buildStringList1().iterator(), 3); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIteratorInt_Empty() { - Object[] a = ArrayTools.array(EmptyIterator.instance(), 3); - assertEquals(0, a.length); - } - - public void testArrayIteratorObjectArray_String() { - String[] a = ArrayTools.array(this.buildStringList1().iterator(), new String[0]); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIteratorObjectArray_Empty() { - String[] a = ArrayTools.array(EmptyIterator.<String>instance(), new String[0]); - assertEquals(0, a.length); - } - - public void testArrayIteratorObjectArray_Empty_ClearArray() { - String[] a = ArrayTools.array(EmptyIterator.<String>instance(), new String[5]); - assertEquals(5, a.length); - assertNull(a[0]); - } - - public void testArrayIteratorObjectArray_Object() { - Object[] a = ArrayTools.array(this.buildStringList1().iterator(), new Object[0]); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIteratorIntObjectArray() { - String[] a = ArrayTools.array(this.buildStringList1().iterator(), 3, new String[0]); - assertEquals(3, a.length); - assertTrue(ArrayTools.containsAll(a, this.buildStringList1().iterator())); - } - - public void testArrayIteratorIntObjectArray_Empty() { - String[] a = ArrayTools.array(EmptyIterator.<String>instance(), 3, new String[0]); - assertEquals(0, a.length); - } - - - // ********** add ********** - - public void testAddObjectArrayObject_Object() { - Object[] a = ArrayTools.add(this.buildObjectArray1(), "twenty"); - assertEquals(4, a.length); - assertTrue(ArrayTools.contains(a, "twenty")); - assertEquals("twenty", a[a.length-1]); - } - - public void testAddObjectArrayObject_String() { - String[] a = ArrayTools.add(this.buildStringArray1(), "twenty"); - assertEquals(4, a.length); - assertTrue(ArrayTools.contains(a, "twenty")); - assertEquals("twenty", a[a.length-1]); - } - - public void testAddObjectArrayObject_EmptyArray() { - String[] a = new String[0]; - a = ArrayTools.add(a, "twenty"); - assertEquals(1, a.length); - assertTrue(ArrayTools.contains(a, "twenty")); - assertEquals("twenty", a[0]); - } - - public void testAddObjectArrayIntObject_Object() { - Object[] a = new Object[] { "a", "b", "c", "d" }; - a = ArrayTools.add(a, 2, "X"); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new Object[] { "a", "b", "X", "c", "d" }, a)); - } - - public void testAddObjectArrayIntObject_String() { - String[] a = new String[] { "a", "b", "c", "d" }; - a = ArrayTools.add(a, 2, "X"); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new String[] { "a", "b", "X", "c", "d" }, a)); - } - - public void testAddObjectArrayIntObject_End() { - String[] a = new String[] { "a", "b", "c", "d" }; - a = ArrayTools.add(a, 4, "X"); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new String[] { "a", "b", "c", "d", "X" }, a)); - } - - public void testAddObjectArrayIntObject_Zero() { - String[] a = new String[] { "a", "b", "c", "d" }; - a = ArrayTools.add(a, 0, "X"); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new String[] { "X", "a", "b", "c", "d" }, a)); - } - - public void testAddObjectArrayIntObject_Exception() { - Object[] a = new Object[] { "a", "b", "c", "d" }; - boolean exCaught = false; - try { - a = ArrayTools.add(a, 33, "X"); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddCharArrayChar() { - char[] a = ArrayTools.add(this.buildCharArray(), 'd'); - assertEquals(4, a.length); - assertTrue(ArrayTools.contains(a, 'd')); - } - - public void testAddCharArrayChar_Empty() { - char[] a = new char[0]; - a = ArrayTools.add(a, 'd'); - assertEquals(1, a.length); - assertTrue(ArrayTools.contains(a, 'd')); - assertTrue(Arrays.equals(new char[] { 'd' }, a)); - } - - public void testAddCharArrayIntChar() { - char[] a = new char[] { 'a', 'b', 'c', 'd' }; - a = ArrayTools.add(a, 2, 'X'); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 'X')); - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'X', 'c', 'd' }, a)); - } - - public void testAddCharArrayIntChar_Zero() { - char[] a = new char[] { 'a', 'b', 'c', 'd' }; - a = ArrayTools.add(a, 0, 'X'); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 'X')); - assertTrue(Arrays.equals(new char[] { 'X', 'a', 'b', 'c', 'd' }, a)); - } - - public void testAddCharArrayIntChar_End() { - char[] a = new char[] { 'a', 'b', 'c', 'd' }; - a = ArrayTools.add(a, 4, 'X'); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 'X')); - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd', 'X' }, a)); - } - - public void testAddIntArrayInt() { - int[] a = ArrayTools.add(this.buildIntArray(), 30); - assertEquals(4, a.length); - assertTrue(ArrayTools.contains(a, 30)); - } - - public void testAddIntArrayInt_Empty() { - int[] a = new int[0]; - a = ArrayTools.add(a, 30); - assertEquals(1, a.length); - assertTrue(ArrayTools.contains(a, 30)); - assertTrue(Arrays.equals(new int[] { 30 }, a)); - } - - public void testAddIntArrayIntInt() { - int[] a = new int[] { 1, 2, 3, 4 }; - a = ArrayTools.add(a, 2, 99); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 99)); - assertTrue(Arrays.equals(new int[] { 1, 2, 99, 3, 4 }, a)); - } - - public void testAddIntArrayIntInt_Zero() { - int[] a = new int[] { 1, 2, 3, 4 }; - a = ArrayTools.add(a, 0, 99); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 99)); - assertTrue(Arrays.equals(new int[] { 99, 1, 2, 3, 4 }, a)); - } - - public void testAddIntArrayIntInt_End() { - int[] a = new int[] { 1, 2, 3, 4 }; - a = ArrayTools.add(a, 4, 99); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 99)); - assertTrue(Arrays.equals(new int[] { 1, 2, 3, 4, 99 }, a)); - } - - - // ********** add all ********** - - public void testAddAllObjectArrayCollection_String() { - String[] a = this.buildStringArray1(); - Collection<String> c = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, c); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, c)); - } - - public void testAddAllObjectArrayCollection_Object() { - Object[] a = this.buildObjectArray1(); - Collection<String> c = this.buildStringList2(); - Object[] newArray = ArrayTools.addAll(a, c); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, c)); - } - - public void testAddAllObjectArrayCollection_EmptyArray() { - String[] a = new String[0]; - Collection<String> c = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, c); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, c)); - } - - public void testAddAllObjectArrayCollection_EmptyCollection() { - String[] a = this.buildStringArray1(); - Collection<String> c = new ArrayList<String>(); - String[] newArray = ArrayTools.addAll(a, c); - - assertEquals(3, newArray.length); - } - - public void testAddAllObjectArrayIntCollection_String() { - String[] a = this.buildStringArray1(); - Collection<String> c = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 1, c); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, c)); - } - - public void testAddAllObjectArrayIntCollection_String_End() { - String[] a = this.buildStringArray1(); - Collection<String> c = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 3, c); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, c)); - } - - public void testAddAllObjectArrayIntCollection_EmptyArray() { - String[] a = new String[0]; - Collection<String> c = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 0, c); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, c)); - } - - public void testAddAllObjectArrayIntCollection_EmptyArray_Exception() { - String[] a = new String[0]; - Collection<String> c = this.buildStringList2(); - boolean exCaught = false; - try { - String[] newArray = ArrayTools.addAll(a, 3, c); - fail("bogus array: " + Arrays.toString(newArray)); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddAllObjectArrayIntCollection_EmptyCollection() { - String[] a = this.buildStringArray1(); - Collection<String> c = new ArrayList<String>(); - String[] newArray = ArrayTools.addAll(a, 1, c); - - assertEquals(3, newArray.length); - } - - public void testAddAllObjectArrayIntIterable_String() { - String[] a = this.buildStringArray1(); - Iterable<String> iterable = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 1, iterable); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, iterable)); - } - - public void testAddAllObjectArrayIntIterable_EmptyArray() { - String[] a = new String[0]; - Iterable<String> iterable = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 0, iterable); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, iterable)); - } - - public void testAddAllObjectArrayIntIterable_EmptyIterable() { - String[] a = this.buildStringArray1(); - Iterable<String> iterable = new ArrayList<String>(); - String[] newArray = ArrayTools.addAll(a, 1, iterable); - - assertEquals(3, newArray.length); - } - - public void testAddAllObjectArrayIntIterableInt_String() { - String[] a = this.buildStringArray1(); - Iterable<String> iterable = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 1, iterable, 3); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, iterable)); - } - - public void testAddAllObjectArrayIntIterableInt_EmptyArray() { - String[] a = new String[0]; - Iterable<String> iterable = this.buildStringList2(); - String[] newArray = ArrayTools.addAll(a, 0, iterable, 3); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, iterable)); - } - - public void testAddAllObjectArrayIntIterableInt_EmptyIterable() { - String[] a = this.buildStringArray1(); - Iterable<String> iterable = new ArrayList<String>(); - String[] newArray = ArrayTools.addAll(a, 1, iterable, 0); - - assertEquals(3, newArray.length); - } - - public void testAddAllObjectArrayIntIterator_String() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = this.buildStringList2().iterator(); - String[] newArray = ArrayTools.addAll(a, 1, iterator); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); - } - - public void testAddAllObjectArrayIntIterator_EmptyArray() { - String[] a = new String[0]; - Iterator<String> iterator = this.buildStringList2().iterator(); - String[] newArray = ArrayTools.addAll(a, 0, iterator); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); - } - - public void testAddAllObjectArrayIntIterator_EmptyIterable() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = EmptyIterator.instance(); - String[] newArray = ArrayTools.addAll(a, 1, iterator); - - assertEquals(3, newArray.length); - } - - public void testAddAllObjectArrayIntIteratorInt_String() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = this.buildStringList2().iterator(); - String[] newArray = ArrayTools.addAll(a, 1, iterator, 3); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); - } - - public void testAddAllObjectArrayIntIteratorInt_EmptyArray() { - String[] a = new String[0]; - Iterator<String> iterator = this.buildStringList2().iterator(); - String[] newArray = ArrayTools.addAll(a, 0, iterator, 3); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList2())); - } - - public void testAddAllObjectArrayIntIteratorInt_EmptyIterator() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = EmptyIterator.instance(); - String[] newArray = ArrayTools.addAll(a, 1, iterator, 0); - - assertEquals(3, newArray.length); - } - - public void testAddAllObjectArrayIterable() { - String[] a = this.buildStringArray1(); - Iterable<String> iterable = this.buildStringList1(); - String[] newArray = ArrayTools.addAll(a, iterable); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); - } - - public void testAddAllObjectArrayIterableInt() { - String[] a = this.buildStringArray1(); - Iterable<String> iterable = this.buildStringList1(); - String[] newArray = ArrayTools.addAll(a, iterable, 33); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); - } - - public void testAddAllObjectArrayIterator_String() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = this.buildStringList1().iterator(); - String[] newArray = ArrayTools.addAll(a, iterator); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); - } - - public void testAddAllObjectArrayIterator_Object() { - String[] a = this.buildStringArray1(); - Iterator<Object> iterator = this.buildObjectList1().iterator(); - Object[] newArray = ArrayTools.addAll(a, iterator); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildObjectList1())); - } - - public void testAddAllObjectArrayIterator_EmptyIterator() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = EmptyIterator.instance(); - String[] newArray = ArrayTools.addAll(a, iterator); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); - } - - public void testAddAllObjectArrayIteratorInt() { - String[] a = this.buildStringArray1(); - Iterator<Object> iterator = this.buildObjectList1().iterator(); - Object[] newArray = ArrayTools.addAll(a, iterator, 3); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildObjectList1())); - } - - public void testAddAllObjectArrayIteratorInt_EmptyIterator() { - String[] a = this.buildStringArray1(); - Iterator<String> iterator = EmptyIterator.instance(); - String[] newArray = ArrayTools.addAll(a, iterator, 0); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, this.buildStringList1())); - } - - public void testAddAllObjectArrayObjectArray_Object() { - Object[] a1 = this.buildObjectArray1(); - Object[] a2 = this.buildObjectArray2(); - Object[] newArray = ArrayTools.addAll(a1, a2); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, a1)); - assertTrue(ArrayTools.containsAll(newArray, a2)); - } - - public void testAddAllObjectArrayObjectArray_String() { - String[] a1 = this.buildStringArray1(); - String[] a2 = this.buildStringArray2(); - String[] newArray = ArrayTools.addAll(a1, a2); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, (Object[]) a1)); - assertTrue(ArrayTools.containsAll(newArray, (Object[]) a2)); - } - - public void testAddAllObjectArrayObjectArray_ObjectString() { - Object[] a1 = this.buildObjectArray1(); - String[] a2 = this.buildStringArray2(); - Object[] newArray = ArrayTools.addAll(a1, (Object[]) a2); - - assertEquals(6, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, a1)); - assertTrue(ArrayTools.containsAll(newArray, (Object[]) a2)); - } - - public void testAddAllObjectArrayObjectArray_EmptyArray1() { - Object[] a1 = new Object[0]; - Object[] a2 = this.buildObjectArray2(); - Object[] newArray = ArrayTools.addAll(a1, a2); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, a2)); - } - - public void testAddAllObjectArrayObjectArray_EmptyArray2() { - Object[] a1 = this.buildObjectArray1(); - Object[] a2 = new Object[0]; - Object[] newArray = ArrayTools.addAll(a1, a2); - - assertEquals(3, newArray.length); - assertTrue(ArrayTools.containsAll(newArray, a1)); - } - - public void testAddAllObjectArrayIntObjectArray_Object() { - Object[] a = new Object[] { "a", "b", "c", "d" }; - a = ArrayTools.addAll(a, 2, new Object[] { "X", "X", "X" }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new Object[] { "a", "b", "X", "X", "X", "c", "d" }, a)); - } - - public void testAddAllObjectArrayIntObjectArray_String() { - String[] a = new String[] { "a", "b", "c", "d" }; - a = ArrayTools.addAll(a, 2, new String[] { "X", "X", "X" }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new String[] { "a", "b", "X", "X", "X", "c", "d" }, a)); - } - - public void testAddAllObjectArrayIntObjectArray_ObjectString() { - Object[] a = new Object[] { "a", "b", "c", "d" }; - a = ArrayTools.addAll(a, 2, (Object[]) new String[] { "X", "X", "X" }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new Object[] { "a", "b", "X", "X", "X", "c", "d" }, a)); - } - - public void testAddAllObjectArrayIntObjectArray_End() { - Object[] a = new Object[] { "a", "b", "c", "d" }; - a = ArrayTools.addAll(a, 4, (Object[]) new String[] { "X", "X", "X" }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new Object[] { "a", "b", "c", "d", "X", "X", "X" }, a)); - } - - public void testAddAllObjectArrayIntObjectArray_Zero() { - Object[] a = new Object[0]; - a = ArrayTools.addAll(a, 0, (Object[]) new String[] { "X", "X", "X" }); - assertEquals(3, a.length); - assertTrue(ArrayTools.contains(a, "X")); - assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, a)); - } - - public void testAddAllObjectArrayIntObjectArray_EmptyArray2() { - Object[] a = new Object[] { "a", "b", "c", "d" }; - a = ArrayTools.addAll(a, 4, (Object[]) new String[0]); - assertEquals(4, a.length); - assertTrue(Arrays.equals(new Object[] { "a", "b", "c", "d" }, a)); - } - - public void testAddAllObjectArrayIntObjectArray_EmptyArray1() { - Object[] a = new String[0]; - a = ArrayTools.addAll(a, 0, new Object[] { "a", "b", "c", "d" }); - assertEquals(4, a.length); - assertTrue(Arrays.equals(new Object[] { "a", "b", "c", "d" }, a)); - } - - public void testAddAllCharArrayCharArray() { - char[] a = ArrayTools.addAll(this.buildCharArray(), new char[] { 'd', 'e' }); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 'd')); - assertTrue(ArrayTools.contains(a, 'e')); - } - - public void testAddAllCharArrayCharArray_EmptyArray2() { - char[] a = ArrayTools.addAll(this.buildCharArray(), new char[0]); - assertEquals(3, a.length); - } - - public void testAddAllCharArrayCharArrayEmptyArray1() { - char[] a = ArrayTools.addAll(new char[0], new char[] { 'd', 'e' }); - assertEquals(2, a.length); - assertTrue(ArrayTools.contains(a, 'd')); - assertTrue(ArrayTools.contains(a, 'e')); - } - - public void testAddAllCharArrayIntCharArray() { - char[] a = new char[] { 'a', 'b', 'c', 'd' }; - a = ArrayTools.addAll(a, 2, new char[] { 'X', 'X', 'X' }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, 'X')); - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'X', 'X', 'X', 'c', 'd' }, a)); - } - - public void testAddAllCharArrayIntCharArray_End() { - char[] a = new char[] { 'a', 'b', 'c', 'd' }; - a = ArrayTools.addAll(a, 4, new char[] { 'X', 'X', 'X' }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, 'X')); - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd', 'X', 'X', 'X' }, a)); - } - - public void testAddAllCharArrayIntCharArray_EmptyArray1() { - char[] a = new char[0]; - a = ArrayTools.addAll(a, 0, new char[] { 'X', 'X', 'X' }); - assertEquals(3, a.length); - assertTrue(ArrayTools.contains(a, 'X')); - assertTrue(Arrays.equals(new char[] { 'X', 'X', 'X' }, a)); - } - - public void testAddAllCharArrayIntCharArray_EmptyArray2() { - char[] a = new char[] { 'a', 'b', 'c', 'd' }; - a = ArrayTools.addAll(a, 2, new char[0]); - assertEquals(4, a.length); - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd' }, a)); - } - - public void testAddAllIntArrayIntArray() { - int[] a = ArrayTools.addAll(this.buildIntArray(), new int[] { 30, 40 }); - assertEquals(5, a.length); - assertTrue(ArrayTools.contains(a, 30)); - assertTrue(ArrayTools.contains(a, 40)); - } - - public void testAddAllIntArrayIntArray_EmptyArray2() { - int[] a = ArrayTools.addAll(this.buildIntArray(), new int[0]); - assertEquals(3, a.length); - } - - public void testAddAllIntArrayIntArray_EmptyArray1() { - int[] a = ArrayTools.addAll(new int[0], new int[] { 30, 40 }); - assertEquals(2, a.length); - assertTrue(ArrayTools.contains(a, 30)); - assertTrue(ArrayTools.contains(a, 40)); - } - - public void testAddAllIntArrayIntIntArray() { - int[] a = new int[] { 1, 2, 3, 4 }; - a = ArrayTools.addAll(a, 2, new int[] { 99, 99, 99 }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, 99)); - assertTrue(Arrays.equals(new int[] { 1, 2, 99, 99, 99, 3, 4 }, a)); - } - - public void testAddAllIntArrayIntIntArray_End() { - int[] a = new int[] { 1, 2, 3, 4 }; - a = ArrayTools.addAll(a, 4, new int[] { 99, 99, 99 }); - assertEquals(7, a.length); - assertTrue(ArrayTools.contains(a, 99)); - assertTrue(Arrays.equals(new int[] { 1, 2, 3, 4, 99, 99, 99 }, a)); - } - - public void testAddAllIntArrayIntIntArray_EmptyArray2() { - int[] a = new int[] { 1, 2, 3, 4 }; - a = ArrayTools.addAll(a, 2, new int[0]); - assertEquals(4, a.length); - assertTrue(Arrays.equals(new int[] { 1, 2, 3, 4 }, a)); - } - - public void testAddAllIntArrayIntIntArray_EmptyArray1() { - int[] a = new int[0]; - a = ArrayTools.addAll(a, 0, new int[] { 99, 99, 99 }); - assertEquals(3, a.length); - assertTrue(ArrayTools.contains(a, 99)); - assertTrue(Arrays.equals(new int[] { 99, 99, 99 }, a)); - } - - - // ********** clear ********** - - public void testClearObjectArray() { - String[] a = this.buildStringArray1(); - assertEquals(3, a.length); - a = ArrayTools.clear(a); - assertEquals(0, a.length); - } - - public void testClearObjectArray_Empty() { - String[] a = new String[0]; - assertEquals(0, a.length); - a = ArrayTools.clear(a); - assertEquals(0, a.length); - } - - - // ********** concatenate ********** - - public void testConcatenateObjectArrayArray() { - String[] aArray = new String[] { "a", "b", "c", "d" }; - String[] eArray = new String[] { "e", "f", "g", "h" }; - String[] iArray = new String[] { "i", "j", "k", "l" }; - - String[] expected = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" }; - String[] actual = ArrayTools.concatenate(aArray, eArray, iArray); - assertTrue(Arrays.equals(expected, actual)); - } - - public void testConcatenateObjectArrayArray_Empty() { - String[] aArray = new String[] { }; - String[] eArray = new String[0]; - String[] iArray = new String[0]; - - String[] expected = new String[0]; - String[] actual = ArrayTools.concatenate(aArray, eArray, iArray); - assertEquals(0, actual.length); - assertTrue(Arrays.equals(expected, actual)); - } - - public void testConcatenateCharArrayArray() { - char[] aArray = new char[] { 'a', 'b', 'c', 'd' }; - char[] eArray = new char[] { 'e', 'f', 'g', 'h' }; - char[] iArray = new char[] { 'i', 'j', 'k', 'l' }; - - char[] expected = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' }; - char[] actual = ArrayTools.concatenate(aArray, eArray, iArray); - assertTrue(Arrays.equals(expected, actual)); - } - - public void testConcatenateCharArrayArray_Empty() { - char[] aArray = new char[] { }; - char[] eArray = new char[0]; - char[] iArray = new char[0]; - - char[] expected = new char[0]; - char[] actual = ArrayTools.concatenate(aArray, eArray, iArray); - assertEquals(0, actual.length); - assertTrue(Arrays.equals(expected, actual)); - } - - public void testConcatenateIntArrayArray() { - int[] aArray = new int[] { 'a', 'b', 'c', 'd' }; - int[] eArray = new int[] { 'e', 'f', 'g', 'h' }; - int[] iArray = new int[] { 'i', 'j', 'k', 'l' }; - - int[] expected = new int[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' }; - int[] actual = ArrayTools.concatenate(aArray, eArray, iArray); - assertTrue(Arrays.equals(expected, actual)); - } - - public void testConcatenateIntArrayArray_Empty() { - int[] aArray = new int[] { }; - int[] eArray = new int[0]; - int[] iArray = new int[0]; - - int[] expected = new int[0]; - int[] actual = ArrayTools.concatenate(aArray, eArray, iArray); - assertEquals(0, actual.length); - assertTrue(Arrays.equals(expected, actual)); - } - - - // ********** contains ********** - - public void testContainsObjectArrayObject() { - Object[] a = this.buildObjectArray1(); - assertTrue(ArrayTools.contains(a, "one")); - assertFalse(ArrayTools.contains(a, null)); - Object[] a2 = ArrayTools.add(a, null); - assertTrue(ArrayTools.contains(a2, null)); - } - - public void testContainsObjectArrayObject_EmptyArray() { - Object[] a = new Object[0]; - assertFalse(ArrayTools.contains(a, "one")); - assertFalse(ArrayTools.contains(a, null)); - } - - public void testContainsCharArrayChar() { - char[] a = this.buildCharArray(); - assertTrue(ArrayTools.contains(a, 'a')); - assertFalse(ArrayTools.contains(a, 'z')); - char[] a2 = ArrayTools.add(a, 'z'); - assertTrue(ArrayTools.contains(a2, 'z')); - } - - public void testContainsCharArrayObject_EmptyArray() { - char[] a = new char[0]; - assertFalse(ArrayTools.contains(a, 'a')); - } - - public void testContainsIntArrayInt() { - int[] a = this.buildIntArray(); - assertTrue(ArrayTools.contains(a, 10)); - assertFalse(ArrayTools.contains(a, 55)); - int[] a2 = ArrayTools.add(a, 55); - assertTrue(ArrayTools.contains(a2, 55)); - } - - public void testContainsIntArrayObject_EmptyArray() { - int[] a = new int[0]; - assertFalse(ArrayTools.contains(a, 'a')); - } - - - // ********** contains all ********** - - public void testContainsAllObjectArrayCollection() { - assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList1())); - assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList2())); - } - - public void testContainsAllObjectArrayIterable() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), iterable)); - iterable = this.buildStringList2(); - assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), iterable)); - } - - public void testContainsAllObjectArrayIterator() { - assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList1().iterator())); - assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), this.buildStringList2().iterator())); - } - - public void testContainsAllObjectArrayIterator_Empty() { - assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), EmptyIterator.instance())); - } - - public void testContainsAllObjectArrayObjectArray() { - assertTrue(ArrayTools.containsAll(this.buildObjectArray1(), this.buildObjectArray1())); - assertFalse(ArrayTools.containsAll(this.buildObjectArray1(), this.buildObjectArray2())); - } - - public void testContainsAllCharArrayCharArray() { - assertTrue(ArrayTools.containsAll(this.buildCharArray(), this.buildCharArray())); - assertFalse(ArrayTools.containsAll(this.buildCharArray(), new char[] { 'x', 'y' })); - } - - public void testContainsAllIntArrayIntArray() { - assertTrue(ArrayTools.containsAll(this.buildIntArray(), this.buildIntArray())); - assertFalse(ArrayTools.containsAll(this.buildIntArray(), new int[] { 444, 888 })); - } - - - // ********** diff ********** - - public void testDiffEnd() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String a_ = new String("a"); - String b_ = new String("b"); - String c_ = new String("c"); - String d_ = new String("d"); - String e_ = new String("e"); - assertTrue((a != a_) && a.equals(a_)); - assertTrue((b != b_) && b.equals(b_)); - assertTrue((c != c_) && c.equals(c_)); - assertTrue((d != d_) && d.equals(d_)); - assertTrue((e != e_) && e.equals(e_)); - String[] array1; - String[] array2; - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(-1, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a }; - array2 = new String[] { a_ }; - assertEquals(-1, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[0]; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[0]; - assertEquals(4, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[0]; - array2 = new String[0]; - assertEquals(-1, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, a_, d_, e_ }; - assertEquals(2, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, c_, d_, e_ }; - assertEquals(0, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a, b, c, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(3, ArrayTools.diffEnd(array1, array2)); - - String c__ = new String(c); - assertTrue((c != c__) && c.equals(c_)); - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c__, d_, e_ }; - assertEquals(-1, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(2, ArrayTools.diffEnd(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, null, d_, e_ }; - assertEquals(-1, ArrayTools.diffEnd(array1, array2)); - } - - public void testDiffRange() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String a_ = a; - String b_ = b; - String c_ = c; - String d_ = d; - String e_ = e; - assertTrue((a == a_) && a.equals(a_)); - assertTrue((b == b_) && b.equals(b_)); - assertTrue((c == c_) && c.equals(c_)); - assertTrue((d == d_) && d.equals(d_)); - assertTrue((e == e_) && e.equals(e_)); - String[] array1; - String[] array2; - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(5, -1), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a }; - array2 = new String[] { a_ }; - assertEquals(new Range(1, -1), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, d_, e_ }; - assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); - - array1 = new String[0]; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[0]; - assertEquals(new Range(0, 4), ArrayTools.diffRange(array1, array2)); - - array1 = new String[0]; - array2 = new String[0]; - assertEquals(new Range(0, -1), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, a_, d_, e_ }; - assertEquals(new Range(0, 2), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, c_, d_, e_ }; - assertEquals(new Range(0, 0), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a, b, c, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(new Range(3, 3), ArrayTools.diffRange(array1, array2)); - - String c__ = new String(c); - assertTrue((c != c__) && c.equals(c_)); - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c__, d_, e_ }; - assertEquals(new Range(5, -1), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(2, 2), ArrayTools.diffRange(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, null, d_, e_ }; - assertEquals(new Range(5, -1), ArrayTools.diffRange(array1, array2)); - } - - public void testDiffStart() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String a_ = new String("a"); - String b_ = new String("b"); - String c_ = new String("c"); - String d_ = new String("d"); - String e_ = new String("e"); - assertTrue((a != a_) && a.equals(a_)); - assertTrue((b != b_) && b.equals(b_)); - assertTrue((c != c_) && c.equals(c_)); - assertTrue((d != d_) && d.equals(d_)); - assertTrue((e != e_) && e.equals(e_)); - String[] array1; - String[] array2; - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(5, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a }; - array2 = new String[] { a_ }; - assertEquals(1, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, c, d }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(4, ArrayTools.diffStart(array1, array2)); - - array1 = new String[0]; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(0, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[0]; - assertEquals(0, ArrayTools.diffStart(array1, array2)); - - array1 = new String[0]; - array2 = new String[0]; - assertEquals(0, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, e_, c_, d_ }; - assertEquals(2, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, c, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(3, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, c_, d_, e_ }; - assertEquals(0, ArrayTools.diffStart(array1, array2)); - - String c__ = new String(c); - assertTrue((c != c__) && c.equals(c__)); - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c__, d_, e_ }; - assertEquals(5, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(2, ArrayTools.diffStart(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, null, d_, e_ }; - assertEquals(5, ArrayTools.diffStart(array1, array2)); - } - - - // ********** identity diff ********** - - public void testIdentityDiffEnd() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String a_ = a; - String b_ = b; - String c_ = c; - String d_ = d; - String e_ = e; - assertTrue((a == a_) && a.equals(a_)); - assertTrue((b == b_) && b.equals(b_)); - assertTrue((c == c_) && c.equals(c_)); - assertTrue((d == d_) && d.equals(d_)); - assertTrue((e == e_) && e.equals(e_)); - String[] array1; - String[] array2; - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a }; - array2 = new String[] { a_ }; - assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[0]; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[0]; - assertEquals(4, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[0]; - array2 = new String[0]; - assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, a_, d_, e_ }; - assertEquals(2, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, c_, d_, e_ }; - assertEquals(0, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a, b, c, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(3, ArrayTools.identityDiffEnd(array1, array2)); - - String c__ = new String(c); - assertTrue((c != c__) && c.equals(c_)); - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c__, d_, e_ }; - assertEquals(2, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(2, ArrayTools.identityDiffEnd(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, null, d_, e_ }; - assertEquals(-1, ArrayTools.identityDiffEnd(array1, array2)); - } - - public void testIdentityDiffRange() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String a_ = a; - String b_ = b; - String c_ = c; - String d_ = d; - String e_ = e; - assertTrue((a == a_) && a.equals(a_)); - assertTrue((b == b_) && b.equals(b_)); - assertTrue((c == c_) && c.equals(c_)); - assertTrue((d == d_) && d.equals(d_)); - assertTrue((e == e_) && e.equals(e_)); - String[] array1; - String[] array2; - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(5, -1), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a }; - array2 = new String[] { a_ }; - assertEquals(new Range(1, -1), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, d_, e_ }; - assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[0]; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[0]; - assertEquals(new Range(0, 4), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[0]; - array2 = new String[0]; - assertEquals(new Range(0, -1), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { b_, c_, a_, d_, e_ }; - assertEquals(new Range(0, 2), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, c_, d_, e_ }; - assertEquals(new Range(0, 0), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a, b, c, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(new Range(3, 3), ArrayTools.identityDiffRange(array1, array2)); - - String c__ = new String(c); - assertTrue((c != c__) && c.equals(c_)); - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c__, d_, e_ }; - assertEquals(new Range(2, 2), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(new Range(2, 2), ArrayTools.identityDiffRange(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, null, d_, e_ }; - assertEquals(new Range(5, -1), ArrayTools.identityDiffRange(array1, array2)); - } - - public void testIdentityDiffStart() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String a_ = a; - String b_ = b; - String c_ = c; - String d_ = d; - String e_ = e; - assertTrue((a == a_) && a.equals(a_)); - assertTrue((b == b_) && b.equals(b_)); - assertTrue((c == c_) && c.equals(c_)); - assertTrue((d == d_) && d.equals(d_)); - assertTrue((e == e_) && e.equals(e_)); - String[] array1; - String[] array2; - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(5, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a }; - array2 = new String[] { a_ }; - assertEquals(1, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, c, d }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(4, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(4, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[0]; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[0]; - assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[0]; - array2 = new String[0]; - assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, e_, c_, d_ }; - assertEquals(2, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, c, e }; - array2 = new String[] { a_, b_, c_, d_ }; - assertEquals(3, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { b, c, d, e }; - array2 = new String[] { a_, c_, d_, e_ }; - assertEquals(0, ArrayTools.identityDiffStart(array1, array2)); - - String c__ = new String(c); - assertTrue((c != c__) && c.equals(c_)); - array1 = new String[] { a, b, c, d, e }; - array2 = new String[] { a_, b_, c__, d_, e_ }; - assertEquals(2, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, c_, d_, e_ }; - assertEquals(2, ArrayTools.identityDiffStart(array1, array2)); - - array1 = new String[] { a, b, null, d, e }; - array2 = new String[] { a_, b_, null, d_, e_ }; - assertEquals(5, ArrayTools.identityDiffStart(array1, array2)); - } - - - // ********** elements are identical ********** - - public void testElementsAreIdenticalObjectArrayObjectArray() { - Object[] a1 = new Object[4]; - for (int i = 0; i < a1.length; i++) { - a1[i] = String.valueOf(i * 1000); - } - - Object[] a2 = new Object[a1.length]; - for (int i = 0; i < a2.length; i++) { - a2[i] = a1[i]; - } - - assertTrue(ArrayTools.elementsAreIdentical(a1, a2)); - a2[2] = "2000"; - assertFalse(ArrayTools.elementsAreIdentical(a1, a2)); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testElementsAreIdenticalObjectArrayObjectArray_BothNull() { - Object[] a1 = null; - Object[] a2 = null; - assertTrue(ArrayTools.elementsAreIdentical(a1, a2)); - } - - public void testElementsAreIdenticalObjectArrayObjectArray_OneNull() { - Object[] a1 = null; - Object[] a2 = new Object[0]; - assertFalse(ArrayTools.elementsAreIdentical(a1, a2)); - } - - public void testElementsAreIdenticalObjectArrayObjectArray_DifferentLengths() { - Object[] a1 = new String[] {"foo", "bar"}; - Object[] a2 = new String[] {"foo", "bar", "baz"}; - assertFalse(ArrayTools.elementsAreIdentical(a1, a2)); - } - - - // ********** index of ********** - - public void testIndexOfObjectArrayObject() { - Object[] a = this.buildObjectArray1(); - assertEquals(1, ArrayTools.indexOf(a, "one")); - } - - public void testIndexOfObjectArrayObject_NotFound() { - Object[] a = this.buildObjectArray1(); - assertEquals(-1, ArrayTools.indexOf(a, "twenty")); - } - - public void testIndexOfObjectArrayObject_Null() { - Object[] a = this.buildObjectArray1(); - a = ArrayTools.add(a, null); - assertEquals(a.length - 1, ArrayTools.indexOf(a, null)); - } - - public void testIndexOfObjectArrayObject_Null_NotFound() { - Object[] a = this.buildObjectArray1(); - assertEquals(-1, ArrayTools.indexOf(a, null)); - } - - public void testIdentityIndexOfObjectArrayObject() { - String foo = "foo"; - String bar = "bar"; - String baz = "baz"; - Object[] a = new Object[3]; - a[0] = foo; - a[1] = bar; - a[2] = baz; - assertEquals(1, ArrayTools.identityIndexOf(a, bar)); - } - - public void testIdentityIndexOfObjectArrayObject_NotFound() { - String foo = "foo"; - String bar = "bar"; - String baz = "baz"; - Object[] a = new Object[3]; - a[0] = foo; - a[1] = bar; - a[2] = baz; - assertEquals(-1, ArrayTools.identityIndexOf(a, new String("bar"))); - } - - public void testIndexOfCharArrayChar() { - char[] a = this.buildCharArray(); - assertEquals(1, ArrayTools.indexOf(a, 'b')); - a = ArrayTools.add(a, 'd'); - assertEquals(a.length - 1, ArrayTools.indexOf(a, 'd')); - } - - public void testIndexOfCharArrayChar_NotFound() { - char[] a = this.buildCharArray(); - assertEquals(-1, ArrayTools.indexOf(a, 'z')); - } - - public void testIndexOfIntArrayInt() { - int[] a = this.buildIntArray(); - assertEquals(1, ArrayTools.indexOf(a, 10)); - a = ArrayTools.add(a, 30); - assertEquals(a.length - 1, ArrayTools.indexOf(a, 30)); - } - - public void testIndexOfIntArrayInt_NotFound() { - int[] a = this.buildIntArray(); - assertEquals(-1, ArrayTools.indexOf(a, 1000)); - } - - - // ********** insertion index of ********** - - public void testInsertionIndexOfObjectArrayComparable() { - String[] a = new String[] { "A", "C", "D" }; - assertEquals(1, ArrayTools.insertionIndexOf(a, "B")); - - a = new String[] { "A", "B", "C", "D" }; - assertEquals(2, ArrayTools.insertionIndexOf(a, "B")); - - a = new String[] { "A", "B", "B", "B", "C", "D" }; - assertEquals(4, ArrayTools.insertionIndexOf(a, "B")); - - a = new String[] { "A", "B", "B", "B", "C", "D" }; - assertEquals(6, ArrayTools.insertionIndexOf(a, "E")); - - a = new String[] { "B", "B", "B", "C", "D" }; - assertEquals(0, ArrayTools.insertionIndexOf(a, "A")); - - a = new String[] { "A", "A", "B", "B", "C", "D" }; - assertEquals(2, ArrayTools.insertionIndexOf(a, "A")); - } - - public void testInsertionIndexOfObjectArrayObjectComparator() { - Comparator<String> c = new ReverseComparator<String>(); - String[] a = new String[] { "D", "C", "A" }; - assertEquals(2, ArrayTools.insertionIndexOf(a, "B", c)); - - a = new String[] { "D", "C", "B", "A" }; - assertEquals(3, ArrayTools.insertionIndexOf(a, "B", c)); - - a = new String[] { "D", "C", "B", "B", "B", "A" }; - assertEquals(5, ArrayTools.insertionIndexOf(a, "B", c)); - - a = new String[] { "D", "C", "B", "B", "B", "A" }; - assertEquals(0, ArrayTools.insertionIndexOf(a, "E", c)); - - a = new String[] { "D", "C", "B", "B", "B" }; - assertEquals(5, ArrayTools.insertionIndexOf(a, "A", c)); - - a = new String[] { "D", "C", "B", "B", "A", "A" }; - assertEquals(6, ArrayTools.insertionIndexOf(a, "A", c)); - } - - - // ********** last index of ********** - - public void testLastIndexOfObjectArrayObject() { - Object[] a = this.buildObjectArray1(); - assertEquals(1, ArrayTools.lastIndexOf(a, "one")); - } - - public void testLastIndexOfObjectArrayObject_NotFound() { - Object[] a = this.buildObjectArray1(); - assertEquals(-1, ArrayTools.lastIndexOf(a, "twenty")); - } - - public void testLastIndexOfObjectArrayObject_Null() { - Object[] a = this.buildObjectArray1(); - a = ArrayTools.add(a, null); - assertEquals(a.length - 1, ArrayTools.lastIndexOf(a, null)); - } - - public void testLastIndexOfObjectArrayObject_Null_NotFound() { - Object[] a = this.buildObjectArray1(); - assertEquals(-1, ArrayTools.lastIndexOf(a, null)); - } - - public void testLastIndexOfCharArrayChar() { - char[] a = this.buildCharArray(); - assertEquals(1, ArrayTools.lastIndexOf(a, 'b')); - a = ArrayTools.add(a, 'd'); - assertEquals(a.length - 1, ArrayTools.lastIndexOf(a, 'd')); - } - - public void testLastIndexOfCharArrayChar_NotFound() { - char[] a = this.buildCharArray(); - assertEquals(-1, ArrayTools.lastIndexOf(a, 'z')); - } - - public void testLastIndexOfIntArrayInt() { - int[] a = this.buildIntArray(); - assertEquals(1, ArrayTools.lastIndexOf(a, 10)); - a = ArrayTools.add(a, 30); - assertEquals(a.length - 1, ArrayTools.lastIndexOf(a, 30)); - } - - public void testLastIndexOfIntArrayInt_NotFound() { - int[] a = this.buildIntArray(); - assertEquals(-1, ArrayTools.lastIndexOf(a, 1000)); - } - - - // ********** min/max ********** - - public void testMinCharArray() { - assertEquals('a', ArrayTools.min(this.buildCharArray())); - } - - public void testMinCharArray_Exception() { - char[] array = new char[0]; - boolean exCaught = false; - try { - char c = ArrayTools.min(array); - fail("bogus char: " + c); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testMinIntArray() { - assertEquals(0, ArrayTools.min(this.buildIntArray())); - } - - public void testMinIntArray_Exception() { - int[] array = new int[0]; - boolean exCaught = false; - try { - int i = ArrayTools.min(array); - fail("bogus int: " + i); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testMaxCharArray1() { - assertEquals('c', ArrayTools.max(this.buildCharArray())); - } - - public void testMaxCharArray2() { - char[] array = new char[] { 'x', 'a', 'b', 'c' }; - assertEquals('x', ArrayTools.max(array)); - } - - public void testMaxCharArray_Exception() { - char[] array = new char[0]; - boolean exCaught = false; - try { - char c = ArrayTools.max(array); - fail("bogus char: " + c); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testMaxIntArray1() { - assertEquals(20, ArrayTools.max(this.buildIntArray())); - } - - public void testMaxIntArray2() { - int[] array = new int[] { 77, 3, 1, -3 }; - assertEquals(77, ArrayTools.max(array)); - } - - public void testMaxIntArray_Exception() { - int[] array = new int[0]; - boolean exCaught = false; - try { - int i = ArrayTools.max(array); - fail("bogus int: " + i); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - // ********** move ********** - - public void testMoveObjectArrayIntInt() { - String[] array = new String[] { "0", "1", "2", "3", "4", "5" }; - - String[] result = ArrayTools.move(array, 4, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result)); - - result = ArrayTools.move(array, 0, 5); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result)); - - result = ArrayTools.move(array, 2, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result)); - - result = ArrayTools.move(array, 4, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result)); - } - - public void testMoveObjectArrayIntIntInt() { - String[] array = new String[] { "0", "1", "2", "3", "4", "5" }; - - String[] result = ArrayTools.move(array, 4, 2, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result)); - - result = ArrayTools.move(array, 0, 5, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result)); - - result = ArrayTools.move(array, 2, 4, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result)); - - result = ArrayTools.move(array, 2, 4, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); - - result = ArrayTools.move(array, 0, 1, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "3", "2", "4", "5", "1" }, result)); - - result = ArrayTools.move(array, 1, 0, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); - - result = ArrayTools.move(array, 1, 1, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); - - result = ArrayTools.move(array, 1, 0, 0); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result)); - } - - public void testMoveIntArrayIntInt() { - int[] array = new int[] { 0, 1, 2, 3, 4, 5 }; - - int[] result = ArrayTools.move(array, 4, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 0, 1, 3, 4, 2, 5 }, result)); - - result = ArrayTools.move(array, 0, 5); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 1, 3, 4, 2 }, result)); - - result = ArrayTools.move(array, 2, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 4, 1, 3, 2 }, result)); - - result = ArrayTools.move(array, 2, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 4, 1, 3, 2 }, result)); - } - - public void testMoveIntArrayIntIntInt() { - int[] array = new int[] { 0, 1, 2, 3, 4, 5 }; - - int[] result = ArrayTools.move(array, 4, 2, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 0, 1, 3, 4, 2, 5 }, result)); - - result = ArrayTools.move(array, 0, 5, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 1, 3, 4, 2 }, result)); - - result = ArrayTools.move(array, 2, 4, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 4, 1, 3, 2 }, result)); - - result = ArrayTools.move(array, 2, 4, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); - - result = ArrayTools.move(array, 0, 1, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 0, 3, 2, 4, 5, 1 }, result)); - - result = ArrayTools.move(array, 1, 0, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); - - result = ArrayTools.move(array, 1, 1, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); - - result = ArrayTools.move(array, 1, 0, 0); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new int[] { 5, 0, 3, 2, 4, 1 }, result)); - } - - public void testMoveCharArrayIntInt() { - char[] array = new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }; - - char[] result = ArrayTools.move(array, 4, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'd', 'e', 'c', 'f' }, result)); - - result = ArrayTools.move(array, 0, 5); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'f', 'a', 'b', 'd', 'e', 'c' }, result)); - - result = ArrayTools.move(array, 2, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'f', 'a', 'e', 'b', 'd', 'c' }, result)); - - result = ArrayTools.move(array, 2, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'f', 'a', 'e', 'b', 'd', 'c' }, result)); - } - - public void testMoveCharArrayIntIntInt() { - char[] array = new char[] { 'a', 'b', 'b', 'c', 'd', 'e' }; - - char[] result = ArrayTools.move(array, 4, 2, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'a', 'b', 'c', 'd', 'b', 'e' }, result)); - - result = ArrayTools.move(array, 0, 5, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'e', 'a', 'b', 'c', 'd', 'b' }, result)); - - result = ArrayTools.move(array, 2, 4, 1); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'e', 'a', 'd', 'b', 'c', 'b' }, result)); - - result = ArrayTools.move(array, 2, 4, 2); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); - - result = ArrayTools.move(array, 0, 1, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'a', 'c', 'b', 'd', 'e', 'b' }, result)); - - result = ArrayTools.move(array, 1, 0, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); - - result = ArrayTools.move(array, 1, 1, 4); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); - - result = ArrayTools.move(array, 1, 0, 0); - assertSame(array, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new char[] { 'e', 'a', 'c', 'b', 'd', 'b' }, result)); - } - - - // ********** remove ********** - - public void testRemoveObjectArrayObject_Object() { - Object[] a = this.buildObjectArray1(); - a = ArrayTools.add(a, "three"); - a = ArrayTools.add(a, "four"); - a = ArrayTools.add(a, "five"); - - assertEquals(6, a.length); - assertTrue(ArrayTools.contains(a, "three")); - a = ArrayTools.remove(a, "three"); - assertEquals(5, a.length); - assertFalse(ArrayTools.contains(a, "three")); - assertTrue(ArrayTools.contains(a, "four")); - assertTrue(ArrayTools.contains(a, "five")); - } - - public void testRemoveObjectArrayObject_String() { - String[] a = this.buildStringArray1(); - a = ArrayTools.add(a, "three"); - a = ArrayTools.add(a, "four"); - a = ArrayTools.add(a, "five"); - - assertEquals(6, a.length); - assertTrue(ArrayTools.contains(a, "three")); - a = ArrayTools.remove(a, "three"); - assertEquals(5, a.length); - assertFalse(ArrayTools.contains(a, "three")); - assertTrue(ArrayTools.contains(a, "four")); - assertTrue(ArrayTools.contains(a, "five")); - } - - public void testRemoveCharArrayChar() { - char[] a = this.buildCharArray(); - a = ArrayTools.add(a, 'd'); - a = ArrayTools.add(a, 'e'); - a = ArrayTools.add(a, 'f'); - - assertEquals(6, a.length); - assertTrue(ArrayTools.contains(a, 'd')); - a = ArrayTools.remove(a, 'd'); - assertEquals(5, a.length); - assertFalse(ArrayTools.contains(a, 'd')); - assertTrue(ArrayTools.contains(a, 'e')); - assertTrue(ArrayTools.contains(a, 'f')); - } - - public void testRemoveIntArrayInt() { - int[] a = this.buildIntArray(); - a = ArrayTools.add(a, 30); - a = ArrayTools.add(a, 40); - a = ArrayTools.add(a, 50); - - assertEquals(6, a.length); - assertTrue(ArrayTools.contains(a, 30)); - a = ArrayTools.remove(a, 30); - assertEquals(5, a.length); - assertFalse(ArrayTools.contains(a, 30)); - assertTrue(ArrayTools.contains(a, 40)); - assertTrue(ArrayTools.contains(a, 50)); - } - - - // ********** remove all ********** - - public void testRemoveAllObjectArrayObjectArray() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - String[] a2 = new String[] { "E", "B" }; - String[] a3 = ArrayTools.removeAll(a1, (Object[]) a2); - assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); - } - - public void testRemoveAllObjectArrayObjectArray_Empty() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - String[] a2 = new String[0]; - String[] a3 = ArrayTools.removeAll(a1, (Object[]) a2); - assertTrue(Arrays.equals(a1, a3)); - } - - public void testRemoveAllObjectArrayObjectArray_NoMatches() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - String[] a2 = new String[] { "X", "Y", "Z" }; - String[] a3 = ArrayTools.removeAll(a1, (Object[]) a2); - assertTrue(Arrays.equals(a1, a3)); - } - - public void testRemoveAllObjectArrayIterable() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); - String[] a3 = ArrayTools.removeAll(a1, iterable); - assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); - } - - public void testRemoveAllObjectArrayIterableInt() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); - String[] a3 = ArrayTools.removeAll(a1, iterable, 7); - assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); - } - - public void testRemoveAllObjectArrayIterator() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); - String[] a3 = ArrayTools.removeAll(a1, iterable.iterator()); - assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); - } - - public void testRemoveAllObjectArrayIterator_Empty() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - String[] a3 = ArrayTools.removeAll(a1, EmptyIterator.instance()); - assertTrue(Arrays.equals(a1, a3)); - } - - public void testRemoveAllObjectArrayIteratorInt() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterable<?> iterable = Arrays.asList(new String[] { "E", "B" }); - String[] a3 = ArrayTools.removeAll(a1, iterable.iterator(), 7); - assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); - } - - public void testRemoveAllObjectArrayIteratorInt_Empty() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - String[] a3 = ArrayTools.removeAll(a1, EmptyIterator.instance(), 7); - assertTrue(Arrays.equals(a1, a3)); - } - - public void testRemoveAllObjectArrayCollection() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Collection<String> collection = Arrays.asList(new String[] { "E", "B" }); - String[] a3 = ArrayTools.removeAll(a1, collection); - assertTrue(Arrays.equals(new String[] { "A", "A", "C", "C", "D", "D", "F", "F" }, a3)); - } - - public void testRemoveAllObjectArrayCollection_Empty() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Collection<String> collection = new ArrayList<String>(); - String[] a3 = ArrayTools.removeAll(a1, collection); - assertTrue(Arrays.equals(a1, a3)); - } - - public void testRemoveAllObjectArrayCollection_EmptyArray() { - String[] a1 = new String[0]; - Collection<String> collection = Arrays.asList(new String[] { "E", "B" }); - String[] a3 = ArrayTools.removeAll(a1, collection); - assertTrue(Arrays.equals(a1, a3)); - assertEquals(0, a3.length); - } - - public void testRemoveAllObjectArrayCollection_NoMatches() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Collection<String> collection = Arrays.asList(new String[] { "X", "Y", "Z" }); - String[] a3 = ArrayTools.removeAll(a1, collection); - assertTrue(Arrays.equals(a1, a3)); - } - - public void testRemoveAllCharArrayCharArray() { - char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; - char[] a2 = new char[] { 'E', 'B' }; - assertTrue(Arrays.equals(new char[] { 'A', 'A', 'C', 'C', 'D', 'D', 'F', 'F' }, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllCharArrayCharArray_Empty1() { - char[] a1 = new char[0]; - char[] a2 = new char[] { 'E', 'B' }; - assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllCharArrayCharArray_Empty2() { - char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; - char[] a2 = new char[0]; - assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllCharArrayCharArray_NoMatches() { - char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; - char[] a2 = new char[] { 'X', 'Z' }; - assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllIntArrayIntArray() { - int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; - int[] a2 = new int[] { 5, 2 }; - assertTrue(Arrays.equals(new int[] { 1, 1, 3, 3, 4, 4, 6, 6 }, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllIntArrayIntArray_Empty1() { - int[] a1 = new int[0]; - int[] a2 = new int[] { 5, 2 }; - assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllIntArrayIntArray_Empty2() { - int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; - int[] a2 = new int[0]; - assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); - } - - public void testRemoveAllIntArrayIntArray_NoMatches() { - int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; - int[] a2 = new int[] { 52, 67 }; - assertTrue(Arrays.equals(a1, ArrayTools.removeAll(a1, a2))); - } - - - // ********** remove all occurrences ********** - - public void testRemoveAllOccurrencesObjectArrayObject() { - String[] a = this.buildStringArray1(); - assertEquals(3, a.length); - a = ArrayTools.removeAllOccurrences(a, "three"); - assertEquals(3, a.length); - a = ArrayTools.removeAllOccurrences(a, "two"); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, "two"); - assertEquals(2, a.length); - - a = ArrayTools.add(a, "five"); - a = ArrayTools.add(a, "five"); - a = ArrayTools.add(a, "five"); - assertEquals(5, a.length); - a = ArrayTools.removeAllOccurrences(a, "five"); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, "five"); - assertEquals(2, a.length); - - a = ArrayTools.add(a, null); - a = ArrayTools.add(a, null); - a = ArrayTools.add(a, null); - assertEquals(5, a.length); - a = ArrayTools.removeAllOccurrences(a, null); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, null); - assertEquals(2, a.length); - } - - public void testRemoveAllOccurrencesObjectArrayObject_Empty() { - String[] a = new String[0]; - a = ArrayTools.removeAllOccurrences(a, "three"); - assertEquals(0, a.length); - } - - public void testRemoveAllOccurrencesCharArrayChar() { - char[] a = this.buildCharArray(); - assertEquals(3, a.length); - a = ArrayTools.removeAllOccurrences(a, 'd'); - assertEquals(3, a.length); - a = ArrayTools.removeAllOccurrences(a, 'b'); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, 'b'); - assertEquals(2, a.length); - - a = ArrayTools.add(a, 'g'); - a = ArrayTools.add(a, 'g'); - a = ArrayTools.add(a, 'g'); - assertEquals(5, a.length); - a = ArrayTools.removeAllOccurrences(a, 'g'); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, 'g'); - assertEquals(2, a.length); - } - - public void testRemoveAllOccurrencesCharArrayChar_Empty() { - char[] a = new char[0]; - a = ArrayTools.removeAllOccurrences(a, 'a'); - assertEquals(0, a.length); - } - - public void testRemoveAllOccurrencesIntArrayInt() { - int[] a = this.buildIntArray(); - assertEquals(3, a.length); - a = ArrayTools.removeAllOccurrences(a, 55); - assertEquals(3, a.length); - a = ArrayTools.removeAllOccurrences(a, 10); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, 10); - assertEquals(2, a.length); - - a = ArrayTools.add(a, 77); - a = ArrayTools.add(a, 77); - a = ArrayTools.add(a, 77); - assertEquals(5, a.length); - a = ArrayTools.removeAllOccurrences(a, 77); - assertEquals(2, a.length); - a = ArrayTools.removeAllOccurrences(a, 77); - assertEquals(2, a.length); - } - - public void testRemoveAllOccurrencesIntArrayInt_Empty() { - int[] a = new int[0]; - a = ArrayTools.removeAllOccurrences(a, 22); - assertEquals(0, a.length); - } - - - // ********** remove duplicate elements ********** - - public void testRemoveDuplicateElementsObjectArray() { - List<String> list = this.buildStringVector1(); - list.add("zero"); - list.add("zero"); - list.add("two"); - list.add("zero"); - String[] array = ArrayTools.removeDuplicateElements(list.toArray(new String[list.size()])); - int i = 0; - assertEquals("zero", array[i++]); - assertEquals("one", array[i++]); - assertEquals("two", array[i++]); - assertEquals(i, array.length); - } - - public void testRemoveDuplicateElementsObjectArray_Empty() { - String[] array = ArrayTools.removeDuplicateElements(new String[0]); - assertEquals(0, array.length); - } - - public void testRemoveDuplicateElementsObjectArray_SingleElement() { - String[] array = ArrayTools.removeDuplicateElements(new String[] { "foo" }); - assertEquals(1, array.length); - } - - public void testRemoveDuplicateElementsObjectArray_NoDuplicates() { - String[] a1 = new String[] { "foo", "bar", "baz" }; - String[] a2 = ArrayTools.removeDuplicateElements(a1); - assertEquals(3, a2.length); - assertTrue(Arrays.equals(a1, a2)); - } - - - // ********** remove element at index ********** - - public void testRemoveElementAtIndexObjectArrayInt() { - String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.removeElementAtIndex(a, 3); - assertTrue(Arrays.equals(new String[] { "A", "B", "A", "A", "D" }, a)); - } - - public void testRemoveElementAtIndexCharArrayInt() { - char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - a = ArrayTools.removeElementAtIndex(a, 3); - assertTrue(Arrays.equals(new char[] { 'A', 'B', 'A', 'A', 'D' }, a)); - } - - public void testRemoveElementAtIndexIntArrayInt() { - int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; - a = ArrayTools.removeElementsAtIndex(a, 3, 3); - assertTrue(Arrays.equals(new int[] { 8, 6, 7 }, a)); - } - - public void testRemoveFirstObjectArray() { - String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.removeFirst(a); - assertTrue(Arrays.equals(new String[] { "B", "A", "C", "A", "D" }, a)); - } - - public void testRemoveFirstCharArray() { - char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - a = ArrayTools.removeFirst(a); - assertTrue(Arrays.equals(new char[] { 'B', 'A', 'C', 'A', 'D' }, a)); - } - - public void testRemoveFirstIntArray() { - int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; - a = ArrayTools.removeFirst(a); - assertTrue(Arrays.equals(new int[] { 6, 7, 33, 2, 11 }, a)); - } - - public void testRemoveLastObjectArray() { - String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.removeLast(a); - assertTrue(Arrays.equals(new String[] { "A", "B", "A", "C", "A" }, a)); - } - - public void testRemoveLastCharArray() { - char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - a = ArrayTools.removeLast(a); - assertTrue(Arrays.equals(new char[] { 'A', 'B', 'A', 'C', 'A' }, a)); - } - - public void testRemoveLastIntArray() { - int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; - a = ArrayTools.removeLast(a); - assertTrue(Arrays.equals(new int[] { 8, 6, 7, 33, 2 }, a)); - } - - - // ********** remove elements at index ********** - - public void testRemoveElementsAtIndexObjectArrayIntInt() { - String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.removeElementsAtIndex(a, 3, 2); - assertTrue(Arrays.equals(new String[] { "A", "B", "A", "D" }, a)); - } - - public void testRemoveElementsAtIndexObjectArrayIntInt_ZeroLength() { - String[] a1 = new String[] { "A", "B", "A", "C", "A", "D" }; - String[] a2 = ArrayTools.removeElementsAtIndex(a1, 3, 0); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testRemoveElementsAtIndexObjectArrayIntInt_Empty() { - String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.removeElementsAtIndex(a, 0, 6); - assertEquals(0, a.length); - } - - public void testRemoveElementsAtIndexCharArrayIntInt() { - char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - a = ArrayTools.removeElementsAtIndex(a, 0, 5); - assertTrue(Arrays.equals(new char[] { 'D' }, a)); - } - - public void testRemoveElementsAtIndexCharArrayIntInt_ZeroLength() { - char[] a1 = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - char[] a2 = ArrayTools.removeElementsAtIndex(a1, 3, 0); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testRemoveElementsAtIndexCharArrayIntInt_Empty() { - char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - a = ArrayTools.removeElementsAtIndex(a, 0, 6); - assertEquals(0, a.length); - } - - public void testRemoveElementsAtIndexIntArrayIntInt() { - int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; - a = ArrayTools.removeElementsAtIndex(a, 3, 3); - assertTrue(Arrays.equals(new int[] { 8, 6, 7 }, a)); - } - - public void testRemoveElementsAtIndexIntArrayIntInt_ZeroLength() { - int[] a1 = new int[] { 8, 6, 7, 33, 2, 11 }; - int[] a2 = ArrayTools.removeElementsAtIndex(a1, 3, 0); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testRemoveElementsAtIndexIntArrayIntInt_Empty() { - int[] a = new int[] { 8, 6, 7, 33, 2, 11 }; - a = ArrayTools.removeElementsAtIndex(a, 0, 6); - assertEquals(0, a.length); - } - - - // ********** replace all ********** - - public void testReplaceAllObjectArrayObjectObject_Object() { - Object[] a = new Object[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.replaceAll(a, "A", "Z"); - assertTrue(Arrays.equals(new Object[] { "Z", "B", "Z", "C", "Z", "D" }, a)); - } - - public void testReplaceAllObjectArrayObjectObject_String() { - String[] a = new String[] { "A", "B", "A", "C", "A", "D" }; - a = ArrayTools.replaceAll(a, "A", "Z"); - assertTrue(Arrays.equals(new String[] { "Z", "B", "Z", "C", "Z", "D" }, a)); - } - - public void testReplaceAllObjectArrayObjectObject_Null() { - String[] a = new String[] { null, "B", null, "C", null, "D" }; - a = ArrayTools.replaceAll(a, null, "Z"); - assertTrue(Arrays.equals(new String[] { "Z", "B", "Z", "C", "Z", "D" }, a)); - } - - public void testReplaceAllCharArrayCharChar() { - char[] a = new char[] { 'A', 'B', 'A', 'C', 'A', 'D' }; - a = ArrayTools.replaceAll(a, 'A', 'Z'); - assertTrue(Arrays.equals(new char[] { 'Z', 'B', 'Z', 'C', 'Z', 'D' }, a)); - } - - public void testReplaceAllIntArrayIntInt() { - int[] a = new int[] { 0, 1, 0, 7, 0, 99 }; - a = ArrayTools.replaceAll(a, 0, 13); - assertTrue(Arrays.equals(new int[] { 13, 1, 13, 7, 13, 99 }, a)); - } - - - // ********** retain all ********** - - public void testRetainAllObjectArrayObjectArray() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Object[] a2 = new Object[] { "E", "B", new Integer(7) }; - assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, a2))); - } - - public void testRetainAllObjectArrayObjectArray_EmptyObjectArray1() { - String[] a1 = new String[0]; - String[] a2 = new String[] { "E", "B", "" }; - String[] a3 = ArrayTools.retainAll(a1, a2); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayObjectArray_EmptyObjectArray2() { - String[] a1 = new String[] { "E", "B", "" }; - String[] a2 = new String[0]; - String[] a3 = ArrayTools.retainAll(a1, a2); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayObjectArray_BothEmpty() { - String[] a1 = new String[0]; - String[] a2 = new String[0]; - String[] a3 = ArrayTools.retainAll(a1, a2); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayIterable() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); - assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterable))); - } - - public void testRetainAllObjectArrayIterable_EmptyObjectArray() { - String[] a1 = new String[0]; - Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); - String[] a3 = ArrayTools.retainAll(a1, iterable); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayIterableInt() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); - assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterable, 3))); - } - - public void testRetainAllObjectArrayIterableInt_EmptyObjectArray() { - String[] a1 = new String[0]; - Iterable<String> iterable = Arrays.asList(new String[] { "E", "B", "" }); - String[] a3 = ArrayTools.retainAll(a1, iterable, 3); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayIterator() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); - assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterator))); - } - - public void testRetainAllObjectArrayIterator_EmptyObjectArray() { - String[] a1 = new String[0]; - Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); - String[] a3 = ArrayTools.retainAll(a1, iterator); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayIterator_EmptyIterator() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - assertTrue(Arrays.equals(new String[0], ArrayTools.retainAll(a1, EmptyIterator.instance()))); - } - - public void testRetainAllObjectArrayIteratorInt() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); - assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, iterator, 3))); - } - - public void testRetainAllObjectArrayIteratorInt_EmptyIterator() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - assertTrue(Arrays.equals(new String[0], ArrayTools.retainAll(a1, EmptyIterator.instance(), 3))); - } - - public void testRetainAllObjectArrayIteratorInt_EmptyObjectArray() { - String[] a1 = new String[0]; - Iterator<String> iterator = Arrays.asList(new String[] { "E", "B", "" }).iterator(); - String[] a3 = ArrayTools.retainAll(a1, iterator, 3); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayCollection() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Collection<String> collection = Arrays.asList(new String[] { "E", "B", "" }); - assertTrue(Arrays.equals(new String[] { "B", "B", "E", "E" }, ArrayTools.retainAll(a1, collection))); - } - - public void testRetainAllObjectArrayCollection_EmptyObjectArray() { - String[] a1 = new String[0]; - Collection<String> collection = Arrays.asList(new String[] { "E", "B", "" }); - String[] a3 = ArrayTools.retainAll(a1, collection); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayCollection_EmptyCollection() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Collection<String> collection = new ArrayList<String>(); - String[] a3 = ArrayTools.retainAll(a1, collection); - assertEquals(0, a3.length); - } - - public void testRetainAllObjectArrayCollection_All() { - String[] a1 = new String[] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }; - Collection<String> collection = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" }); - assertTrue(Arrays.equals(a1, ArrayTools.retainAll(a1, collection))); - } - - public void testRetainAllCharArrayCharArray() { - char[] a1 = new char[] { 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F' }; - char[] a2 = new char[] { 'E', 'B' }; - assertTrue(Arrays.equals(new char[] { 'B', 'B', 'E', 'E' }, ArrayTools.retainAll(a1, a2))); - } - - public void testRetainAllCharArrayCharArray_EmptyCharArray1() { - char[] a1 = new char[0]; - char[] a2 = new char[] { 'E', 'B' }; - assertSame(a1, ArrayTools.retainAll(a1, a2)); - } - - public void testRetainAllCharArrayCharArray_EmptyCharArray2() { - char[] a1 = new char[] { 'E', 'B' }; - char[] a2 = new char[0]; - assertEquals(0, ArrayTools.retainAll(a1, a2).length); - } - - public void testRetainAllCharArrayCharArray_RetainAll() { - char[] a1 = new char[] { 'E', 'B', 'E', 'B', 'E', 'B', 'E', 'B', 'E' }; - char[] a2 = new char[] { 'E', 'B' }; - assertSame(a1, ArrayTools.retainAll(a1, a2)); - } - - public void testRetainAllIntArrayIntArray() { - int[] a1 = new int[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6 }; - int[] a2 = new int[] { 5, 2 }; - assertTrue(Arrays.equals(new int[] { 2, 2, 5, 5 }, ArrayTools.retainAll(a1, a2))); - } - - public void testRetainAllIntArrayIntArray_EmptyIntArray1() { - int[] a1 = new int[0]; - int[] a2 = new int[] { 5, 2 }; - assertSame(a1, ArrayTools.retainAll(a1, a2)); - } - - public void testRetainAllIntArrayIntArray_EmptyIntArray2() { - int[] a1 = new int[] { 5, 2 }; - int[] a2 = new int[0]; - assertEquals(0, ArrayTools.retainAll(a1, a2).length); - } - - public void testRetainAllIntArrayIntArray_RetainAll() { - int[] a1 = new int[] { 5, 2, 5, 2, 5, 2, 5, 2, 5, 2, 5 }; - int[] a2 = new int[] { 5, 2 }; - assertSame(a1, ArrayTools.retainAll(a1, a2)); - } - - - // ********** reverse ********** - - public void testReverseObjectArray_Object() { - Object[] a = this.buildObjectArray1(); - a = ArrayTools.reverse(a); - assertEquals("two", a[0]); - assertEquals("one", a[1]); - assertEquals("zero", a[2]); - } - - public void testReverseObjectArray_String() { - String[] a = this.buildStringArray1(); - a = ArrayTools.reverse(a); - assertEquals("two", a[0]); - assertEquals("one", a[1]); - assertEquals("zero", a[2]); - } - - public void testReverseObjectArray_Singleton() { - String[] a1 = new String[] { "foo" }; - String[] a2 = ArrayTools.reverse(a1); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testReverseCharArray() { - char[] a = this.buildCharArray(); - a = ArrayTools.reverse(a); - assertEquals('c', a[0]); - assertEquals('b', a[1]); - assertEquals('a', a[2]); - } - - public void testReverseCharArray_Singleton() { - char[] a1 = new char[] { 'f' }; - char[] a2 = ArrayTools.reverse(a1); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testReverseIntArray() { - int[] a = this.buildIntArray(); - a = ArrayTools.reverse(a); - assertEquals(20, a[0]); - assertEquals(10, a[1]); - assertEquals(0, a[2]); - } - - public void testReverseIntArray_Singleton() { - int[] a1 = new int[] { 7 }; - int[] a2 = ArrayTools.reverse(a1); - assertTrue(Arrays.equals(a1, a2)); - } - - - // ********** rotate ********** - - public void testRotateObjectArray() { - String[] a = this.buildStringArray1(); - a = ArrayTools.rotate(a); - assertEquals("two", a[0]); - assertEquals("zero", a[1]); - assertEquals("one", a[2]); - } - - public void testRotateObjectArray_Zero() { - String[] a1 = new String[0]; - String[] a2 = ArrayTools.rotate(a1); - assertSame(a1, a2); - } - - public void testRotateObjectArray_One() { - String[] a1 = new String[] { "foo " }; - String[] a2 = ArrayTools.rotate(a1); - assertSame(a1, a2); - } - - public void testRotateObjectArrayInt() { - String[] a = this.buildStringArray1(); - a = ArrayTools.rotate(a, 2); - assertEquals("one", a[0]); - assertEquals("two", a[1]); - assertEquals("zero", a[2]); - } - - public void testRotateObjectArrayInt_ZeroDistance() { - String[] a1 = this.buildStringArray1(); - String[] a2 = ArrayTools.rotate(a1, 0); - assertSame(a1, a2); - } - - public void testRotateObjectArrayInt_NegativeDistance() { - String[] a1 = this.buildStringArray1(); - String[] a2 = ArrayTools.rotate(a1, -1); - assertEquals("one", a2[0]); - assertEquals("two", a2[1]); - assertEquals("zero", a2[2]); - } - - public void testRotateObjectArrayInt_Zero() { - String[] a1 = new String[0]; - String[] a2 = ArrayTools.rotate(a1, 7); - assertSame(a1, a2); - } - - public void testRotateObjectArrayInt_One() { - String[] a1 = new String[] { "foo " }; - String[] a2 = ArrayTools.rotate(a1, 8); - assertSame(a1, a2); - } - - public void testRotateCharArray() { - char[] a = this.buildCharArray(); - a = ArrayTools.rotate(a); - assertEquals('c', a[0]); - assertEquals('a', a[1]); - assertEquals('b', a[2]); - } - - public void testRotateCharArray_Zero() { - char[] a1 = new char[0]; - char[] a2 = ArrayTools.rotate(a1); - assertSame(a1, a2); - } - - public void testRotateCharArray_One() { - char[] a1 = new char[] { 'a' }; - char[] a2 = ArrayTools.rotate(a1); - assertSame(a1, a2); - } - - public void testRotateCharArrayInt() { - char[] a = this.buildCharArray(); - a = ArrayTools.rotate(a, 2); - assertEquals('b', a[0]); - assertEquals('c', a[1]); - assertEquals('a', a[2]); - } - - public void testRotateCharArrayInt_ZeroDistance() { - char[] a1 = new char[] { 'a', 'b', 'c' }; - char[] a2 = ArrayTools.rotate(a1, 0); - assertSame(a1, a2); - } - - public void testRotateCharArrayInt_NegativeDistance() { - char[] a = this.buildCharArray(); - a = ArrayTools.rotate(a, -1); - assertEquals('b', a[0]); - assertEquals('c', a[1]); - assertEquals('a', a[2]); - } - - public void testRotateCharArrayInt_Zero() { - char[] a1 = new char[0]; - char[] a2 = ArrayTools.rotate(a1, 2001); - assertSame(a1, a2); - } - - public void testRotateCharArrayInt_One() { - char[] a1 = new char[] { 'a' }; - char[] a2 = ArrayTools.rotate(a1, 22); - assertSame(a1, a2); - } - - public void testRotateIntArray() { - int[] a = this.buildIntArray(); - a = ArrayTools.rotate(a); - assertEquals(20, a[0]); - assertEquals(0, a[1]); - assertEquals(10, a[2]); - } - - public void testRotateIntArray_Zero() { - int[] a1 = new int[0]; - int[] a2 = ArrayTools.rotate(a1); - assertSame(a1, a2); - } - - public void testRotateIntArray_One() { - int[] a1 = new int[] { 77 }; - int[] a2 = ArrayTools.rotate(a1); - assertSame(a1, a2); - } - - public void testRotateIntArrayInt() { - int[] a = this.buildIntArray(); - a = ArrayTools.rotate(a, 2); - assertEquals(10, a[0]); - assertEquals(20, a[1]); - assertEquals(0, a[2]); - } - - public void testRotateIntArrayInt_ZeroDistance() { - int[] a1 = new int[] { 3, 2, 1 }; - int[] a2 = ArrayTools.rotate(a1, 0); - assertSame(a1, a2); - } - - public void testRotateIntArrayInt_NegativeDistance() { - int[] a = this.buildIntArray(); - a = ArrayTools.rotate(a, -1); - assertEquals(10, a[0]); - assertEquals(20, a[1]); - assertEquals(0, a[2]); - } - - public void testRotateIntArrayInt_Zero() { - int[] a1 = new int[0]; - int[] a2 = ArrayTools.rotate(a1, 3); - assertSame(a1, a2); - } - - public void testRotateIntArrayInt_One() { - int[] a1 = new int[] { 77 }; - int[] a2 = ArrayTools.rotate(a1, 44); - assertSame(a1, a2); - } - - - // ********** shuffle ********** - - public void testShuffleObjectArray() { - String[] array1 = this.buildStringArray1(); - String[] array2 = ArrayTools.shuffle(this.buildStringArray1()); - assertEquals(array1.length, array2.length); - assertTrue(ArrayTools.containsAll(array1, (Object[]) array2)); - } - - public void testShuffleObjectArray_Singleton() { - String[] array1 = new String[] { "foo" }; - String[] array2 = ArrayTools.shuffle(new String[] { "foo" }); - assertEquals(array1.length, array2.length); - assertTrue(ArrayTools.containsAll(array1, (Object[]) array2)); - } - - public void testShuffleCharArray() { - char[] array1 = this.buildCharArray(); - char[] array2 = ArrayTools.shuffle(this.buildCharArray()); - assertEquals(array1.length, array2.length); - assertTrue(ArrayTools.containsAll(array1, array2)); - } - - public void testShuffleCharArray_Singleton() { - char[] array1 = new char[] { 'f' }; - char[] array2 = ArrayTools.shuffle(new char[] { 'f' }); - assertEquals(array1.length, array2.length); - assertTrue(ArrayTools.containsAll(array1, array2)); - } - - public void testShuffleIntArray() { - int[] array1 = this.buildIntArray(); - int[] array2 = ArrayTools.shuffle(this.buildIntArray()); - assertEquals(array1.length, array2.length); - assertTrue(ArrayTools.containsAll(array1, array2)); - } - - public void testShuffleIntArray_Singleton() { - int[] array1 = new int[] { 7 }; - int[] array2 = ArrayTools.shuffle(new int[] { 7 }); - assertEquals(array1.length, array2.length); - assertTrue(ArrayTools.containsAll(array1, array2)); - } - - - // ********** sub-array ********** - - public void testSubArrayObjectArrayIntInt() { - String[] array = new String[] {"foo", "bar", "baz", "joo", "jar", "jaz"}; - String[] result = new String[] {"foo", "bar", "baz", "joo"}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 0, 4))); - - result = new String[] {"jar"}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 4, 5))); - - result = new String[0]; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 5, 5))); - - result = new String[] {"joo", "jar", "jaz"}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 3, 6))); - } - - public void testSubArrayIntArrayIntInt() { - int[] array = new int[] {77, 99, 333, 4, 9090, 42}; - int[] result = new int[] {77, 99, 333, 4}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 0, 4))); - - result = new int[] {9090}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 4, 5))); - - result = new int[0]; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 5, 5))); - - result = new int[] {4, 9090, 42}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 3, 6))); - } - - public void testSubArrayCharArrayIntInt() { - char[] array = new char[] {'a', 'b', 'c', 'd', 'e', 'f'}; - char[] result = new char[] {'a', 'b', 'c', 'd'}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 0, 4))); - - result = new char[] {'e'}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 4, 5))); - - result = new char[0]; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 5, 5))); - - result = new char[] {'d', 'e', 'f'}; - assertTrue(Arrays.equals(result, ArrayTools.subArray(array, 3, 6))); - } - - - // ********** swap ********** - - public void testSwapObjectArray() { - String[] a = this.buildStringArray1(); - a = ArrayTools.swap(a, 1, 2); - assertEquals("zero", a[0]); - assertEquals("two", a[1]); - assertEquals("one", a[2]); - } - - public void testSwapObjectArray_SameIndices() { - String[] a1 = this.buildStringArray1(); - String[] a2 = this.buildStringArray1(); - a1 = ArrayTools.swap(a1, 1, 1); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testSwapCharArray() { - char[] a = this.buildCharArray(); - a = ArrayTools.swap(a, 1, 2); - assertEquals('a', a[0]); - assertEquals('c', a[1]); - assertEquals('b', a[2]); - } - - public void testSwapCharArray_SameIndices() { - char[] a1 = this.buildCharArray(); - char[] a2 = this.buildCharArray(); - a1 = ArrayTools.swap(a1, 1, 1); - assertTrue(Arrays.equals(a1, a2)); - } - - public void testSwapIntArray() { - int[] a = this.buildIntArray(); - a = ArrayTools.swap(a, 1, 2); - assertEquals(0, a[0]); - assertEquals(20, a[1]); - assertEquals(10, a[2]); - } - - public void testSwapIntArray_SameIndices() { - int[] a1 = this.buildIntArray(); - int[] a2 = this.buildIntArray(); - a1 = ArrayTools.swap(a1, 1, 1); - assertTrue(Arrays.equals(a1, a2)); - } - - - // ********** Arrays enhancements ********** - - public void testFillBooleanArrayBoolean() { - boolean[] a1 = new boolean[9]; - boolean[] a2 = ArrayTools.fill(a1, true); - for (boolean x : a1) { - assertTrue(x); - } - assertSame(a1, a2); - } - - public void testFillBooleanArrayIntIntBoolean() { - boolean[] a1 = new boolean[9]; - boolean[] a2 = ArrayTools.fill(a1, false); - int from = 3; - int to = 6; - boolean[] a3 = ArrayTools.fill(a2, from, to, true); - for (int i = 0; i < a1.length; i++) { - boolean x = a1[i]; - if (i < from || i >= to) { - assertFalse(x); - } else { - assertTrue(x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillByteArrayByte() { - byte[] a1 = new byte[9]; - byte[] a2 = ArrayTools.fill(a1, (byte) 77); - for (byte x : a1) { - assertEquals(77, x); - } - assertSame(a1, a2); - } - - public void testFillByteArrayIntIntByte() { - byte[] a1 = new byte[9]; - byte[] a2 = ArrayTools.fill(a1, (byte) 3); - int from = 3; - int to = 6; - byte[] a3 = ArrayTools.fill(a2, from, to, (byte) 77); - for (int i = 0; i < a1.length; i++) { - byte x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertEquals(77, x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillCharArrayChar() { - char[] a1 = new char[9]; - char[] a2 = ArrayTools.fill(a1, 'c'); - for (char x : a1) { - assertEquals('c', x); - } - assertSame(a1, a2); - } - - public void testFillCharArrayIntIntChar() { - char[] a1 = new char[9]; - char[] a2 = ArrayTools.fill(a1, 'a'); - int from = 3; - int to = 6; - char[] a3 = ArrayTools.fill(a2, from, to, 'c'); - for (int i = 0; i < a1.length; i++) { - char x = a1[i]; - if (i < from || i >= to) { - assertEquals('a', x); - } else { - assertEquals('c', x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillDoubleArrayDouble() { - double[] a1 = new double[9]; - double[] a2 = ArrayTools.fill(a1, 77.77); - for (double x : a1) { - assertEquals(77.77, x, 0.0); - } - assertSame(a1, a2); - } - - public void testFillDoubleArrayIntIntDouble() { - double[] a1 = new double[9]; - double[] a2 = ArrayTools.fill(a1, 3.3); - int from = 3; - int to = 6; - double[] a3 = ArrayTools.fill(a2, from, to, 77.77); - for (int i = 0; i < a1.length; i++) { - double x = a1[i]; - if (i < from || i >= to) { - assertEquals(3.3, x, 0.0); - } else { - assertEquals(77.77, x, 0.0); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillFloatArrayFloat() { - float[] a1 = new float[9]; - float[] a2 = ArrayTools.fill(a1, 77.77f); - for (float x : a1) { - assertEquals(77.77f, x, 0.0); - } - assertSame(a1, a2); - } - - public void testFillFloatArrayIntIntFloat() { - float[] a1 = new float[9]; - float[] a2 = ArrayTools.fill(a1, 3.3f); - int from = 3; - int to = 6; - float[] a3 = ArrayTools.fill(a2, from, to, 77.77f); - for (int i = 0; i < a1.length; i++) { - float x = a1[i]; - if (i < from || i >= to) { - assertEquals(3.3f, x, 0.0); - } else { - assertEquals(77.77f, x, 0.0); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillIntArrayInt() { - int[] a1 = new int[9]; - int[] a2 = ArrayTools.fill(a1, 77); - for (int x : a1) { - assertEquals(77, x); - } - assertSame(a1, a2); - } - - public void testFillIntArrayIntIntInt() { - int[] a1 = new int[9]; - int[] a2 = ArrayTools.fill(a1, 3); - int from = 3; - int to = 6; - int[] a3 = ArrayTools.fill(a2, from, to, 77); - for (int i = 0; i < a1.length; i++) { - int x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertEquals(77, x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillObjectArrayObject() { - String[] a1 = new String[9]; - String[] a2 = ArrayTools.fill(a1, "77"); - for (String x : a1) { - assertEquals("77", x); - } - assertSame(a1, a2); - } - - public void testFillObjectArrayIntIntObject() { - String[] a1 = new String[9]; - String[] a2 = ArrayTools.fill(a1, "3"); - int from = 3; - int to = 6; - String[] a3 = ArrayTools.fill(a2, from, to, "77"); - for (int i = 0; i < a1.length; i++) { - String x = a1[i]; - if (i < from || i >= to) { - assertEquals("3", x); - } else { - assertEquals("77", x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillLongArrayLong() { - long[] a1 = new long[9]; - long[] a2 = ArrayTools.fill(a1, 77); - for (long x : a1) { - assertEquals(77, x); - } - assertSame(a1, a2); - } - - public void testFillLongArrayIntIntLong() { - long[] a1 = new long[9]; - long[] a2 = ArrayTools.fill(a1, 3); - int from = 3; - int to = 6; - long[] a3 = ArrayTools.fill(a2, from, to, 77); - for (int i = 0; i < a1.length; i++) { - long x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertEquals(77, x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testFillShortArrayShort() { - short[] a1 = new short[9]; - short[] a2 = ArrayTools.fill(a1, (short) 77); - for (short x : a1) { - assertEquals(77, x); - } - assertSame(a1, a2); - } - - public void testFillShortArrayIntIntShort() { - short[] a1 = new short[9]; - short[] a2 = ArrayTools.fill(a1, (short) 3); - int from = 3; - int to = 6; - short[] a3 = ArrayTools.fill(a2, from, to, (short) 77); - for (int i = 0; i < a1.length; i++) { - short x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertEquals(77, x); - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortByteArray() { - byte[] a1 = new byte[3]; - a1[0] = (byte) 33; - a1[1] = (byte) 11; - a1[2] = (byte) 22; - byte[] a2 = ArrayTools.sort(a1); - byte last = (byte) 0; - for (byte x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortByteArrayIntInt() { - byte[] a1 = new byte[9]; - byte[] a2 = ArrayTools.fill(a1, (byte) 3); - a2[3] = (byte) 33; - a2[4] = (byte) 11; - a2[5] = (byte) 22; - int from = 3; - int to = 6; - byte[] a3 = ArrayTools.sort(a2, from, to); - byte last = (byte) 0; - for (int i = 0; i < a1.length; i++) { - byte x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortCharArray() { - char[] a1 = new char[3]; - a1[0] = 'z'; - a1[1] = 'b'; - a1[2] = 'm'; - char[] a2 = ArrayTools.sort(a1); - char last = 'a'; - for (char x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortCharArrayIntInt() { - char[] a1 = new char[9]; - char[] a2 = ArrayTools.fill(a1, 'c'); - a2[3] = 'z'; - a2[4] = 'b'; - a2[5] = 'm'; - int from = 3; - int to = 6; - char[] a3 = ArrayTools.sort(a2, from, to); - char last = 'a'; - for (int i = 0; i < a1.length; i++) { - char x = a1[i]; - if (i < from || i >= to) { - assertEquals('c', x); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortDoubleArray() { - double[] a1 = new double[3]; - a1[0] = 33.33; - a1[1] = 11.11; - a1[2] = 22.22; - double[] a2 = ArrayTools.sort(a1); - double last = 0; - for (double x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortDoubleArrayIntInt() { - double[] a1 = new double[9]; - double[] a2 = ArrayTools.fill(a1, 3.3); - a2[3] = 33.33; - a2[4] = 11.11; - a2[5] = 22.22; - int from = 3; - int to = 6; - double[] a3 = ArrayTools.sort(a2, from, to); - double last = 0; - for (int i = 0; i < a1.length; i++) { - double x = a1[i]; - if (i < from || i >= to) { - assertEquals(3.3, x, 0.0); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortFloatArray() { - float[] a1 = new float[3]; - a1[0] = 33.33f; - a1[1] = 11.11f; - a1[2] = 22.22f; - float[] a2 = ArrayTools.sort(a1); - float last = 0; - for (float x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortFloatArrayIntInt() { - float[] a1 = new float[9]; - float[] a2 = ArrayTools.fill(a1, 3.3f); - a2[3] = 33.33f; - a2[4] = 11.11f; - a2[5] = 22.22f; - int from = 3; - int to = 6; - float[] a3 = ArrayTools.sort(a2, from, to); - float last = 0; - for (int i = 0; i < a1.length; i++) { - float x = a1[i]; - if (i < from || i >= to) { - assertEquals(3.3f, x, 0.0); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortIntArray() { - int[] a1 = new int[3]; - a1[0] = 33; - a1[1] = 11; - a1[2] = 22; - int[] a2 = ArrayTools.sort(a1); - int last = 0; - for (int x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortIntArrayIntInt() { - int[] a1 = new int[9]; - int[] a2 = ArrayTools.fill(a1, 3); - a2[3] = 33; - a2[4] = 11; - a2[5] = 22; - int from = 3; - int to = 6; - int[] a3 = ArrayTools.sort(a2, from, to); - int last = 0; - for (int i = 0; i < a1.length; i++) { - int x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortObjectArray() { - String[] a1 = new String[3]; - a1[0] = "y"; - a1[1] = "b"; - a1[2] = "m"; - String[] a2 = ArrayTools.sort(a1); - String last = "a"; - for (String x : a1) { - assertTrue(last.compareTo(x) < 0); - last = x; - } - assertSame(a1, a2); - } - - public void testSortObjectArrayComparator() { - String[] a1 = new String[3]; - a1[0] = "y"; - a1[1] = "b"; - a1[2] = "m"; - String[] a2 = ArrayTools.sort(a1, new ReverseComparator<String>()); - String last = "z"; - for (String x : a1) { - assertTrue(last.compareTo(x) > 0); - last = x; - } - assertSame(a1, a2); - } - - public void testSortObjectArrayIntInt() { - String[] a1 = new String[9]; - String[] a2 = ArrayTools.fill(a1, "c"); - a2[3] = "y"; - a2[4] = "b"; - a2[5] = "m"; - int from = 3; - int to = 6; - String[] a3 = ArrayTools.sort(a2, from, to); - String last = "a"; - for (int i = 0; i < a1.length; i++) { - String x = a1[i]; - if (i < from || i >= to) { - assertEquals("c", x); - } else { - assertTrue(last.compareTo(x) < 0); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortObjectArrayIntIntComparator() { - String[] a1 = new String[9]; - String[] a2 = ArrayTools.fill(a1, "c"); - a2[3] = "y"; - a2[4] = "b"; - a2[5] = "m"; - int from = 3; - int to = 6; - String[] a3 = ArrayTools.sort(a2, from, to, new ReverseComparator<String>()); - String last = "z"; - for (int i = 0; i < a1.length; i++) { - String x = a1[i]; - if (i < from || i >= to) { - assertEquals("c", x); - } else { - assertTrue(last.compareTo(x) > 0); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortLongArray() { - long[] a1 = new long[3]; - a1[0] = 33; - a1[1] = 11; - a1[2] = 22; - long[] a2 = ArrayTools.sort(a1); - long last = 0; - for (long x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortLongArrayIntInt() { - long[] a1 = new long[9]; - long[] a2 = ArrayTools.fill(a1, 3); - a2[3] = 33; - a2[4] = 11; - a2[5] = 22; - int from = 3; - int to = 6; - long[] a3 = ArrayTools.sort(a2, from, to); - long last = 0; - for (int i = 0; i < a1.length; i++) { - long x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - public void testSortShortArray() { - short[] a1 = new short[3]; - a1[0] = (short) 33; - a1[1] = (short) 11; - a1[2] = (short) 22; - short[] a2 = ArrayTools.sort(a1); - short last = (short) 0; - for (short x : a1) { - assertTrue(last < x); - last = x; - } - assertSame(a1, a2); - } - - public void testSortShortArrayIntInt() { - short[] a1 = new short[9]; - short[] a2 = ArrayTools.fill(a1, (short) 3); - a2[3] = (short) 33; - a2[4] = (short) 11; - a2[5] = (short) 22; - int from = 3; - int to = 6; - short[] a3 = ArrayTools.sort(a2, from, to); - short last = (short) 0; - for (int i = 0; i < a1.length; i++) { - short x = a1[i]; - if (i < from || i >= to) { - assertEquals(3, x); - } else { - assertTrue(last < x); - last = x; - } - } - assertSame(a1, a2); - assertSame(a1, a3); - } - - - // ********** constructor ********** - - public void testConstructor() { - boolean exCaught = false; - try { - Object at = ReflectionTools.newInstance(ArrayTools.class); - fail("bogus: " + at); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InvocationTargetException) { - if (ex.getCause().getCause() instanceof UnsupportedOperationException) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - - // ********** utility ********** - - private Object[] buildObjectArray1() { - return new Object[] { "zero", "one", "two" }; - } - - private String[] buildStringArray1() { - return new String[] { "zero", "one", "two" }; - } - - private char[] buildCharArray() { - return new char[] { 'a', 'b', 'c' }; - } - - private int[] buildIntArray() { - return new int[] { 0, 10, 20 }; - } - - private Object[] buildObjectArray2() { - return new Object[] { "three", "four", "five" }; - } - - private String[] buildStringArray2() { - return new String[] { "three", "four", "five" }; - } - - private List<String> buildStringList1() { - List<String> l = new ArrayList<String>(); - this.addToCollection1(l); - return l; - } - - private List<Object> buildObjectList1() { - List<Object> l = new ArrayList<Object>(); - this.addToCollection1(l); - return l; - } - - private void addToCollection1(Collection<? super String> c) { - c.add("zero"); - c.add("one"); - c.add("two"); - } - - private List<String> buildStringList2() { - List<String> l = new ArrayList<String>(); - this.addToCollection2(l); - return l; - } - - private void addToCollection2(Collection<? super String> c) { - c.add("three"); - c.add("four"); - c.add("five"); - } - - private Vector<String> buildStringVector1() { - Vector<String> v = new Vector<String>(); - this.addToCollection1(v); - return v; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BagTests.java deleted file mode 100644 index e018dfaeea..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BagTests.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; - -@SuppressWarnings("nls") -public class BagTests extends TestCase { - - public BagTests(String name) { - super(name); - } - - public void testEmptyBag_iterator() throws Exception { - assertFalse(Bag.Empty.instance().iterator().hasNext()); - } - - public void testEmptyBag_size() throws Exception { - assertEquals(0, Bag.Empty.instance().size()); - } - - public void testEmptyBag_uniqueIterator() throws Exception { - assertFalse(Bag.Empty.instance().uniqueIterator().hasNext()); - } - - public void testEmptyBag_uniqueCount() throws Exception { - assertEquals(0, Bag.Empty.instance().uniqueCount()); - } - - public void testEmptyBag_count() throws Exception { - assertEquals(0, Bag.Empty.instance().count("foo")); - } - - public void testEmptyBag_entries() throws Exception { - assertFalse(Bag.Empty.instance().entries().hasNext()); - } - - public void testEmptyBag_remove() throws Exception { - assertFalse(Bag.Empty.instance().remove("foo", 3)); - } - - public void testEmptyBag_add() throws Exception { - boolean exCaught = false; - try { - Bag.Empty.instance().add("foo", 3); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testEmptyBag_equals() throws Exception { - assertTrue(Bag.Empty.instance().equals(Bag.Empty.instance())); - assertFalse(Bag.Empty.instance().equals("foo")); - - Bag<Object> bag = new HashBag<Object>(); - assertTrue(Bag.Empty.instance().equals(bag)); - bag.add("foo"); - assertFalse(Bag.Empty.instance().equals(bag)); - } - - public void testEmptyBag_hashCode() throws Exception { - assertEquals(0, Bag.Empty.instance().hashCode()); - } - - public void testEmptyBag_serialization() throws Exception { - Bag<?> xxx = TestTools.serialize(Bag.Empty.instance()); - assertSame(Bag.Empty.instance(), xxx); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiFilterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiFilterTests.java deleted file mode 100644 index b2d1564479..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiFilterTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.BidiFilter; - -@SuppressWarnings("nls") -public class BidiFilterTests extends TestCase { - - public BidiFilterTests(String name) { - super(name); - } - - public void testNullBidiFilter_accept() throws Exception { - assertTrue(BidiFilter.Null.instance().accept("foo")); - } - - public void testNullBidiFilter_reverseAccept() throws Exception { - assertTrue(BidiFilter.Null.instance().reverseAccept("foo")); - } - - public void testNullBidiFilter_toString() throws Exception { - assertNotNull(BidiFilter.Null.instance().toString()); - } - - public void testNullBidiFilter_serialization() throws Exception { - BidiFilter<?> xxx = TestTools.serialize(BidiFilter.Null.instance()); - assertSame(BidiFilter.Null.instance(), xxx); - } - - public void testOpaqueBidiFilter_accept() throws Exception { - assertFalse(BidiFilter.Opaque.instance().accept("foo")); - } - - public void testOpaqueBidiFilter_reverseAccept() throws Exception { - assertFalse(BidiFilter.Opaque.instance().reverseAccept("foo")); - } - - public void testOpaqueBidiFilter_toString() throws Exception { - assertNotNull(BidiFilter.Opaque.instance().toString()); - } - - public void testOpaqueBidiFilter_serialization() throws Exception { - BidiFilter<?> xxx = TestTools.serialize(BidiFilter.Opaque.instance()); - assertSame(BidiFilter.Opaque.instance(), xxx); - } - - public void testDisabledBidiFilter_accept() throws Exception { - boolean exCaught = false; - try { - BidiFilter.Disabled.instance().accept("foo"); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledBidiFilter_reverseAccept() throws Exception { - boolean exCaught = false; - try { - BidiFilter.Disabled.instance().reverseAccept("foo"); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledBidiFilter_toString() throws Exception { - assertNotNull(BidiFilter.Disabled.instance().toString()); - } - - public void testDisabledBidiFilter_serialization() throws Exception { - BidiFilter<?> xxx = TestTools.serialize(BidiFilter.Disabled.instance()); - assertSame(BidiFilter.Disabled.instance(), xxx); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiStringConverterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiStringConverterTests.java deleted file mode 100644 index cf0400b104..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiStringConverterTests.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.BidiStringConverter; - -@SuppressWarnings("nls") -public class BidiStringConverterTests extends TestCase { - - public BidiStringConverterTests(String name) { - super(name); - } - - public void testDefaultBidiStringConverter_convertToString() throws Exception { - assertEquals("foo", BidiStringConverter.Default.instance().convertToString("foo")); - assertNull(BidiStringConverter.Default.instance().convertToString(null)); - } - - public void testDefaultBidiStringConverter_convertToObject() throws Exception { - assertEquals("foo", BidiStringConverter.Default.instance().convertToObject("foo")); - assertNull(BidiStringConverter.Default.instance().convertToString(null)); - } - - public void testDefaultBidiStringConverter_toString() throws Exception { - assertNotNull(BidiStringConverter.Default.instance().toString()); - } - - public void testDefaultBidiStringConverter_serialization() throws Exception { - BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.Default.instance()); - assertSame(BidiStringConverter.Default.instance(), xxx); - } - - public void testDisabledBidiStringConverter_convertToString() throws Exception { - boolean exCaught = false; - try { - BidiStringConverter.Disabled.instance().convertToString("foo"); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledBidiStringConverter_convertToObject() throws Exception { - boolean exCaught = false; - try { - BidiStringConverter.Disabled.instance().convertToObject("foo"); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledBidiStringConverter_toString() throws Exception { - assertNotNull(BidiStringConverter.Disabled.instance().toString()); - } - - public void testDisabledBidiStringConverter_serialization() throws Exception { - BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.Disabled.instance()); - assertSame(BidiStringConverter.Disabled.instance(), xxx); - } - - public void testBooleanBidiStringConverter_convertToString() throws Exception { - assertEquals("true", BidiStringConverter.BooleanConverter.instance().convertToString(Boolean.TRUE)); - assertEquals("false", BidiStringConverter.BooleanConverter.instance().convertToString(Boolean.FALSE)); - assertNull(BidiStringConverter.BooleanConverter.instance().convertToString(null)); - } - - public void testBooleanBidiStringConverter_convertToObject() throws Exception { - assertEquals(Boolean.TRUE, BidiStringConverter.BooleanConverter.instance().convertToObject("true")); - assertEquals(Boolean.TRUE, BidiStringConverter.BooleanConverter.instance().convertToObject("TRUE")); - assertEquals(Boolean.FALSE, BidiStringConverter.BooleanConverter.instance().convertToObject("false")); - assertEquals(Boolean.FALSE, BidiStringConverter.BooleanConverter.instance().convertToObject("xxxx")); - assertNull(BidiStringConverter.BooleanConverter.instance().convertToObject(null)); - } - - public void testBooleanBidiStringConverter_toString() throws Exception { - assertNotNull(BidiStringConverter.BooleanConverter.instance().toString()); - } - - public void testBooleanBidiStringConverter_serialization() throws Exception { - BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.BooleanConverter.instance()); - assertSame(BidiStringConverter.BooleanConverter.instance(), xxx); - } - - public void testIntegerBidiStringConverter_convertToString() throws Exception { - assertEquals("7", BidiStringConverter.IntegerConverter.instance().convertToString(Integer.valueOf(7))); - assertNull(BidiStringConverter.IntegerConverter.instance().convertToString(null)); - } - - public void testIntegerBidiStringConverter_convertToObject() throws Exception { - assertEquals(Integer.valueOf(7), BidiStringConverter.IntegerConverter.instance().convertToObject("7")); - assertNull(BidiStringConverter.IntegerConverter.instance().convertToObject(null)); - } - - public void testIntegerBidiStringConverter_toString() throws Exception { - assertNotNull(BidiStringConverter.IntegerConverter.instance().toString()); - } - - public void testIntegerBidiStringConverter_serialization() throws Exception { - BidiStringConverter<?> xxx = TestTools.serialize(BidiStringConverter.IntegerConverter.instance()); - assertSame(BidiStringConverter.IntegerConverter.instance(), xxx); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiTransformerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiTransformerTests.java deleted file mode 100644 index 973f153f45..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BidiTransformerTests.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.BidiTransformer; - -@SuppressWarnings("nls") -public class BidiTransformerTests extends TestCase { - - public BidiTransformerTests(String name) { - super(name); - } - - public void testNullBidiTransformer_transform() throws Exception { - assertEquals("foo", BidiTransformer.Null.instance().transform("foo")); - assertNull(BidiTransformer.Null.instance().transform(null)); - } - - public void testNullBidiTransformer_reverseTransform() throws Exception { - assertEquals("foo", BidiTransformer.Null.instance().reverseTransform("foo")); - assertNull(BidiTransformer.Null.instance().transform(null)); - } - - public void testNullBidiTransformer_toString() throws Exception { - assertNotNull(BidiTransformer.Null.instance().toString()); - } - - public void testNullBidiTransformer_serialization() throws Exception { - BidiTransformer<?, ?> xxx = TestTools.serialize(BidiTransformer.Null.instance()); - assertSame(BidiTransformer.Null.instance(), xxx); - } - - public void testDisabledBidiTransformer_transform() throws Exception { - boolean exCaught = false; - try { - BidiTransformer.Disabled.instance().transform("foo"); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledBidiTransformer_reverseTransform() throws Exception { - boolean exCaught = false; - try { - BidiTransformer.Disabled.instance().reverseTransform("foo"); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledBidiTransformer_toString() throws Exception { - assertNotNull(BidiTransformer.Disabled.instance().toString()); - } - - public void testDisabledBidiTransformer_serialization() throws Exception { - BidiTransformer<?, ?> xxx = TestTools.serialize(BidiTransformer.Disabled.instance()); - assertSame(BidiTransformer.Disabled.instance(), xxx); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BitToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BitToolsTests.java deleted file mode 100644 index dd1941237b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BitToolsTests.java +++ /dev/null @@ -1,262 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.InvocationTargetException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.BitTools; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; - -public class BitToolsTests extends TestCase { - - public BitToolsTests(String name) { - super(name); - } - - public void testFlagIsSetIntInt() { - assertTrue(BitTools.flagIsSet(0x0003, 0x0001)); - assertTrue(BitTools.flagIsSet(0x0303, 0x0001)); - assertTrue(BitTools.flagIsSet(0x0303, 0x0101)); - assertTrue(BitTools.flagIsSet(0x0303, 0x0103)); - - assertFalse(BitTools.flagIsSet(0x0303, 0x1103)); - assertFalse(BitTools.flagIsSet(0x0000, 0x1103)); - } - - public void testFlagIsOffIntInt() { - assertFalse(BitTools.flagIsOff(0x0003, 0x0001)); - assertFalse(BitTools.flagIsOff(0x0303, 0x0001)); - assertFalse(BitTools.flagIsOff(0x0303, 0x0101)); - assertFalse(BitTools.flagIsOff(0x0303, 0x0103)); - - assertTrue(BitTools.flagIsOff(0x2204, 0x1103)); - assertTrue(BitTools.flagIsOff(0x0000, 0x1103)); - } - - public void testOnlyFlagIsSetIntInt() { - assertFalse(BitTools.onlyFlagIsSet(0x0003, 0x0001)); - assertTrue(BitTools.onlyFlagIsSet(0x0001, 0x0001)); - - assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x0001)); - assertTrue(BitTools.onlyFlagIsSet(0x0001, 0x0001)); - - assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x0101)); - assertTrue(BitTools.onlyFlagIsSet(0x0101, 0x0101)); - - assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x0103)); - assertTrue(BitTools.onlyFlagIsSet(0x0103, 0x0103)); - - assertFalse(BitTools.onlyFlagIsSet(0x0303, 0x1103)); - assertTrue(BitTools.onlyFlagIsSet(0x1103, 0x1103)); - - assertFalse(BitTools.onlyFlagIsSet(0x0000, 0x1103)); - assertTrue(BitTools.onlyFlagIsSet(0x0103, 0x0103)); - } - - public void testOnlyFlagIsOffIntInt() { - assertFalse(BitTools.onlyFlagIsOff(0x0003, 0x0001)); - assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x0001)); - assertTrue(BitTools.onlyFlagIsOff(0xFFFFFFFE, 0x0001)); - - assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x0101)); - assertTrue(BitTools.onlyFlagIsOff(0xFFFFFEFE, 0x0101)); - - assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x0103)); - assertTrue(BitTools.onlyFlagIsOff(0xFFFFFEFC, 0x0103)); - - assertFalse(BitTools.onlyFlagIsOff(0x0303, 0x1103)); - assertTrue(BitTools.onlyFlagIsOff(0xFFFFEEFC, 0x1103)); - } - - public void testAllFlagsAreSetIntInt() { - assertTrue(BitTools.allFlagsAreSet(0x0003, 0x0001)); - assertTrue(BitTools.allFlagsAreSet(0x0303, 0x0001)); - assertTrue(BitTools.allFlagsAreSet(0x0303, 0x0101)); - assertTrue(BitTools.allFlagsAreSet(0x0303, 0x0103)); - - assertFalse(BitTools.allFlagsAreSet(0x0303, 0x1103)); - assertFalse(BitTools.allFlagsAreSet(0x0000, 0x1103)); - } - - public void testAllFlagsAreOffIntInt() { - assertFalse(BitTools.allFlagsAreOff(0x0003, 0x0001)); - assertFalse(BitTools.allFlagsAreOff(0x0303, 0x0001)); - assertFalse(BitTools.allFlagsAreOff(0x0303, 0x0101)); - assertFalse(BitTools.allFlagsAreOff(0x0303, 0x0103)); - - assertTrue(BitTools.allFlagsAreOff(0x2204, 0x1103)); - assertTrue(BitTools.allFlagsAreOff(0x0000, 0x1103)); - } - - public void testOnlyFlagsAreSetIntInt() { - assertFalse(BitTools.onlyFlagsAreSet(0x0003, 0x0001)); - assertTrue(BitTools.onlyFlagsAreSet(0x0001, 0x0001)); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x0001)); - assertTrue(BitTools.onlyFlagsAreSet(0x0001, 0x0001)); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x0101)); - assertTrue(BitTools.onlyFlagsAreSet(0x0101, 0x0101)); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x0103)); - assertTrue(BitTools.onlyFlagsAreSet(0x0103, 0x0103)); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, 0x1103)); - assertTrue(BitTools.onlyFlagsAreSet(0x1103, 0x1103)); - - assertFalse(BitTools.onlyFlagsAreSet(0x0000, 0x1103)); - assertTrue(BitTools.onlyFlagsAreSet(0x0103, 0x0103)); - } - - public void testOnlyFlagsAreOffIntInt() { - assertFalse(BitTools.onlyFlagsAreOff(0x0003, 0x0001)); - assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x0001)); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFFFE, 0x0001)); - - assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x0101)); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFE, 0x0101)); - - assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x0103)); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFC, 0x0103)); - - assertFalse(BitTools.onlyFlagsAreOff(0x0303, 0x1103)); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFEEFC, 0x1103)); - } - - public void testAnyFlagsAreSetIntInt() { - assertTrue(BitTools.anyFlagsAreSet(0x0003, 0x0001)); - assertTrue(BitTools.anyFlagsAreSet(0xFFFF, 0x0001)); - assertTrue(BitTools.anyFlagsAreSet(0x0003, 0xFFFF)); - - assertFalse(BitTools.anyFlagsAreSet(0x0303, 0x1010)); - assertFalse(BitTools.anyFlagsAreSet(0x0000, 0xFFFF)); - } - - public void testAnyFlagsAreOffIntInt() { - assertTrue(BitTools.anyFlagsAreOff(0x333E, 0x0001)); - assertTrue(BitTools.anyFlagsAreOff(0xFFFE, 0x0001)); - assertTrue(BitTools.anyFlagsAreOff(0x0003, 0xFFFF)); - - assertFalse(BitTools.anyFlagsAreOff(0x7373, 0x1010)); - assertFalse(BitTools.anyFlagsAreOff(0xFFFF, 0xFFFF)); - } - - public void testAllFlagsAreSetIntIntArray() { - assertTrue(BitTools.allFlagsAreSet(0x0003, new int[] { 0x0001 })); - assertTrue(BitTools.allFlagsAreSet(0x0303, new int[] { 0x0001 })); - assertTrue(BitTools.allFlagsAreSet(0x0303, new int[] { 0x0100, 0x0001 })); - assertTrue(BitTools.allFlagsAreSet(0x0303, new int[] { 0x0100, 0x0002, 0x0001 })); - - assertFalse(BitTools.allFlagsAreSet(0x0303, new int[] { 0x1000, 0x0100, 0x0002, 0x0001 })); - assertFalse(BitTools.allFlagsAreSet(0x0000, new int[] { 0x1000, 0x0100, 0x0002, 0x0001 })); - } - - public void testAllFlagsAreOffIntIntArray() { - assertFalse(BitTools.allFlagsAreOff(0x0003, new int[] { 0x0001 })); - assertFalse(BitTools.allFlagsAreOff(0x0303, new int[] { 0x0001 })); - assertFalse(BitTools.allFlagsAreOff(0x0303, new int[] { 0x0100, 0x0001 })); - assertFalse(BitTools.allFlagsAreOff(0x0303, new int[] { 0x0100, 0x0002, 0x0001 })); - - assertTrue(BitTools.allFlagsAreOff(0x0303, new int[] { 0x1000, 0x0400, 0x0020, 0x0000 })); - assertTrue(BitTools.allFlagsAreOff(0x0000, new int[] { 0x1000, 0x0100, 0x0002, 0x0001 })); - } - - public void testOnlyFlagsAreSetIntIntArray() { - assertFalse(BitTools.onlyFlagsAreSet(0x0003, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreSet(0x0001, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreSet(0x0001, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreSet(0x0101, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreSet(0x0103, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreSet(0x0303, new int[] { 0x011, 0x0100, 0x0002, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreSet(0x1103, new int[] { 0x1100, 0x0100, 0x0002, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreSet(0x0000, new int[] { 0x011, 0x0100, 0x0002, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreSet(0x0103, new int[] { 0x0101, 0x0100, 0x0002, 0x0001 })); - } - - public void testOnlyFlagsAreOffIntIntArray() { - assertFalse(BitTools.onlyFlagsAreOff(0x0003, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFFFE, new int[] { 0x001, 0x0000, 0x0000, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFE, new int[] { 0x001, 0x0100, 0x0000, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFFEFC, new int[] { 0x001, 0x0100, 0x0002, 0x0001 })); - - assertFalse(BitTools.onlyFlagsAreOff(0x0303, new int[] { 0x1100, 0x0100, 0x0002, 0x0001 })); - assertTrue(BitTools.onlyFlagsAreOff(0xFFFFEEFC, new int[] { 0x1100, 0x0100, 0x0002, 0x0001 })); - } - - public void testAnyFlagsAreSetIntIntArray() { - assertTrue(BitTools.anyFlagsAreSet(0x0003, new int[] { 0x0001 })); - assertTrue(BitTools.anyFlagsAreSet(0xFFFF, new int[] { 0x0001 })); - assertTrue(BitTools.anyFlagsAreSet(0x0303, new int[] { 0xF000, 0x0F00, 0x00F0, 0x000F })); - - assertFalse(BitTools.anyFlagsAreSet(0x0303, new int[] { 0x1000, 0x0010 })); - assertFalse(BitTools.anyFlagsAreSet(0x0000, new int[] { 0xF000, 0x0F00, 0x00F0, 0x000F })); - } - - public void testAnyFlagsAreOffIntIntArray() { - assertFalse(BitTools.anyFlagsAreOff(0x0003, new int[] { 0x0001 })); - assertFalse(BitTools.anyFlagsAreOff(0xFFFF, new int[] { 0x0001 })); - assertFalse(BitTools.anyFlagsAreOff(0x0303, new int[] { 0x0100, 0x0200, 0x0003, 0x0002 })); - - assertTrue(BitTools.anyFlagsAreOff(0x0303, new int[] { 0x0100, 0x0010 })); - assertTrue(BitTools.anyFlagsAreOff(0x0000, new int[] { 0xF000, 0x0F00, 0x00F0, 0x000F })); - } - - public void testOrFlags() { - assertEquals(0x0001, BitTools.orFlags(new int[] { 0x0001, 0x0000 })); - assertEquals(0x0011, BitTools.orFlags(new int[] { 0x0001, 0x0011 })); - assertEquals(0xF011, BitTools.orFlags(new int[] { 0x0001, 0x0011, 0xF000 })); - } - - public void testAndFlags() { - assertEquals(0x0001, BitTools.andFlags(new int[] { 0x0001, 0x0001 })); - assertEquals(0x0001, BitTools.andFlags(new int[] { 0x0001, 0x0011 })); - assertEquals(0x0000, BitTools.andFlags(new int[] { 0x0001, 0x0011, 0xF000 })); - assertEquals(0x0001, BitTools.andFlags(new int[] { 0x0001, 0x0011, 0xF001 })); - } - - public void testXorFlags() { - assertEquals(0x0001, BitTools.xorFlags(new int[] { 0x0001, 0x0000 })); - assertEquals(0x0010, BitTools.xorFlags(new int[] { 0x0001, 0x0011 })); - assertEquals(0xF010, BitTools.xorFlags(new int[] { 0x0001, 0x0011, 0xF000 })); - assertEquals(0xFF11, BitTools.xorFlags(new int[] { 0x0001, 0x0011, 0xF000, 0x0F01 })); - assertEquals(0xF010, BitTools.xorFlags(new int[] { 0x0001, 0x0011, 0xF000, 0x0F01, 0x0F01 })); - } - - public void testConstructor() { - boolean exCaught = false; - try { - Object at = ReflectionTools.newInstance(BitTools.class); - fail("bogus: " + at); //$NON-NLS-1$ - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InvocationTargetException) { - if (ex.getCause().getCause() instanceof UnsupportedOperationException) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BooleanToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BooleanToolsTests.java deleted file mode 100644 index f134a70e87..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/BooleanToolsTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.InvocationTargetException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.BooleanTools; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; - -public class BooleanToolsTests extends TestCase { - private static final Boolean TRUE = Boolean.TRUE; - private static final Boolean FALSE = Boolean.FALSE; - - public BooleanToolsTests(String name) { - super(name); - } - - public void testNOT() { - assertEquals(FALSE, BooleanTools.not(TRUE)); - assertEquals(TRUE, BooleanTools.not(FALSE)); - } - - public void testAND() { - assertEquals(TRUE, BooleanTools.and(TRUE, TRUE)); - assertEquals(FALSE, BooleanTools.and(TRUE, FALSE)); - assertEquals(FALSE, BooleanTools.and(FALSE, TRUE)); - assertEquals(FALSE, BooleanTools.and(FALSE, FALSE)); - } - - public void testOR() { - assertEquals(TRUE, BooleanTools.or(TRUE, TRUE)); - assertEquals(TRUE, BooleanTools.or(TRUE, FALSE)); - assertEquals(TRUE, BooleanTools.or(FALSE, TRUE)); - assertEquals(FALSE, BooleanTools.or(FALSE, FALSE)); - } - - public void testXOR() { - assertEquals(FALSE, BooleanTools.xor(TRUE, TRUE)); - assertEquals(TRUE, BooleanTools.xor(TRUE, FALSE)); - assertEquals(TRUE, BooleanTools.xor(FALSE, TRUE)); - assertEquals(FALSE, BooleanTools.xor(FALSE, FALSE)); - } - - public void testNAND() { - assertEquals(FALSE, BooleanTools.nand(TRUE, TRUE)); - assertEquals(TRUE, BooleanTools.nand(TRUE, FALSE)); - assertEquals(TRUE, BooleanTools.nand(FALSE, TRUE)); - assertEquals(TRUE, BooleanTools.nand(FALSE, FALSE)); - } - - public void testNOR() { - assertEquals(FALSE, BooleanTools.nor(TRUE, TRUE)); - assertEquals(FALSE, BooleanTools.nor(TRUE, FALSE)); - assertEquals(FALSE, BooleanTools.nor(FALSE, TRUE)); - assertEquals(TRUE, BooleanTools.nor(FALSE, FALSE)); - } - - public void testXNOR() { - assertEquals(TRUE, BooleanTools.xnor(TRUE, TRUE)); - assertEquals(FALSE, BooleanTools.xnor(TRUE, FALSE)); - assertEquals(FALSE, BooleanTools.xnor(FALSE, TRUE)); - assertEquals(TRUE, BooleanTools.xnor(FALSE, FALSE)); - } - - public void testConstructor() { - boolean exCaught = false; - try { - Object at = ReflectionTools.newInstance(BooleanTools.class); - fail("bogus: " + at); //$NON-NLS-1$ - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InvocationTargetException) { - if (ex.getCause().getCause() instanceof UnsupportedOperationException) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClassNameTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClassNameTests.java deleted file mode 100644 index 8e070b6d18..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClassNameTests.java +++ /dev/null @@ -1,368 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ClassName; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; - -@SuppressWarnings("nls") -public class ClassNameTests extends TestCase { - - public ClassNameTests(String name) { - super(name); - } - - public void testIsArray() { - assertFalse(ClassName.isArray(int.class.getName())); - assertTrue(ClassName.isArray(int[].class.getName())); - assertTrue(ClassName.isArray(int[][].class.getName())); - - assertFalse(ClassName.isArray(java.lang.String.class.getName())); - assertTrue(ClassName.isArray(java.lang.String[].class.getName())); - assertTrue(ClassName.isArray(java.lang.String[][].class.getName())); - } - - public void testGetElementTypeName() { - assertEquals(java.util.Vector.class.getName(), ClassName.getElementTypeName(java.util.Vector.class.getName())); - assertEquals(int.class.getName(), ClassName.getElementTypeName(int.class.getName())); - assertEquals(void.class.getName(), ClassName.getElementTypeName(void.class.getName())); - assertEquals(java.util.Vector.class.getName(), ClassName.getElementTypeName(java.util.Vector[].class.getName())); - assertEquals(int.class.getName(), ClassName.getElementTypeName(int[].class.getName())); - assertEquals(java.util.Vector.class.getName(), ClassName.getElementTypeName(java.util.Vector[][][].class.getName())); - assertEquals(int.class.getName(), ClassName.getElementTypeName(int[][][].class.getName())); - } - - public void testGetArrayDepth() { - assertEquals(0, ClassName.getArrayDepth(java.util.Vector.class.getName())); - assertEquals(0, ClassName.getArrayDepth(int.class.getName())); - assertEquals(0, ClassName.getArrayDepth(void.class.getName())); - assertEquals(1, ClassName.getArrayDepth(java.util.Vector[].class.getName())); - assertEquals(1, ClassName.getArrayDepth(int[].class.getName())); - assertEquals(3, ClassName.getArrayDepth(java.util.Vector[][][].class.getName())); - assertEquals(3, ClassName.getArrayDepth(int[][][].class.getName())); - } - - public void testGetComponentTypeName() { - assertEquals(null, ClassName.getComponentTypeName(java.lang.Object.class.getName())); - assertEquals(java.lang.Object.class.getName(), ClassName.getComponentTypeName(java.lang.Object[].class.getName())); - assertEquals(java.lang.Object[].class.getName(), ClassName.getComponentTypeName(java.lang.Object[][].class.getName())); - - assertEquals(null, ClassName.getComponentTypeName(int.class.getName())); - assertEquals(int.class.getName(), ClassName.getComponentTypeName(int[].class.getName())); - assertEquals(int[].class.getName(), ClassName.getComponentTypeName(int[][].class.getName())); - } - - public void testGetSimpleName() throws Exception { - assertEquals("Object", ClassName.getSimpleName(java.lang.Object.class.getName())); - assertEquals("Object[]", ClassName.getSimpleName(java.lang.Object[].class.getName())); - assertEquals("Object[][]", ClassName.getSimpleName(java.lang.Object[][].class.getName())); - - assertEquals(java.util.Map.class.getSimpleName(), ClassName.getSimpleName(java.util.Map.class.getName())); - assertEquals(java.util.Map.Entry.class.getSimpleName(), ClassName.getSimpleName(java.util.Map.Entry.class.getName())); - - assertEquals("int", ClassName.getSimpleName(int.class.getName())); - assertEquals("int[]", ClassName.getSimpleName(int[].class.getName())); - assertEquals("int[][]", ClassName.getSimpleName(int[][].class.getName())); - - Object anonObject = new Object() { - // anonymous class - }; - assertEquals("", ClassName.getSimpleName(anonObject.getClass().getName())); - - class Local { - // anonymous class - } - Local localObject = new Local(); - assertEquals("Local", ClassName.getSimpleName(localObject.getClass().getName())); - } - - public void testGetPackageName() throws Exception { - assertEquals(java.lang.Object.class.getPackage().getName(), ClassName.getPackageName(java.lang.Object.class.getName())); - assertEquals("", ClassName.getPackageName(java.lang.Object[].class.getName())); - assertEquals("", ClassName.getPackageName(java.lang.Object[][].class.getName())); - - assertEquals(java.util.Map.class.getPackage().getName(), ClassName.getPackageName(java.util.Map.class.getName())); - assertEquals(java.util.Map.Entry.class.getPackage().getName(), ClassName.getPackageName(java.util.Map.Entry.class.getName())); - - assertEquals("", ClassName.getPackageName(int.class.getName())); - assertEquals("", ClassName.getPackageName(int[].class.getName())); - assertEquals("", ClassName.getPackageName(int[][].class.getName())); - - assertEquals("", ClassName.getPackageName(void.class.getName())); - - Object anonObject = new Object() { - // anonymous class - }; - assertEquals(anonObject.getClass().getPackage().getName(), ClassName.getPackageName(anonObject.getClass().getName())); - } - - public void testIsTopLevel() throws Exception { - assertTrue(ClassName.isTopLevel(java.util.Map.class.getName())); // top-level - assertFalse(ClassName.isTopLevel(java.util.Map.Entry.class.getName())); // member - assertFalse(ClassName.isTopLevel(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local - assertFalse(ClassName.isTopLevel(Class.forName("java.util.Vector$1").getName())); // anonymous - - Object[] array = new java.util.Map[0]; // top-level - assertFalse(ClassName.isTopLevel(array.getClass().getName())); - array = new java.util.Map.Entry[0]; // member - assertFalse(ClassName.isTopLevel(array.getClass().getName())); - Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local - array = (Object[]) Array.newInstance(localClass, 0); - assertFalse(ClassName.isTopLevel(array.getClass().getName())); - Class<?> anonClass = Class.forName("java.util.Vector$1"); // local - array = (Object[]) Array.newInstance(anonClass, 0); - assertFalse(ClassName.isTopLevel(array.getClass().getName())); - } - - public void testIsMember() throws Exception { - assertFalse(ClassName.isMember(java.util.Map.class.getName())); // top-level - assertTrue(ClassName.isMember(java.util.Map.Entry.class.getName())); // member - assertFalse(ClassName.isMember(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local - assertFalse(ClassName.isMember(Class.forName("java.util.Vector$1").getName())); // anonymous - - Object[] array = new java.util.Map[0]; // top-level - assertFalse(ClassName.isMember(array.getClass().getName())); - array = new java.util.Map.Entry[0]; // member - assertFalse(ClassName.isMember(array.getClass().getName())); - Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local - array = (Object[]) Array.newInstance(localClass, 0); - assertFalse(ClassName.isMember(array.getClass().getName())); - Class<?> anonClass = Class.forName("java.util.Vector$1"); // local - array = (Object[]) Array.newInstance(anonClass, 0); - assertFalse(ClassName.isMember(array.getClass().getName())); - - // test a few edge cases - assertTrue(ClassName.isMember("java.util.Map$a1")); - assertTrue(ClassName.isMember("java.util.Map$1aa$aaa")); // member inside local - assertTrue(ClassName.isMember("java.util.Map$1$aaa")); // member inside anonymous - assertTrue(ClassName.isMember("java.util.Map$a1$aaa$bbb")); - assertTrue(ClassName.isMember("java.util.Map$1a1$aaa")); // member inside local - assertFalse(ClassName.isMember("java.util.Map$1a")); - assertTrue(ClassName.isMember("java.util.Map$a12345$b12345")); - assertFalse(ClassName.isMember("java.util.Map$12345a")); - assertFalse(ClassName.isMember("java.util.Map$333")); - assertFalse(ClassName.isMember("java.util.Map3$333")); - } - - public void testIsLocal() throws Exception { - class LocalClass { - void foo() { - System.getProperty("foo"); - } - } - new LocalClass().foo(); - assertFalse(ClassName.isLocal(java.util.Map.class.getName())); // top-level - assertFalse(ClassName.isLocal(java.util.Map.Entry.class.getName())); // member - assertTrue(ClassName.isLocal(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local - assertFalse(ClassName.isLocal(Class.forName("java.util.Vector$1").getName())); // anonymous - - Object[] array = new java.util.Map[0]; // top-level - assertFalse(ClassName.isLocal(array.getClass().getName())); - array = new java.util.Map.Entry[0]; // member - assertFalse(ClassName.isLocal(array.getClass().getName())); - Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local - array = (Object[]) Array.newInstance(localClass, 0); - assertFalse(ClassName.isLocal(array.getClass().getName())); - Class<?> anonClass = Class.forName("java.util.Vector$1"); // local - array = (Object[]) Array.newInstance(anonClass, 0); - assertFalse(ClassName.isLocal(array.getClass().getName())); - - // test a few edge cases - assertFalse(ClassName.isLocal("java.util.Map$a1")); - assertFalse(ClassName.isLocal("java.util.Map$a1$aaa$bbb")); - assertFalse(ClassName.isLocal("java.util.Map$11$aaa")); - assertTrue(ClassName.isLocal("java.util.Map$1a")); - assertTrue(ClassName.isLocal("java.util.Map$2abc")); - assertTrue(ClassName.isLocal("java.util.Map$2abc1")); - assertFalse(ClassName.isLocal("java.util.Map$a12345$b12345")); - assertTrue(ClassName.isLocal("java.util.Map$12345$1234a")); - assertFalse(ClassName.isLocal("java.util.Map$333")); - assertFalse(ClassName.isLocal("java.util.Map3$333")); - } - - public void testIsAnonymous() throws Exception { - assertFalse(ClassName.isAnonymous(java.util.Map.class.getName())); // top-level - assertFalse(ClassName.isAnonymous(java.util.Map.Entry.class.getName())); // member - assertFalse(ClassName.isAnonymous(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local - assertTrue(ClassName.isAnonymous(Class.forName("java.util.Vector$1").getName())); // anonymous - - Object[] array = new java.util.Map[0]; // top-level - assertFalse(ClassName.isAnonymous(array.getClass().getName())); - array = new java.util.Map.Entry[0]; // member - assertFalse(ClassName.isAnonymous(array.getClass().getName())); - Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local - array = (Object[]) Array.newInstance(localClass, 0); - assertFalse(ClassName.isAnonymous(array.getClass().getName())); - Class<?> anonClass = Class.forName("java.util.Vector$1"); // local - array = (Object[]) Array.newInstance(anonClass, 0); - assertFalse(ClassName.isAnonymous(array.getClass().getName())); - - // test a few edge cases - assertFalse(ClassName.isAnonymous("java.util.Map$a1")); - assertFalse(ClassName.isAnonymous("java.util.Map$a1$aaa$bbb")); - assertFalse(ClassName.isAnonymous("java.util.Map$1a1$aaa")); - assertFalse(ClassName.isAnonymous("java.util.Map$1$a")); - assertFalse(ClassName.isAnonymous("java.util.Map$1a")); - assertFalse(ClassName.isAnonymous("java.util.Map$a12345$b12345")); - assertFalse(ClassName.isAnonymous("java.util.Map$12345$a1234")); - assertTrue(ClassName.isAnonymous("java.util.Map$333")); - assertTrue(ClassName.isAnonymous("java.util.Map3$333")); - } - - public void testIsReference() throws Exception { - assertFalse(ClassName.isReference(int.class.getName())); // top-level - - assertTrue(ClassName.isReference(java.util.Map.class.getName())); // top-level - assertTrue(ClassName.isReference(java.util.Map.Entry.class.getName())); // member - assertTrue(ClassName.isReference(Class.forName(this.getClass().getName() + "$1LocalClass").getName())); // local - assertTrue(ClassName.isReference(Class.forName("java.util.Vector$1").getName())); // anonymous - - Object[] array = new java.util.Map[0]; // top-level - assertTrue(ClassName.isReference(array.getClass().getName())); - array = new java.util.Map.Entry[0]; // member - assertTrue(ClassName.isReference(array.getClass().getName())); - Class<?> localClass = Class.forName(this.getClass().getName() + "$1LocalClass"); // local - array = (Object[]) Array.newInstance(localClass, 0); - assertTrue(ClassName.isReference(array.getClass().getName())); - Class<?> anonClass = Class.forName("java.util.Vector$1"); // local - array = (Object[]) Array.newInstance(anonClass, 0); - assertTrue(ClassName.isReference(array.getClass().getName())); - } - - public void testIsPrimitive() { - assertTrue(void.class.isPrimitive()); - - assertTrue(ClassName.isPrimitive(void.class.getName())); - assertTrue(ClassName.isPrimitive(int.class.getName())); - assertTrue(ClassName.isPrimitive(float.class.getName())); - assertTrue(ClassName.isPrimitive(boolean.class.getName())); - - assertFalse(ClassName.isPrimitive(java.lang.Number.class.getName())); - assertFalse(ClassName.isPrimitive(java.lang.String.class.getName())); - assertFalse(ClassName.isPrimitive(java.lang.Boolean.class.getName())); - assertFalse(ClassName.isPrimitive(java.lang.Integer.class.getName())); - } - - public void testIsPrimitiveWrapper() { - assertFalse(ClassName.isPrimitiveWrapper(void.class.getName())); - assertFalse(ClassName.isPrimitiveWrapper(int.class.getName())); - assertFalse(ClassName.isPrimitiveWrapper(float.class.getName())); - assertFalse(ClassName.isPrimitiveWrapper(boolean.class.getName())); - - assertFalse(ClassName.isPrimitiveWrapper(java.lang.reflect.Field.class.getName())); - assertFalse(ClassName.isPrimitiveWrapper(java.lang.String.class.getName())); - assertTrue(ClassName.isPrimitiveWrapper(java.lang.Boolean.class.getName())); - assertTrue(ClassName.isPrimitiveWrapper(java.lang.Integer.class.getName())); - } - - public void testIsVariablePrimitive() { - assertFalse(ClassName.isVariablePrimitive(void.class.getName())); - - assertTrue(ClassName.isVariablePrimitive(int.class.getName())); - assertTrue(ClassName.isVariablePrimitive(float.class.getName())); - assertTrue(ClassName.isVariablePrimitive(boolean.class.getName())); - - assertFalse(ClassName.isVariablePrimitive(java.lang.Number.class.getName())); - assertFalse(ClassName.isVariablePrimitive(java.lang.String.class.getName())); - assertFalse(ClassName.isVariablePrimitive(java.lang.Boolean.class.getName())); - } - - public void testIsVariablePrimitiveWrapper() { - assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.Void.class.getName())); - - assertTrue(ClassName.isVariablePrimitiveWrapper(java.lang.Integer.class.getName())); - assertTrue(ClassName.isVariablePrimitiveWrapper(java.lang.Float.class.getName())); - assertTrue(ClassName.isVariablePrimitiveWrapper(java.lang.Boolean.class.getName())); - - assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.Number.class.getName())); - assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.String.class.getName())); - assertFalse(ClassName.isVariablePrimitiveWrapper(java.lang.Object.class.getName())); - } - - public void testGetWrapperClassName() { - assertEquals(java.lang.Void.class.getName(), ClassName.getWrapperClassName(void.class.getName())); - assertEquals(java.lang.Integer.class.getName(), ClassName.getWrapperClassName(int.class.getName())); - assertEquals(java.lang.Float.class.getName(), ClassName.getWrapperClassName(float.class.getName())); - assertEquals(java.lang.Boolean.class.getName(), ClassName.getWrapperClassName(boolean.class.getName())); - - assertNull(ClassName.getWrapperClassName(java.lang.String.class.getName())); - } - - public void testGetPrimitiveClassName() { - assertEquals(void.class.getName(), ClassName.getPrimitiveClassName(java.lang.Void.class.getName())); - assertEquals(int.class.getName(), ClassName.getPrimitiveClassName(java.lang.Integer.class.getName())); - assertEquals(float.class.getName(), ClassName.getPrimitiveClassName(java.lang.Float.class.getName())); - assertEquals(boolean.class.getName(), ClassName.getPrimitiveClassName(java.lang.Boolean.class.getName())); - - assertNull(ClassName.getPrimitiveClassName(java.lang.String.class.getName())); - } - - public void testAreAutoboxEquivalents() { - assertTrue(ClassName.areAutoboxEquivalents(Integer.class.getName(), Integer.class.getName())); - assertTrue(ClassName.areAutoboxEquivalents(int.class.getName(), Integer.class.getName())); - assertTrue(ClassName.areAutoboxEquivalents(Integer.class.getName(), int.class.getName())); - assertFalse(ClassName.areAutoboxEquivalents(int.class.getName(), Boolean.class.getName())); - assertTrue(ClassName.areAutoboxEquivalents(String.class.getName(), String.class.getName())); - } - - public void testForCode() { - assertEquals("byte", ClassName.forCode('B')); - assertEquals("char", ClassName.forCode('C')); - assertEquals("double", ClassName.forCode('D')); - assertEquals("float", ClassName.forCode('F')); - assertEquals("int", ClassName.forCode('I')); - assertEquals("long", ClassName.forCode('J')); - assertEquals("short", ClassName.forCode('S')); - assertEquals("boolean", ClassName.forCode('Z')); - assertEquals("void", ClassName.forCode('V')); - - assertNull(ClassName.forCode('X')); - - assertEquals("byte", ClassName.forCode((int) 'B')); - assertEquals("char", ClassName.forCode((int) 'C')); - assertEquals("double", ClassName.forCode((int) 'D')); - assertEquals("float", ClassName.forCode((int) 'F')); - assertEquals("int", ClassName.forCode((int) 'I')); - assertEquals("long", ClassName.forCode((int) 'J')); - assertEquals("short", ClassName.forCode((int) 'S')); - assertEquals("boolean", ClassName.forCode((int) 'Z')); - assertEquals("void", ClassName.forCode((int) 'V')); - - assertNull(ClassName.forCode((int) 'X')); - } - - public void testGetCodeForClassName() { - assertEquals('I', ClassName.getCodeForClassName(int.class.getName())); - assertEquals('I', ClassName.getCodeForClassName("int")); - assertEquals('B', ClassName.getCodeForClassName(byte.class.getName())); - assertEquals('B', ClassName.getCodeForClassName("byte")); - - assertEquals((char) 0, ClassName.getCodeForClassName(java.lang.Object.class.getName())); - } - - public void testConstructor() { - boolean exCaught = false; - try { - Object at = ReflectionTools.newInstance(ClassName.class); - fail("bogus: " + at); //$NON-NLS-1$ - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InvocationTargetException) { - if (ex.getCause().getCause() instanceof UnsupportedOperationException) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClasspathTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClasspathTests.java deleted file mode 100644 index 6542662416..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ClasspathTests.java +++ /dev/null @@ -1,402 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.Classpath; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.Tools; - -@SuppressWarnings("nls") -public class ClasspathTests extends TestCase { - private static final String JAVA_HOME = System.getProperty("java.home"); - - public ClasspathTests(String name) { - super(name); - } - - public void testCompressed() { - String path = ""; - - // no changes - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\i18n.jar;C:\\jdk\\i18n.jar;C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;;;;C:\\jdk\\jaws.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;;;")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - // no changes - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\..\\jdk\\i18n.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - path = new Classpath(this.morph("C:\\jdk1\\jdk2\\jdk3\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk1\\jdk2\\jdk3\\..\\..\\..\\jdk1\\jdk2\\jdk3\\i18n.jar;C:\\jdk\\jaws.jar")).compressed().getPath(); - assertEquals(this.morph("C:\\jdk1\\jdk2\\jdk3\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar"), path); - - } - - public void testConvertToClassName() { - String fileName = "java/lang/String.class"; - File file = new File(fileName); - String className = Classpath.convertToClassName(file); - assertEquals(java.lang.String.class.getName(), className); - } - - public void testConvertToClass() throws ClassNotFoundException { - String fileName = "java/lang/String.class"; - File file = new File(fileName); - Class<?> javaClass = Classpath.convertToClass(file); - assertEquals(java.lang.String.class, javaClass); - } - - public void testConvertToArchiveClassFileEntryName() { - String fileName = Classpath.convertToArchiveClassFileEntryName(java.lang.String.class); - assertEquals("java/lang/String.class", fileName); - } - - public void testConvertToArchiveEntryNameBase() { - String fileName = Classpath.convertToArchiveEntryNameBase(java.lang.String.class); - assertEquals("java/lang/String", fileName); - } - - public void testConvertToClassFileName() { - char sc = File.separatorChar; - String fileName = Classpath.convertToClassFileName(java.lang.String.class); - assertEquals("java" + sc + "lang" + sc + "String.class", fileName); - } - - public void testConvertToClassFileString() { - char sc = File.separatorChar; - File file = Classpath.convertToClassFile(java.lang.String.class.getName()); - assertEquals("java" + sc + "lang" + sc + "String.class", file.getPath()); - } - - public void testConvertToClassFileClass() { - char sc = File.separatorChar; - File file = Classpath.convertToClassFile(java.lang.String.class); - assertEquals("java" + sc + "lang" + sc + "String.class", file.getPath()); - } - - public void testConvertToJavaFileName() { - char sc = File.separatorChar; - String fileName = Classpath.convertToJavaFileName(java.lang.String.class); - assertEquals("java" + sc + "lang" + sc + "String.java", fileName); - } - - public void testConvertToJavaFileString() { - char sc = File.separatorChar; - File file = Classpath.convertToJavaFile(java.lang.String.class.getName()); - assertEquals("java" + sc + "lang" + sc + "String.java", file.getPath()); - } - - public void testConvertToJavaFileClass() { - char sc = File.separatorChar; - File file = Classpath.convertToJavaFile(java.lang.String.class); - assertEquals("java" + sc + "lang" + sc + "String.java", file.getPath()); - } - - public void testConvertToFileNameBase() { - char sc = File.separatorChar; - String fileName = Classpath.convertToFileNameBase(java.lang.String.class); - assertEquals("java" + sc + "lang" + sc + "String", fileName); - } - - public void testConvertToURLs() { - Iterator<URL> entries = new Classpath(this.morph("C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getURLs().iterator(); - assertEquals(this.morphURL("/C:/jdk/rt.jar"), entries.next().getPath()); - assertEquals(this.morphURL("/C:/jdk/i18n.jar"), entries.next().getPath()); - assertEquals(this.morphURL("/C:/jdk/jaws.jar"), entries.next().getPath()); - assertEquals(this.morphURL("/C:/foo/classes"), entries.next().getPath()); - assertEquals(this.morphURL("/C:/bar/bar.jar"), entries.next().getPath()); - assertFalse(entries.hasNext()); - } - - public void testGetEntries() { - Classpath cp = new Classpath(this.morph("C:\\jdk\\rt.jar;;.;C:\\jdk\\i18n.jar;;;C:\\jdk\\jaws.jar;;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\bar\\bar.jar;")); - Iterator<Classpath.Entry> entries = cp.getEntries().iterator(); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entries.next().getFileName()); - assertEquals(this.morph("."), entries.next().getFileName()); - assertEquals(this.morph("C:\\jdk\\i18n.jar"), entries.next().getFileName()); - assertEquals(this.morph("C:\\jdk\\jaws.jar"), entries.next().getFileName()); - assertEquals(this.morph("C:\\foo\\classes"), entries.next().getFileName()); - assertEquals(this.morph("C:\\bar\\bar.jar"), entries.next().getFileName()); - assertEquals(this.morph("C:\\bar\\bar.jar"), entries.next().getFileName()); - assertFalse(entries.hasNext()); - - cp = cp.compressed(); - entries = cp.getEntries().iterator(); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entries.next().getFileName()); - assertEquals(this.morph("."), entries.next().getFileName()); - assertEquals(this.morph("C:\\jdk\\i18n.jar"), entries.next().getFileName()); - assertEquals(this.morph("C:\\jdk\\jaws.jar"), entries.next().getFileName()); - assertEquals(this.morph("C:\\foo\\classes"), entries.next().getFileName()); - assertEquals(this.morph("C:\\bar\\bar.jar"), entries.next().getFileName()); - assertFalse(entries.hasNext()); - } - - public void testGetEntryForFileNamed() { - Classpath.Entry entry = null; - - // in the middle - qualified - entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\rt.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // in the middle - unqualified - entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;rt.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); - assertEquals("rt.jar", entry.getFileName()); - - // at the beginning - qualified - entry = new Classpath(this.morph("C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // at the beginning - unqualified - entry = new Classpath(this.morph("rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); - assertEquals("rt.jar", entry.getFileName()); - - // at the end - qualified - entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\jdk\\rt.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // at the end - unqualified - entry = new Classpath(this.morph("C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;rt.jar")).getEntryForFileNamed("rt.jar"); - assertEquals("rt.jar", entry.getFileName()); - - // alone - qualified - entry = new Classpath(this.morph("C:\\jdk\\rt.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // alone - unqualified - entry = new Classpath("rt.jar").getEntryForFileNamed("rt.jar"); - assertEquals("rt.jar", entry.getFileName()); - - // trick entry at the beginning - entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // trick entry in the middle - entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rtrtrt.jar;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // trick entry at the end - entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rtrtrt.jar;C:\\jdk\\rt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\jdk\\rtrtrt.jar")).getEntryForFileNamed("rt.jar"); - assertEquals(this.morph("C:\\jdk\\rt.jar"), entry.getFileName()); - - // missing - entry = new Classpath(this.morph("rt.jar.new;C:\\jdk\\rtrtrt.jar;C:\\jdk\\i18n.jar;C:\\jdk\\jaws.jar;C:\\foo\\classes;C:\\bar\\bar.jar;C:\\jdk\\rtrtrt.jar")).getEntryForFileNamed("rt.jar"); - assertEquals("path entry should not be found", null, entry); - - } - - public void testGetEntryForClassNamed() { - assertNotNull(Classpath.completeClasspath().getEntryForClassNamed(java.lang.String.class.getName())); - assertNull(Classpath.completeClasspath().getEntryForClassNamed("foo.bar.Baz")); - } - - public void testLocationForClass() { - Class<?> javaClass = Classpath.class; - File entry = new File(Classpath.locationFor(javaClass)); - if (entry.isFile() || entry.isDirectory()) { - assertTrue(entry.exists()); - } - if (entry.isDirectory()) { - assertTrue(new File(entry, Classpath.convertToClassFileName(javaClass)).exists()); - } - } - - public void testRtJarName() throws IOException { - File rtFile = new File(Classpath.rtJarName()); - assertTrue("rt.jar does not exist", rtFile.exists()); - - JarFile rtJarFile = new JarFile(rtFile); - JarEntry entry = rtJarFile.getJarEntry("java/lang/Object.class"); - rtJarFile.close(); - assertTrue("bogus rt.jar", entry != null); - } - - public void testJREClassNames() { - assertTrue("Vector is missing from JRE class names", CollectionTools.contains(Classpath.bootClasspath().getClassNames(), java.util.Vector.class.getName())); - assertTrue("File is missing from JRE class names", CollectionTools.contains(Classpath.bootClasspath().getClassNames(), java.io.File.class.getName())); - } - - public void testJavaExtensionDirectoryNames() { - char sep = File.separatorChar; - String stdExtDirName = JAVA_HOME + sep + "lib" + sep + "ext"; - assertTrue("standard extension dir name missing: " + stdExtDirName, ArrayTools.contains(Classpath.javaExtensionDirectoryNames(), stdExtDirName)); - } - - public void testJavaExtensionDirectories() { - char sep = File.separatorChar; - File stdExtDir = new File(JAVA_HOME + sep + "lib" + sep + "ext"); - assertTrue("standard extension dir missing: " + stdExtDir.getParent(), ArrayTools.contains(Classpath.javaExtensionDirectories(), stdExtDir)); - } - - public void testJavaExtensionClasspathEntries() { - char sep = File.separatorChar; - String jdk = System.getProperty("java.version"); - if (jdk.startsWith("1.4") || jdk.startsWith("1.5") || jdk.startsWith("1.6")) { - Collection<String> jarNames = new ArrayList<String>(); - Iterable<Classpath.Entry> entries = Classpath.javaExtensionClasspath().getEntries(); - for (Classpath.Entry entry : entries) { - jarNames.add(entry.getFileName()); - } - String stdExtJarName = JAVA_HOME + sep + "lib" + sep + "ext" + sep + "dnsns.jar"; - String msg = "jdk 1.4.x standard extension jar missing: " + stdExtJarName; - boolean jarPresent = jarNames.contains(stdExtJarName); - if (Tools.jvmIsSun() || (Tools.jvmIsIBM() && jdk.startsWith("1.6"))) { - assertTrue(msg, jarPresent); - } - } else { - fail("we need to update this test for the current jdk"); - } - } - - public void testJavaExtensionClassNames() { - String jdk = System.getProperty("java.version"); - if (jdk.startsWith("1.4") || jdk.startsWith("1.5") || jdk.startsWith("1.6")) { - String className = "sun.net.spi.nameservice.dns.DNSNameService"; - String msg = "jdk 1.4.x standard extension class missing: " + className; - boolean classPresent = CollectionTools.contains(Classpath.javaExtensionClasspath().classNames(), className); - if (Tools.jvmIsSun() || (Tools.jvmIsIBM() && jdk.startsWith("1.6"))) { - assertTrue(msg, classPresent); - } - } else { - fail("we need to update this test for the current jdk"); - } - } - - public void testJavaClasspathClassNames() { - String className = this.getClass().getName(); - ClassLoader cl = this.getClass().getClassLoader(); - // make sure we are running under the "normal" class loader; - // when the tests are executed as an ANT task, they are run under - // an ANT class loader and the "Java" classpath does not include this class - if (cl.getClass().getName().startsWith("sun.misc")) { - assertTrue("class missing: " + className, CollectionTools.contains(Classpath.javaClasspath().getClassNames(), className)); - } - } - - public void testCompleteClasspathClassNames() { - String className = this.getClass().getName(); - ClassLoader cl = this.getClass().getClassLoader(); - // make sure we are running under the "normal" class loader; - // when the tests are executed as an ANT task, they are run under - // an ANT class loader and the "Java" classpath does not include this class - if (cl.getClass().getName().startsWith("sun.misc")) { - assertTrue("class missing: " + className, CollectionTools.contains(Classpath.completeClasspath().getClassNames(), className)); - } - } - - public void testClasspathForClass() { - assertNotNull(Classpath.classpathFor(java.lang.String.class)); - } - - public void testAddClassNamesTo() { - Collection<String> classNames = new ArrayList<String>(1000); - Classpath.bootClasspath().addClassNamesTo(classNames); - assertTrue(classNames.contains(java.util.Vector.class.getName())); - } - - public void testToString() { - assertNotNull(Classpath.bootClasspath().toString()); - } - - public void testEntry_getCanonicalFile() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - assertTrue(entry.getCanonicalFile().getPath().endsWith(".jar")); - } - - public void testEntry_getCanonicalFileName() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - String name = entry.getCanonicalFileName(); - if (Tools.jvmIsSun()) { - assertTrue(name.endsWith("rt.jar")); - } else if (Tools.jvmIsIBM()) { - assertTrue(name.endsWith("vm.jar")); - } - } - - public void testEntry_equals() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - assertFalse(entry.equals("foo")); - } - - public void testEntry_containsClass() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - assertTrue(entry.contains(java.lang.String.class)); - } - - public void testEntry_containsString() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - assertTrue(entry.contains(java.lang.String.class.getName())); - } - - public void testEntry_getClassNames() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - assertTrue(CollectionTools.contains(entry.getClassNames(), java.lang.String.class.getName())); - } - - public void testEntry_classNames() { - Classpath.Entry entry = Classpath.bootClasspath().getEntryForClassNamed(java.lang.String.class.getName()); - assertTrue(CollectionTools.contains(entry.classNames(), java.lang.String.class.getName())); - } - - /** - * morph the specified path to a platform-independent path - */ - private String morph(String path) { - String result = path; - result = result.replace('\\', File.separatorChar); - result = result.replace(';', File.pathSeparatorChar); - if (!ArrayTools.contains(File.listRoots(), new File("C:\\"))) { - result = result.replaceAll("C:", ""); - } - return result; - } - - /** - * morph the specified URL to a platform-independent path - */ - private String morphURL(String url) { - String result = url; - if (!ArrayTools.contains(File.listRoots(), new File("C:\\"))) { - result = result.replaceAll("/C:", ""); - } - return result; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CollectionToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CollectionToolsTests.java deleted file mode 100644 index 5bb02201fd..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/CollectionToolsTests.java +++ /dev/null @@ -1,2418 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import java.util.Random; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.Vector; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.Range; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.ReverseComparator; -import org.eclipse.jpt.common.utility.internal.enumerations.EmptyEnumeration; -import org.eclipse.jpt.common.utility.internal.iterables.EmptyIterable; -import org.eclipse.jpt.common.utility.internal.iterators.ArrayIterator; -import org.eclipse.jpt.common.utility.internal.iterators.EmptyIterator; - -@SuppressWarnings("nls") -public class CollectionToolsTests extends TestCase { - - public CollectionToolsTests(String name) { - super(name); - } - - - // ********** add all ********** - - public void testAddAllCollectionIterable_StringModified() { - List<String> list1 = this.buildStringList1(); - Iterable<String> iterable2 = this.buildStringList2(); - assertTrue(CollectionTools.addAll(list1, iterable2.iterator())); - assertEquals(6, list1.size()); - assertTrue(list1.containsAll(this.buildStringList2())); - } - - public void testAddAllCollectionIterable_StringUnmodified() { - Set<String> set1 = this.buildStringSet1(); - Iterable<String> iterable3 = this.buildStringList1(); // same elements as set1 - assertFalse(CollectionTools.addAll(set1, iterable3.iterator())); - assertEquals(3, set1.size()); - assertTrue(set1.containsAll(this.buildStringList1())); - } - - public void testAddAllCollectionIterable_ObjectModified() { - List<Object> list1 = this.buildObjectList1(); - Iterable<String> iterable2 = this.buildStringList2(); - assertTrue(CollectionTools.addAll(list1, iterable2)); - assertEquals(6, list1.size()); - assertTrue(list1.containsAll((List<String>) iterable2)); - } - - public void testAddAllCollectionIterable_ObjectUnmodified() { - Set<Object> set1 = this.buildObjectSet1(); - Iterable<String> iterable3 = this.buildStringList1(); // same elements as set1 - assertFalse(CollectionTools.addAll(set1, iterable3)); - assertEquals(3, set1.size()); - assertTrue(set1.containsAll((List<String>) iterable3)); - } - - public void testAddAllCollectionIterable_EmptyIterable() { - Set<Object> set1 = this.buildObjectSet1(); - assertFalse(CollectionTools.addAll(set1, EmptyIterable.instance())); - assertEquals(3, set1.size()); - } - - public void testAddAllCollectionIterableInt_Modified() { - List<String> list1 = this.buildStringList1(); - List<String> list2 = this.buildStringList2(); - Iterable<String> iterable2 = list2; - assertTrue(CollectionTools.addAll(list1, iterable2, list2.size())); - assertEquals(6, list1.size()); - assertTrue(list1.containsAll(this.buildStringList2())); - } - - public void testAddAllCollectionIterableInt_Unmodified() { - Set<String> set1 = this.buildStringSet1(); - List<String> list1 = this.buildStringList1(); // same elements as set1 - Iterable<String> iterable3 = list1; - assertFalse(CollectionTools.addAll(set1, iterable3, list1.size())); - assertEquals(3, set1.size()); - assertTrue(set1.containsAll(this.buildStringList1())); - } - - public void testAddAllCollectionIterator_StringModified() { - List<String> list1 = this.buildStringList1(); - List<String> list2 = this.buildStringList2(); - assertTrue(CollectionTools.addAll(list1, list2.iterator())); - assertEquals(6, list1.size()); - assertTrue(list1.containsAll(list2)); - } - - public void testAddAllCollectionIterator_StringUnmodified() { - Set<String> set1 = this.buildStringSet1(); - List<String> list3 = this.buildStringList1(); // same elements as s1 - assertFalse(CollectionTools.addAll(set1, list3.iterator())); - assertEquals(3, set1.size()); - assertTrue(set1.containsAll(list3)); - } - - public void testAddAllCollectionIterator_ObjectModified() { - List<Object> list1 = this.buildObjectList1(); - List<String> list2 = this.buildStringList2(); - assertTrue(CollectionTools.addAll(list1, list2.iterator())); - assertEquals(6, list1.size()); - assertTrue(list1.containsAll(list2)); - } - - public void testAddAllCollectionIterator_ObjectUnmodified() { - Set<Object> set1 = this.buildObjectSet1(); - List<String> list3 = this.buildStringList1(); // same elements as s1 - assertFalse(CollectionTools.addAll(set1, list3.iterator())); - assertEquals(3, set1.size()); - assertTrue(set1.containsAll(list3)); - } - - public void testAddAllCollectionIterator_EmptyIterator() { - List<String> list1 = this.buildStringList1(); - assertFalse(CollectionTools.addAll(list1, EmptyIterator.<String>instance())); - assertEquals(3, list1.size()); - } - - public void testAddAllCollectionIteratorInt_Modified() { - List<String> list1 = this.buildStringList1(); - List<String> list2 = this.buildStringList2(); - assertTrue(CollectionTools.addAll(list1, list2.iterator(), 3)); - assertEquals(6, list1.size()); - assertTrue(list1.containsAll(list2)); - } - - public void testAddAllCollectionIteratorInt_Unmodified() { - Set<String> set1 = this.buildStringSet1(); - List<String> list3 = this.buildStringList1(); // same elements as s1 - assertFalse(CollectionTools.addAll(set1, list3.iterator(), 3)); - assertEquals(3, set1.size()); - assertTrue(set1.containsAll(list3)); - } - - public void testAddAllCollectionIteratorInt_EmptyIterator() { - List<String> list1 = this.buildStringList1(); - assertFalse(CollectionTools.addAll(list1, EmptyIterator.<String>instance(), 0)); - assertEquals(3, list1.size()); - } - - public void testAddAllCollectionObjectArray_StringModified() { - List<String> list = this.buildStringList1(); - String[] a = this.buildStringArray1(); - assertTrue(CollectionTools.addAll(list, a)); - assertEquals(6, list.size()); - assertTrue(list.containsAll(CollectionTools.collection(a))); - } - - public void testAddAllCollectionObjectArray_StringListEmptyArray() { - List<String> list = this.buildStringList1(); - assertFalse(CollectionTools.addAll(list, new String[0])); - } - - public void testAddAllCollectionObjectArray_StringUnmodified() { - Set<String> set = this.buildStringSet1(); - String[] a = this.buildStringArray1(); - assertFalse(CollectionTools.addAll(set, a)); - assertEquals(3, set.size()); - assertTrue(set.containsAll(CollectionTools.collection(a))); - - assertFalse(CollectionTools.addAll(set, new String[0])); - } - - public void testAddAllCollectionObjectArray_StringSetEmptyArray() { - Set<String> set = this.buildStringSet1(); - assertFalse(CollectionTools.addAll(set, new String[0])); - } - - public void testAddAllCollectionObjectArray_ObjectModified() { - List<Object> list = this.buildObjectList1(); - String[] a = this.buildStringArray1(); - - assertTrue(CollectionTools.addAll(list, a)); - assertEquals(6, list.size()); - assertTrue(list.containsAll(CollectionTools.collection(a))); - } - - public void testAddAllCollectionObjectArray_ObjectUnmodified() { - String[] a = this.buildStringArray1(); - Set<Object> set = this.buildObjectSet1(); - assertFalse(CollectionTools.addAll(set, a)); - assertEquals(3, set.size()); - assertTrue(set.containsAll(CollectionTools.collection(a))); - } - - public void testAddAllListIntObjectArray() { - List<String> list = this.buildStringList1(); - CollectionTools.addAll(list, 2, new String[] { "X", "X", "X" }); - assertEquals(6, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); - } - - public void testAddAllListIntObjectArray_Zero() { - List<String> list = new ArrayList<String>(); - CollectionTools.addAll(list, 0, new String[] { "X", "X", "X" }); - assertEquals(3, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); - } - - public void testAddAllListIntObjectArray_EmptyArray() { - List<String> list = this.buildStringList1(); - CollectionTools.addAll(list, 2, new String[0]); - assertEquals(3, list.size()); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); - } - - public void testAddAllListIntIterable() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); - CollectionTools.addAll(list, 2, iterable); - assertEquals(6, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); - } - - public void testAddAllListIntIterable_Zero() { - List<String> list = new ArrayList<String>(); - Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); - CollectionTools.addAll(list, 0, iterable); - assertEquals(3, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); - } - - public void testAddAllListIntIterable_EmptyIterable() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = EmptyIterable.instance(); - CollectionTools.addAll(list, 2, iterable); - assertEquals(3, list.size()); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); - } - - public void testAddAllListIntIterableInt() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); - CollectionTools.addAll(list, 2, iterable, 3); - assertEquals(6, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); - } - - public void testAddAllListIntIterableInt_Zero() { - List<String> list = new ArrayList<String>(); - Iterable<String> iterable = Arrays.asList(new String[] { "X", "X", "X" }); - CollectionTools.addAll(list, 0, iterable, 3); - assertEquals(3, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); - } - - public void testAddAllListIntIterableInt_EmptyIterable() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = EmptyIterable.instance(); - CollectionTools.addAll(list, 2, iterable, 0); - assertEquals(3, list.size()); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); - } - - public void testAddAllListIntIterator() { - List<String> list = this.buildStringList1(); - Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); - CollectionTools.addAll(list, 2, iterator); - assertEquals(6, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); - } - - public void testAddAllListIntIterator_Zero() { - List<String> list = new ArrayList<String>(); - Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); - CollectionTools.addAll(list, 0, iterator); - assertEquals(3, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); - } - - public void testAddAllListIntIterator_EmptyIterator() { - List<String> list = this.buildStringList1(); - Iterator<String> iterator = EmptyIterator.instance(); - CollectionTools.addAll(list, 2, iterator); - assertEquals(3, list.size()); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); - } - - public void testAddAllListIntIteratorInt() { - List<String> list = this.buildStringList1(); - Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); - CollectionTools.addAll(list, 2, iterator, 3); - assertEquals(6, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "X", "X", "X", "two" }, list.toArray())); - } - - public void testAddAllListIntIteratorInt_Zero() { - List<String> list = new ArrayList<String>(); - Iterator<String> iterator = Arrays.asList(new String[] { "X", "X", "X" }).iterator(); - CollectionTools.addAll(list, 0, iterator, 3); - assertEquals(3, list.size()); - assertTrue(list.contains("X")); - assertTrue(Arrays.equals(new Object[] { "X", "X", "X" }, list.toArray())); - } - - public void testAddAllListIntIteratorInt_EmptyIterator() { - List<String> list = this.buildStringList1(); - Iterator<String> iterator = EmptyIterator.instance(); - CollectionTools.addAll(list, 2, iterator, 0); - assertEquals(3, list.size()); - assertTrue(Arrays.equals(new Object[] { "zero", "one", "two" }, list.toArray())); - } - - - // ********** bag ********** - - public void testBagEnumeration_String() { - Bag<String> b = CollectionTools.bag(this.buildStringVector1().elements()); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringVector1())); - } - - public void testBagEnumeration_Object() { - Bag<Object> b = CollectionTools.<Object>bag(this.buildStringVector1().elements()); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringVector1())); - } - - public void testBagEnumeration_Empty() { - Bag<Object> b = CollectionTools.<Object>bag(EmptyEnumeration.instance()); - assertEquals(0, b.size()); - } - - public void testBagEnumerationInt() { - Bag<String> b = CollectionTools.bag(this.buildStringVector1().elements(), 3); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringVector1())); - } - - public void testBagEnumerationInt_Empty() { - Bag<String> b = CollectionTools.bag(EmptyEnumeration.<String>instance(), 3); - assertEquals(0, b.size()); - } - - public void testBagIterable() { - Iterable<String> iterable = this.buildStringList1(); - Bag<String> b = CollectionTools.bag(iterable); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } - - public void testBagIterableInt() { - Iterable<String> iterable = this.buildStringList1(); - Bag<String> b = CollectionTools.bag(iterable, 3); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } - - public void testBagIterator_String() { - Bag<String> b = CollectionTools.bag(this.buildStringList1().iterator()); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } - - public void testBagIterator_StringObject() { - Collection<String> c = new ArrayList<String>(); - c.add("zero"); - c.add("one"); - c.add("two"); - c.add("three"); - Bag<Object> b = CollectionTools.<Object>bag(c.iterator()); - assertEquals(4, b.size()); - assertTrue(b.containsAll(c)); - } - - public void testBagIterator_Empty() { - Bag<String> b = CollectionTools.bag(EmptyIterator.<String>instance()); - assertEquals(0, b.size()); - } - - public void testBagIteratorInt() { - Bag<String> b = CollectionTools.bag(this.buildStringList1().iterator(), 3); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } - - public void testBagIteratorInt_Empty() { - Bag<String> b = CollectionTools.bag(EmptyIterator.<String>instance(), 3); - assertEquals(0, b.size()); - } - - public void testBagObjectArray() { - Bag<String> b = CollectionTools.bag(this.buildStringArray1()); - assertEquals(3, b.size()); - assertTrue(CollectionTools.containsAll(b, (Object[]) this.buildStringArray1())); - } - - public void testBagObjectArray_Vararg() { - Bag<String> b = CollectionTools.bag("foo", "bar", "baz"); - assertEquals(3, b.size()); - assertTrue(CollectionTools.containsAll(b, new Object[]{"foo", "bar", "baz"})); - } - - public void testBagObjectArray_Empty() { - Bag<String> b = CollectionTools.bag(Bag.Empty.<String>instance()); - assertEquals(0, b.size()); - } - - - // ********** collection ********** - - public void testCollectionEnumeration() { - Collection<String> c = CollectionTools.collection(this.buildStringVector1().elements()); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringVector1())); - } - - public void testCollectionEnumeration_ObjectString() { - Collection<Object> c = CollectionTools.<Object>collection(this.buildStringVector1().elements()); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringVector1())); - } - - public void testCollectionEnumerationInt() { - Collection<String> c = CollectionTools.collection(this.buildStringVector1().elements(), 3); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringVector1())); - } - - public void testCollectionIterable() { - Iterable<String> iterable = this.buildStringList1(); - Collection<String> c = CollectionTools.collection(iterable); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringList1())); - } - - public void testCollectionIterableInt() { - Iterable<String> iterable = this.buildStringList1(); - Collection<String> c = CollectionTools.collection(iterable, 3); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringList1())); - } - - public void testCollectionIterator() { - Collection<String> c = CollectionTools.collection(this.buildStringList1().iterator()); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringList1())); - } - - public void testCollectionIterator_ObjectString() { - Collection<Object> c = CollectionTools.<Object>collection(this.buildStringList1().iterator()); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringList1())); - } - - public void testCollectionIteratorInt() { - Collection<String> c = CollectionTools.collection(this.buildStringList1().iterator(), 3); - assertEquals(3, c.size()); - assertTrue(c.containsAll(this.buildStringList1())); - } - - public void testCollectionObjectArray() { - Collection<String> c = CollectionTools.collection(this.buildStringArray1()); - assertEquals(3, c.size()); - assertTrue(CollectionTools.containsAll(c, (Object[]) this.buildStringArray1())); - } - - - // ********** contains ********** - - public void testContainsEnumerationObject_String() { - Vector<String> v = this.buildStringVector1(); - assertTrue(CollectionTools.contains(v.elements(), "one")); - assertFalse(CollectionTools.contains(v.elements(), null)); - v.add(null); - assertTrue(CollectionTools.contains(v.elements(), null)); - } - - public void testContainsEnumerationObject_Object() { - Vector<Object> c = new Vector<Object>(); - c.add("zero"); - c.add("one"); - c.add("two"); - c.add("three"); - String one = "one"; - assertTrue(CollectionTools.contains(c.elements(), one)); - assertFalse(CollectionTools.contains(c.elements(), null)); - c.add(null); - assertTrue(CollectionTools.contains(c.elements(), null)); - } - - public void testContainsIterableObject() { - Collection<String> c = this.buildStringList1(); - Iterable<String> iterable = c; - assertTrue(CollectionTools.contains(iterable, "one")); - assertFalse(CollectionTools.contains(iterable, null)); - c.add(null); - assertTrue(CollectionTools.contains(iterable, null)); - } - - public void testContainsIteratorObject_String() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.contains(c.iterator(), "one")); - assertFalse(CollectionTools.contains(c.iterator(), null)); - c.add(null); - assertTrue(CollectionTools.contains(c.iterator(), null)); - } - - public void testContainsIteratorObject_Object() { - Collection<Object> c = new HashBag<Object>(); - c.add("zero"); - c.add("one"); - c.add("two"); - c.add("three"); - String one = "one"; - assertTrue(CollectionTools.contains(c.iterator(), one)); - assertFalse(CollectionTools.contains(c.iterator(), null)); - c.add(null); - assertTrue(CollectionTools.contains(c.iterator(), null)); - } - - - // ********** contains all ********** - - public void testContainsAllCollectionIterable() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(this.buildStringList1(), iterable)); - } - - public void testContainsAllCollectionIterator_String() { - assertTrue(CollectionTools.containsAll(this.buildStringList1(), this.buildStringList1().iterator())); - } - - public void testContainsAllCollectionIterator_Object() { - Collection<Object> c1 = new ArrayList<Object>(); - c1.add("zero"); - c1.add("one"); - c1.add("two"); - Collection<String> c2 = new ArrayList<String>(); - c2.add("two"); - c2.add("zero"); - c2.add("one"); - assertTrue(CollectionTools.containsAll(c1, c2.iterator())); - } - - public void testContainsAllCollectionObjectArray_StringObject() { - assertTrue(CollectionTools.containsAll(this.buildStringList1(), this.buildObjectArray1())); - } - - public void testContainsAllCollectionObjectArray() { - Object[] a = new Object[] { "zero", "one", "two" }; - assertTrue(CollectionTools.containsAll(this.buildStringList1(), a)); - } - - public void testContainsAllIterableCollection() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable, this.buildStringList1())); - } - - public void testContainsAllIterableIntCollection() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable, 3, this.buildStringList1())); - } - - public void testContainsAllIterableIterable() { - Iterable<String> iterable1 = this.buildStringList1(); - Iterable<String> iterable2 = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable1, iterable2)); - } - - public void testContainsAllIterableIntIterable() { - Iterable<String> iterable1 = this.buildStringList1(); - Iterable<String> iterable2 = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable1, 3, iterable2)); - } - - public void testContainsAllIterableIterator() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable, this.buildStringList1().iterator())); - } - - public void testContainsAllIterableIntIterator() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable, 3, this.buildStringList1().iterator())); - } - - public void testContainsAllIterableObjectArray() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable, this.buildObjectArray1())); - iterable = this.buildStringList2(); - assertFalse(CollectionTools.containsAll(iterable, this.buildObjectArray1())); - } - - public void testContainsAllIterableIntObjectArray() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(iterable, 3, this.buildObjectArray1())); - iterable = this.buildStringList2(); - assertFalse(CollectionTools.containsAll(iterable, 3, this.buildObjectArray1())); - } - - public void testContainsAllIteratorCollection_StringString() { - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList1())); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList2())); - } - - public void testContainsAllIteratorCollection_ObjectString() { - Collection<Object> c1 = new ArrayList<Object>(); - c1.add("zero"); - c1.add("one"); - c1.add("two"); - Collection<String> c2 = new ArrayList<String>(); - c2.add("zero"); - c2.add("one"); - c2.add("two"); - assertTrue(CollectionTools.containsAll(c1.iterator(), c2)); - } - - public void testContainsAllIteratorIntCollection() { - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 5, this.buildStringList1())); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 5, this.buildStringList2())); - } - - public void testContainsAllIteratorIterable() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), iterable)); - iterable = this.buildStringList2(); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), iterable)); - } - - public void testContainsAllIteratorIntIterable() { - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, iterable)); - iterable = this.buildStringList2(); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, iterable)); - } - - public void testContainsAllIteratorIterator_StringString() { - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList1().iterator())); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildStringList2().iterator())); - } - - public void testContainsAllIteratorIterator_ObjectString() { - Collection<Object> c1 = new ArrayList<Object>(); - c1.add("zero"); - c1.add("one"); - c1.add("two"); - Collection<String> c2 = new ArrayList<String>(); - c2.add("zero"); - c2.add("one"); - c2.add("two"); - assertTrue(CollectionTools.containsAll(c1.iterator(), c2.iterator())); - } - - public void testContainsAllIteratorIntIterator() { - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildStringList1().iterator())); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildStringList2().iterator())); - } - - public void testContainsAllIteratorObjectArray() { - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildObjectArray1())); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), this.buildObjectArray2())); - } - - public void testContainsAllIteratorIntObjectArray() { - assertTrue(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildObjectArray1())); - assertFalse(CollectionTools.containsAll(this.buildStringList1().iterator(), 3, this.buildObjectArray2())); - } - - - // ********** diff ********** - - public void testDiffEndListList() { - List<String> list1 = new ArrayList<String>(); - list1.add("a"); - list1.add("b"); - list1.add("c"); - List<String> list2 = new ArrayList<String>(); - list2.add(new String("a")); - list2.add(new String("b")); - list2.add(new String("c")); - assertEquals(-1, CollectionTools.diffEnd(list1, list2)); - } - - public void testDiffRangeListList() { - List<String> list1 = new ArrayList<String>(); - list1.add("a"); - list1.add("b"); - list1.add("c"); - List<String> list2 = new ArrayList<String>(); - list2.add(new String("a")); - list2.add(new String("b")); - list2.add(new String("c")); - assertEquals(new Range(3, -1), CollectionTools.diffRange(list1, list2)); - } - - public void testDiffStartListList() { - List<String> list1 = new ArrayList<String>(); - list1.add("a"); - list1.add("b"); - list1.add("c"); - List<String> list2 = new ArrayList<String>(); - list2.add(new String("a")); - list2.add(new String("b")); - list2.add(new String("c")); - assertEquals(3, CollectionTools.diffStart(list1, list2)); - } - - - // ********** identity diff ********** - - public void testIdentityDiffEndListList() { - List<String> list1 = new ArrayList<String>(); - list1.add("a"); - list1.add("b"); - list1.add("c"); - List<String> list2 = new ArrayList<String>(); - list2.add("a"); - list2.add("b"); - list2.add("c"); - assertEquals(-1, CollectionTools.identityDiffEnd(list1, list2)); - } - - public void testIdentityDiffRangeListList() { - List<String> list1 = new ArrayList<String>(); - list1.add("a"); - list1.add("b"); - list1.add("c"); - List<String> list2 = new ArrayList<String>(); - list2.add("a"); - list2.add("b"); - list2.add("c"); - assertEquals(new Range(3, -1), CollectionTools.identityDiffRange(list1, list2)); - } - - public void testIdentityDiffStartListList() { - List<String> list1 = new ArrayList<String>(); - list1.add("a"); - list1.add("b"); - list1.add("c"); - List<String> list2 = new ArrayList<String>(); - list2.add("a"); - list2.add("b"); - list2.add("c"); - assertEquals(3, CollectionTools.identityDiffStart(list1, list2)); - } - - - // ********** elements are equal ********** - - public void testElementsAreDifferentIterableIterable() { - List<String> list1 = new ArrayList<String>(); - list1.add("1000"); - list1.add("2000"); - list1.add("3000"); - list1.add("4000"); - - List<String> list2 = new ArrayList<String>(); - - assertTrue(CollectionTools.elementsAreDifferent(list1, list2)); - assertFalse(CollectionTools.elementsAreEqual(list1, list2)); - } - - public void testElementsAreDifferentIteratorIterator() { - List<String> list1 = new ArrayList<String>(); - list1.add("1000"); - list1.add("2000"); - list1.add("3000"); - list1.add("4000"); - - List<String> list2 = new ArrayList<String>(); - - assertTrue(CollectionTools.elementsAreDifferent(list1.iterator(), list2.iterator())); - assertFalse(CollectionTools.elementsAreEqual(list1, list2)); - } - - public void testElementsAreEqualIterableIterable() { - List<String> list1 = new ArrayList<String>(); - list1.add("1000"); - list1.add("2000"); - list1.add("3000"); - list1.add("4000"); - - List<String> list2 = new ArrayList<String>(); - for (int i = 0; i < list1.size(); i++) { - list2.add(String.valueOf((i + 1) * 1000)); - } - assertFalse(CollectionTools.elementsAreIdentical(list1, list2)); - assertFalse(CollectionTools.elementsAreDifferent(list1, list2)); - assertTrue(CollectionTools.elementsAreEqual(list1, list2)); - } - - public void testElementsAreEqualIteratorIterator() { - List<String> list1 = new ArrayList<String>(); - list1.add("1000"); - list1.add("2000"); - list1.add("3000"); - list1.add("4000"); - - List<String> list2 = new ArrayList<String>(); - for (int i = 0; i < list1.size(); i++) { - list2.add(String.valueOf((i + 1) * 1000)); - } - assertFalse(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); - assertFalse(CollectionTools.elementsAreDifferent(list1.iterator(), list2.iterator())); - assertTrue(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - - // ********** elements are identical ********** - - public void testElementsAreIdenticalIterableIterable() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - Iterable<String> iterable1 = list1; - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - Iterable<String> iterable2 = list2; - assertTrue(CollectionTools.elementsAreIdentical(iterable1, iterable2)); - assertTrue(CollectionTools.elementsAreEqual(iterable1, iterable2)); - } - - public void testElementsAreIdenticalIteratorIterator() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - assertTrue(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); - assertTrue(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - public void testElementsAreIdenticalIteratorIterator_Not() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - list2.remove(0); - assertFalse(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); - assertFalse(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - public void testElementsAreIdenticalIteratorIterator_DifferentSizes() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - list2.remove(3); - assertFalse(CollectionTools.elementsAreIdentical(list1.iterator(), list2.iterator())); - assertFalse(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - public void testElementsAreNotIdenticalIterableIterable() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - Iterable<String> iterable1 = list1; - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - Iterable<String> iterable2 = list2; - assertFalse(CollectionTools.elementsAreNotIdentical(iterable1, iterable2)); - assertTrue(CollectionTools.elementsAreEqual(iterable1, iterable2)); - } - - public void testElementsAreNotIdenticalIteratorIterator() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - assertFalse(CollectionTools.elementsAreNotIdentical(list1.iterator(), list2.iterator())); - assertTrue(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - public void testElementsAreNotIdenticalIteratorIterator_Not() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - list2.remove(0); - assertTrue(CollectionTools.elementsAreNotIdentical(list1.iterator(), list2.iterator())); - assertFalse(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - public void testElementsAreNotIdenticalIteratorIterator_DifferentSizes() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<String> list2 = new ArrayList<String>(); - for (String s : list1) { - list2.add(s); - } - list2.remove(3); - assertTrue(CollectionTools.elementsAreNotIdentical(list1.iterator(), list2.iterator())); - assertFalse(CollectionTools.elementsAreEqual(list1.iterator(), list2.iterator())); - } - - - // ********** get ********** - - public void testGetIterableInt() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = list; - String o = CollectionTools.get(iterable, 1); - assertEquals("one", o); - list.add(null); - o = CollectionTools.get(iterable, 3); - assertNull(o); - } - - public void testGetIteratorInt1() { - List<String> list = this.buildStringList1(); - String o = CollectionTools.get(list.iterator(), 1); - assertEquals("one", o); - list.add(null); - o = CollectionTools.get(list.iterator(), list.size() - 1); - assertNull(o); - } - - public void testGetIteratorInt2() { - List<String> list = this.buildStringList1(); - boolean exCaught = false; - try { - CollectionTools.get(list.iterator(), list.size()); - fail(); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - // ********** hash code ********** - - public void testHashCodeIterable1() { - Iterable<String> iterable = null; - assertEquals(0, CollectionTools.hashCode(iterable)); - } - - public void testHashCodeIterable2() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = list; - int hashCode = CollectionTools.hashCode(iterable); - assertEquals(list.hashCode(), hashCode); - - list.add(null); - hashCode = CollectionTools.hashCode(iterable); - assertEquals(list.hashCode(), hashCode); - } - - - // ********** index of ********** - - public void testIndexOfIterableObject_String() { - Iterable<String> iterable = this.buildStringList1(); - assertEquals(1, CollectionTools.indexOf(iterable, "one")); - } - - public void testIndexOfIteratorObject_String() { - List<String> list = this.buildStringList1(); - assertEquals(1, CollectionTools.indexOf(list.iterator(), "one")); - } - - public void testIndexOfIteratorObject_String_Not() { - List<String> list = this.buildStringList1(); - assertEquals(-1, CollectionTools.indexOf(list.iterator(), null)); - assertEquals(-1, CollectionTools.indexOf(list.iterator(), "shazam")); - } - - public void testIndexOfIteratorObject_Null() { - List<String> list = this.buildStringList1(); - list.add(null); - assertEquals(list.size() - 1, CollectionTools.indexOf(list.iterator(), null)); - } - - public void testIndexOfIteratorObject_Object() { - List<Object> list = new ArrayList<Object>(); - list.add("0"); - list.add("1"); - list.add("2"); - list.add("3"); - - String one = "1"; - assertEquals(1, CollectionTools.indexOf(list.iterator(), one)); - list.add(null); - assertEquals(list.size() - 1, CollectionTools.indexOf(list.iterator(), null)); - } - - - // ********** insertion index of ********** - - public void testInsertionIndexOfListComparableRandomAccess() { - List<String> list = Arrays.asList(new String[] { "A", "C", "D" }); - assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); - - list = Arrays.asList(new String[] { "A", "B", "C", "D" }); - assertEquals(2, CollectionTools.insertionIndexOf(list, "B")); - - list = Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" }); - assertEquals(4, CollectionTools.insertionIndexOf(list, "B")); - - list = Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" }); - assertEquals(6, CollectionTools.insertionIndexOf(list, "E")); - - list = Arrays.asList(new String[] { "B", "B", "B", "C", "D" }); - assertEquals(0, CollectionTools.insertionIndexOf(list, "A")); - - list = Arrays.asList(new String[] { "A", "A", "B", "B", "C", "D" }); - assertEquals(2, CollectionTools.insertionIndexOf(list, "A")); - } - - public void testInsertionIndexOfListComparableNonRandomAccess() { - List<String> list = new LinkedList<String>(Arrays.asList(new String[] { "A", "C", "D" })); - assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); - - list = new LinkedList<String>(Arrays.asList(new String[] { "A", "B", "C", "D" })); - assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); - - list = new LinkedList<String>(Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" })); - assertEquals(1, CollectionTools.insertionIndexOf(list, "B")); - - list = new LinkedList<String>(Arrays.asList(new String[] { "A", "B", "B", "B", "C", "D" })); - assertEquals(6, CollectionTools.insertionIndexOf(list, "E")); - - list = new LinkedList<String>(Arrays.asList(new String[] { "B", "B", "B", "C", "D" })); - assertEquals(0, CollectionTools.insertionIndexOf(list, "A")); - - list = new LinkedList<String>(Arrays.asList(new String[] { "A", "A", "B", "B", "C", "D" })); - assertEquals(0, CollectionTools.insertionIndexOf(list, "A")); - } - - public void testInsertionIndexOfListObjectComparatorRandomAccess() { - Comparator<String> c = new ReverseComparator<String>(); - List<String> list = Arrays.asList(new String[] { "D", "C", "A" }); - assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); - - list = Arrays.asList(new String[] { "D", "C", "B", "A" }); - assertEquals(3, CollectionTools.insertionIndexOf(list, "B", c)); - - list = Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" }); - assertEquals(5, CollectionTools.insertionIndexOf(list, "B", c)); - - list = Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" }); - assertEquals(0, CollectionTools.insertionIndexOf(list, "E", c)); - - list = Arrays.asList(new String[] { "D", "C", "B", "B", "B" }); - assertEquals(5, CollectionTools.insertionIndexOf(list, "A", c)); - - list = Arrays.asList(new String[] { "D", "C", "B", "B", "A", "A" }); - assertEquals(6, CollectionTools.insertionIndexOf(list, "A", c)); - } - - public void testInsertionIndexOfListObjectComparatorNonRandomAccess() { - Comparator<String> c = new ReverseComparator<String>(); - List<String> list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "A" })); - assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); - - list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "A" })); - assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); - - list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" })); - assertEquals(2, CollectionTools.insertionIndexOf(list, "B", c)); - - list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "B", "A" })); - assertEquals(0, CollectionTools.insertionIndexOf(list, "E", c)); - - list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "B" })); - assertEquals(5, CollectionTools.insertionIndexOf(list, "A", c)); - - list = new LinkedList<String>(Arrays.asList(new String[] { "D", "C", "B", "B", "A", "A" })); - assertEquals(4, CollectionTools.insertionIndexOf(list, "A", c)); - } - - - // ********** is empty ********** - - public void testIsEmptyIterable() { - assertFalse(CollectionTools.isEmpty(buildObjectList1())); - assertTrue(CollectionTools.isEmpty(EmptyIterable.instance())); - } - - public void testIsEmptyIterator() { - assertFalse(CollectionTools.isEmpty(buildObjectList1().iterator())); - assertTrue(CollectionTools.isEmpty(EmptyIterator.instance())); - } - - - // ********** iterable/iterator ********** - - public void testIterableObjectArray() { - String[] strings = this.buildStringArray1(); - int i = 0; - for (String string : CollectionTools.iterable(strings)) { - assertEquals(strings[i++], string); - } - } - - public void testIteratorObjectArray() { - String[] a = this.buildStringArray1(); - int i = 0; - for (Iterator<String> stream = CollectionTools.iterator(a); stream.hasNext(); i++) { - assertEquals(a[i], stream.next()); - } - } - - - // ********** last ********** - - public void testLastIterable1() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = list; - assertEquals("two", CollectionTools.last(iterable)); - list.add(null); - assertEquals(null, CollectionTools.last(iterable)); - } - - public void testLastIterable2() { - Iterable<String> iterable = new ArrayList<String>(); - boolean exCaught = false; - try { - CollectionTools.last(iterable); - fail(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testLastIterator1() { - List<String> list = this.buildStringList1(); - assertEquals("two", CollectionTools.last(list.iterator())); - list.add(null); - assertEquals(null, CollectionTools.last(list.iterator())); - } - - public void testLastIterator2() { - List<String> list = new ArrayList<String>(); - boolean exCaught = false; - try { - CollectionTools.last(list.iterator()); - fail(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - // ********** last index of ********** - - public void testLastIndexOfIterableObject() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = list; - assertEquals(1, CollectionTools.lastIndexOf(iterable, "one")); - list.add(null); - assertEquals(list.size() - 1, CollectionTools.lastIndexOf(iterable, null)); - } - - public void testLastIndexOfIterableIntObject() { - List<String> list = this.buildStringList1(); - Iterable<String> iterable = list; - assertEquals(1, CollectionTools.lastIndexOf(iterable, 23, "one")); - list.add(null); - assertEquals(list.size() - 1, CollectionTools.lastIndexOf(iterable, 42, null)); - } - - public void testLastIndexOfIteratorObject() { - List<String> list = this.buildStringList1(); - assertEquals(1, CollectionTools.lastIndexOf(list.iterator(), "one")); - list.add(null); - assertEquals(list.size() - 1, CollectionTools.lastIndexOf(list.iterator(), null)); - } - - public void testLastIndexOfIteratorObject_Empty() { - assertEquals(-1, CollectionTools.lastIndexOf(EmptyIterator.instance(), "foo")); - } - - public void testLastIndexOfIteratorIntObject() { - List<String> list = this.buildStringList1(); - assertEquals(1, CollectionTools.lastIndexOf(list.iterator(), 3, "one")); - list.add(null); - assertEquals(list.size() - 1, CollectionTools.lastIndexOf(list.iterator(), 4, null)); - } - - public void testLastIndexOfIteratorIntObject_Empty() { - assertEquals(-1, CollectionTools.lastIndexOf(EmptyIterator.instance(), 42, "foo")); - } - - - // ********** list ********** - - public void testListIterable() { - Iterable<String> iterable = this.buildStringList1(); - assertEquals(this.buildStringList1(), CollectionTools.list(iterable)); - } - - public void testListIterableInt() { - Iterable<String> iterable = this.buildStringList1(); - assertEquals(this.buildStringList1(), CollectionTools.list(iterable, 3)); - } - - public void testListIterator_String() { - List<String> list = CollectionTools.list(this.buildStringList1().iterator()); - assertEquals(this.buildStringList1(), list); - } - - public void testListIterator_StringObject() { - List<String> list1 = new ArrayList<String>(); - list1.add("0"); - list1.add("1"); - list1.add("2"); - list1.add("3"); - - List<Object> list2 = CollectionTools.<Object>list(list1.iterator()); - assertEquals(list1, list2); - } - - public void testListIterator_Empty() { - assertEquals(0, CollectionTools.list(EmptyIterator.instance()).size()); - } - - public void testListIteratorInt() { - List<String> list = CollectionTools.list(this.buildStringList1().iterator(), 3); - assertEquals(this.buildStringList1(), list); - } - - public void testListIteratorInt_Empty() { - assertEquals(0, CollectionTools.list(EmptyIterator.instance(), 5).size()); - } - - public void testListObjectArray() { - List<String> list = CollectionTools.list(this.buildStringArray1()); - assertEquals(this.buildStringList1(), list); - } - - public void testListIteratorObjectArray() { - String[] a = this.buildStringArray1(); - int i = 0; - for (ListIterator<String> stream = CollectionTools.listIterator(a); stream.hasNext(); i++) { - assertEquals(a[i], stream.next()); - } - } - - public void testListIteratorObjectArrayInt() { - String[] a = this.buildStringArray1(); - int i = 1; - for (ListIterator<String> stream = CollectionTools.listIterator(a, 1); stream.hasNext(); i++) { - assertEquals(a[i], stream.next()); - } - } - - - // ********** move ********** - - public void testMoveListIntIntRandomAccess() { - List<String> list = new ArrayList<String>(); - CollectionTools.addAll(list, new String[] { "0", "1", "2", "3", "4", "5" }); - - List<String> result = CollectionTools.move(list, 4, 2); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); - - result = CollectionTools.move(list, 0, 5); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 2); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); - } - - public void testMoveListIntIntSequentialAccess() { - List<String> list = new LinkedList<String>(); - CollectionTools.addAll(list, new String[] { "0", "1", "2", "3", "4", "5" }); - - List<String> result = CollectionTools.move(list, 4, 2); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); - - result = CollectionTools.move(list, 0, 5); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 2); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); - } - - public void testMoveListIntIntIntRandomAccess() { - List<String> list = new ArrayList<String>(Arrays.asList(new String[] { "0", "1", "2", "3", "4", "5" })); - - List<String> result = CollectionTools.move(list, 4, 2, 1); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); - - result = CollectionTools.move(list, 0, 5, 1); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 4, 1); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 4, 2); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - - result = CollectionTools.move(list, 0, 1, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "3", "2", "4", "5", "1" }, result.toArray())); - - result = CollectionTools.move(list, 1, 0, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - - result = CollectionTools.move(list, 1, 1, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - - result = CollectionTools.move(list, 1, 0, 0); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - } - - public void testMoveListIntIntIntSequentialAccess() { - List<String> list = new LinkedList<String>(Arrays.asList(new String[] { "0", "1", "2", "3", "4", "5" })); - - List<String> result = CollectionTools.move(list, 4, 2, 1); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "1", "3", "4", "2", "5" }, result.toArray())); - - result = CollectionTools.move(list, 0, 5, 1); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "1", "3", "4", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 4, 1); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "4", "1", "3", "2" }, result.toArray())); - - result = CollectionTools.move(list, 2, 4, 2); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - - result = CollectionTools.move(list, 0, 1, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "0", "3", "2", "4", "5", "1" }, result.toArray())); - - result = CollectionTools.move(list, 1, 0, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - - result = CollectionTools.move(list, 1, 1, 4); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - - result = CollectionTools.move(list, 1, 0, 0); - assertSame(list, result); // the array is modified in place and returned - assertTrue(Arrays.equals(new String[] { "5", "0", "3", "2", "4", "1" }, result.toArray())); - } - - - // ********** remove all ********** - - public void testRemoveAllCollectionIterable() { - Collection<String> c = this.buildStringList1(); - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.removeAll(c, iterable)); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - - c = this.buildStringList1(); - iterable = this.buildStringList2(); - assertFalse(CollectionTools.removeAll(c, iterable)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - } - - public void testRemoveAllCollectionIterableInt() { - Collection<String> c = this.buildStringList1(); - Iterable<String> iterable = this.buildStringList1(); - assertTrue(CollectionTools.removeAll(c, iterable, 4)); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - - c = this.buildStringList1(); - iterable = this.buildStringList2(); - assertFalse(CollectionTools.removeAll(c, iterable, 55)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - } - - public void testRemoveAllCollectionIterator_Empty() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.removeAll(c, this.buildStringList1().iterator())); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - - c = this.buildStringList1(); - assertFalse(CollectionTools.removeAll(c, this.buildStringList2().iterator())); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - c = this.buildStringList1(); - assertFalse(CollectionTools.removeAll(c, EmptyIterator.instance())); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - } - - public void testRemoveAllCollectionIteratorInt_Empty() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.removeAll(c, this.buildStringList1().iterator(), 5)); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - - c = this.buildStringList1(); - assertFalse(CollectionTools.removeAll(c, this.buildStringList2().iterator(), 5)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - c = this.buildStringList1(); - assertFalse(CollectionTools.removeAll(c, EmptyIterator.instance(), 0)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - } - - public void testRemoveAllCollectionIterator_Duplicates() { - Collection<String> c = new ArrayList<String>(); - c.add("a"); - c.add("a"); - c.add("b"); - c.add("c"); - c.add("d"); - c.add("d"); - String[] a = new String[] { "a", "d" }; - Iterator<String> iterator = new ArrayIterator<String>(a); - assertTrue(CollectionTools.removeAll(c, iterator)); - assertEquals(2, c.size()); - assertFalse(c.contains("a")); - assertTrue(c.contains("b")); - assertTrue(c.contains("c")); - assertFalse(c.contains("d")); - - iterator = new ArrayIterator<String>(a); - assertFalse(CollectionTools.removeAll(c, iterator)); - } - - public void testRemoveAllCollectionIterator_ObjectString() { - Collection<Object> c = new ArrayList<Object>(); - c.add("a"); - c.add("a"); - c.add("b"); - c.add("c"); - c.add("d"); - c.add("d"); - String[] a = new String[] { "a", "d" }; - Iterator<String> iterator = new ArrayIterator<String>(a); - assertTrue(CollectionTools.removeAll(c, iterator)); - assertEquals(2, c.size()); - assertFalse(c.contains("a")); - assertTrue(c.contains("b")); - assertTrue(c.contains("c")); - assertFalse(c.contains("d")); - - iterator = new ArrayIterator<String>(a); - assertFalse(CollectionTools.removeAll(c, iterator)); - } - - public void testRemoveAllCollectionObjectArray_Empty() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.removeAll(c, this.buildObjectArray1())); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - - c = this.buildStringList1(); - assertFalse(CollectionTools.removeAll(c, this.buildObjectArray2())); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - c = this.buildStringList1(); - assertFalse(CollectionTools.removeAll(c, new Object[0])); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - } - - public void testRemoveAllCollectionObjectArray_Duplicates() { - Collection<String> c = new ArrayList<String>(); - c.add("a"); - c.add("a"); - c.add("b"); - c.add("c"); - c.add("d"); - c.add("d"); - String[] a = new String[] { "a", "d" }; - assertTrue(CollectionTools.removeAll(c, (Object[]) a)); - assertEquals(2, c.size()); - assertFalse(c.contains("a")); - assertTrue(c.contains("b")); - assertTrue(c.contains("c")); - assertFalse(c.contains("d")); - - assertFalse(CollectionTools.removeAll(c,(Object[]) a)); - } - - public void testRemoveAllCollectionObjectArray_MoreDuplicates() { - Collection<String> c = new ArrayList<String>(); - c.add("a"); - c.add("b"); - c.add("c"); - c.add("d"); - c.add("a"); - c.add("d"); - c.add("d"); - c.add("a"); - c.add("c"); - String[] a = new String[] { "a", "d" }; - assertTrue(CollectionTools.removeAll(c, (Object[]) a)); - assertEquals(3, c.size()); - assertFalse(c.contains("a")); - assertTrue(c.contains("b")); - assertTrue(c.contains("c")); - assertFalse(c.contains("d")); - - assertFalse(CollectionTools.removeAll(c, (Object[]) a)); - } - - - // ********** remove all occurrences ********** - - public void testRemoveAllOccurrencesCollectionObject() { - Collection<String> c = this.buildStringList1(); - assertEquals(3, c.size()); - assertFalse(CollectionTools.removeAllOccurrences(c, "three")); - assertTrue(CollectionTools.removeAllOccurrences(c, "two")); - assertFalse(CollectionTools.removeAllOccurrences(c, "two")); - assertEquals(2, c.size()); - - c.add("five"); - c.add("five"); - c.add("five"); - assertEquals(5, c.size()); - assertTrue(CollectionTools.removeAllOccurrences(c, "five")); - assertFalse(CollectionTools.removeAllOccurrences(c, "five")); - assertEquals(2, c.size()); - - c.add(null); - c.add(null); - c.add(null); - assertEquals(5, c.size()); - assertTrue(CollectionTools.removeAllOccurrences(c, null)); - assertFalse(CollectionTools.removeAllOccurrences(c, null)); - assertEquals(2, c.size()); - } - - - // ********** remove elements at index ********** - - public void testRemoveElementsAtIndexListIntInt() { - List<String> list = new ArrayList<String>(Arrays.asList(new String[] { "A", "B", "A", "C", "A", "D" })); - List<String> removed = CollectionTools.removeElementsAtIndex(list, 3, 2); - assertTrue(Arrays.equals(new String[] { "A", "B", "A", "D" }, list.toArray())); - assertTrue(Arrays.equals(new String[] { "C", "A" }, removed.toArray())); - - list = new ArrayList<String>(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" })); - removed = CollectionTools.removeElementsAtIndex(list, 3, 3); - assertTrue(Arrays.equals(new String[] { "A", "B", "C" }, list.toArray())); - assertTrue(Arrays.equals(new String[] { "D", "E", "F" }, removed.toArray())); - - list = new ArrayList<String>(Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" })); - removed = CollectionTools.removeElementsAtIndex(list, 0, 3); - assertTrue(Arrays.equals(new String[] { "D", "E", "F" }, list.toArray())); - assertTrue(Arrays.equals(new String[] { "A", "B", "C" }, removed.toArray())); - } - - - // ********** remove duplicate elements ********** - - public void testRemoveDuplicateElementsList1() { - List<String> list = this.buildStringVector1(); - list.add("zero"); - list.add("zero"); - list.add("two"); - list.add("zero"); - assertTrue(CollectionTools.removeDuplicateElements(list)); - int i = 0; - assertEquals("zero", list.get(i++)); - assertEquals("one", list.get(i++)); - assertEquals("two", list.get(i++)); - assertEquals(i, list.size()); - } - - public void testRemoveDuplicateElementsList2() { - List<String> list = this.buildStringVector1(); - assertFalse(CollectionTools.removeDuplicateElements(list)); - int i = 0; - assertEquals("zero", list.get(i++)); - assertEquals("one", list.get(i++)); - assertEquals("two", list.get(i++)); - assertEquals(i, list.size()); - } - - public void testRemoveDuplicateElementsList_Empty() { - List<String> list = new ArrayList<String>(); - assertFalse(CollectionTools.removeDuplicateElements(list)); - assertEquals(0, list.size()); - } - - public void testRemoveDuplicateElementsList_SingleElement() { - List<String> list = new ArrayList<String>(); - list.add("zero"); - assertFalse(CollectionTools.removeDuplicateElements(list)); - assertEquals(1, list.size()); - } - - - // ********** retain all ********** - - public void testRetainAllCollectionIterable() { - Collection<String> c = this.buildStringList1(); - Iterable<String> iterable = this.buildStringList1(); - assertFalse(CollectionTools.retainAll(c, iterable)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - iterable = this.buildStringList2(); - assertTrue(CollectionTools.retainAll(c, iterable)); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - } - - public void testRetainAllCollectionIterableInt() { - Collection<String> c = this.buildStringList1(); - Iterable<String> iterable = this.buildStringList1(); - assertFalse(CollectionTools.retainAll(c, iterable)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - iterable = this.buildStringList2(); - assertTrue(CollectionTools.retainAll(c, iterable, 7)); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - } - - public void testRetainAllCollectionIterator() { - Collection<String> c = this.buildStringList1(); - assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator())); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - assertTrue(CollectionTools.retainAll(c, this.buildStringList2().iterator())); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - } - - public void testRetainAllCollectionIterator_ObjectString() { - Collection<Object> c1 = new ArrayList<Object>(); - c1.add("zero"); - c1.add("one"); - c1.add("two"); - - Collection<String> c2 = new ArrayList<String>(); - c2.add("zero"); - c2.add("one"); - c2.add("two"); - - assertFalse(CollectionTools.retainAll(c1, c2.iterator())); - assertEquals(c2.size(), c1.size()); - assertEquals(c2, c1); - - Collection<String> c3 = new ArrayList<String>(); - c3.add("three"); - c3.add("four"); - c3.add("five"); - } - - public void testRetainAllCollectionIterator_EmptyIterator() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.retainAll(c, EmptyIterator.instance())); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionIterator_EmptyCollection() { - Collection<String> c = new ArrayList<String>(); - assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator())); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionIterator_EmptyCollectionEmptyIterator() { - Collection<String> c = new ArrayList<String>(); - assertFalse(CollectionTools.retainAll(c, EmptyIterator.instance())); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionIteratorInt() { - Collection<String> c = this.buildStringList1(); - assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator(), 8)); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - assertTrue(CollectionTools.retainAll(c, this.buildStringList2().iterator(), 9)); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - } - - public void testRetainAllCollectionIteratorInt_EmptyIterator() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.retainAll(c, EmptyIterator.instance(), 0)); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionIteratorInt_EmptyCollection() { - Collection<String> c = new ArrayList<String>(); - assertFalse(CollectionTools.retainAll(c, this.buildStringList1().iterator(), 3)); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionIteratorInt_EmptyCollectionEmptyIterator() { - Collection<String> c = new ArrayList<String>(); - assertFalse(CollectionTools.retainAll(c, EmptyIterator.instance(), 0)); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionObjectArray() { - Collection<String> c = this.buildStringList1(); - assertFalse(CollectionTools.retainAll(c, this.buildObjectArray1())); - assertEquals(this.buildStringList1().size(), c.size()); - assertEquals(this.buildStringList1(), c); - - assertTrue(CollectionTools.retainAll(c, this.buildObjectArray2())); - assertEquals(0, c.size()); - assertFalse(c.contains("one")); - assertFalse(c.contains("two")); - assertFalse(c.contains("three")); - } - - public void testRetainAllCollectionObjectArray_EmptyObjectArray() { - Collection<String> c = this.buildStringList1(); - assertTrue(CollectionTools.retainAll(c, new Object[0])); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionObjectArray_EmptyCollection() { - Collection<String> c = new ArrayList<String>(); - assertFalse(CollectionTools.retainAll(c, (Object[]) new String[] { "foo" })); - assertEquals(0, c.size()); - } - - public void testRetainAllCollectionObjectArray_EmptyCollectionEmptyObjectArray() { - Collection<String> c = new ArrayList<String>(); - assertFalse(CollectionTools.retainAll(c, (Object[]) new String[0])); - assertEquals(0, c.size()); - } - - - // ********** reverse list ********** - - public void testReverseListIterable() { - Iterable<String> iterable = this.buildStringList1(); - List<String> actual = CollectionTools.reverseList(iterable); - List<String> expected = this.buildStringList1(); - Collections.reverse(expected); - assertEquals(expected, actual); - } - - public void testReverseListIterableInt() { - Iterable<String> iterable = this.buildStringList1(); - List<String> actual = CollectionTools.reverseList(iterable, 10); - List<String> expected = this.buildStringList1(); - Collections.reverse(expected); - assertEquals(expected, actual); - } - - public void testReverseListIterator_String() { - List<String> actual = CollectionTools.reverseList(this.buildStringList1().iterator()); - List<String> expected = this.buildStringList1(); - Collections.reverse(expected); - assertEquals(expected, actual); - } - - public void testReverseListIterator_Object() { - List<Object> actual = CollectionTools.<Object>reverseList(this.buildStringList1().iterator()); - List<Object> expected = this.buildObjectList1(); - Collections.reverse(expected); - assertEquals(expected, actual); - } - - public void testReverseListIteratorInt() { - List<String> actual = CollectionTools.reverseList(this.buildStringList1().iterator(), 33); - List<String> expected = this.buildStringList1(); - Collections.reverse(expected); - assertEquals(expected, actual); - } - - - // ********** rotate ********** - - public void testRotateList() { - List<String> actual = CollectionTools.rotate(this.buildStringList1()); - List<String> expected = this.buildStringList1(); - Collections.rotate(expected, 1); - assertEquals(expected, actual); - } - - - // ********** set ********** - - public void testSetIterable() { - Iterable<String> iterable = this.buildStringSet1(); - assertEquals(this.buildStringSet1(), CollectionTools.set(iterable)); - } - - public void testSetIterableInt() { - Iterable<String> iterable = this.buildStringSet1(); - assertEquals(this.buildStringSet1(), CollectionTools.set(iterable, 22)); - } - - public void testSetIterator_String() { - assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().iterator())); - } - - public void testSetIterator_Object() { - List<String> list = new ArrayList<String>(); - list.add("0"); - list.add("1"); - list.add("2"); - list.add("3"); - list.add("0"); - list.add("1"); - list.add("2"); - list.add("3"); - Set<String> set = new HashSet<String>(); - set.addAll(list); - - assertEquals(set, CollectionTools.<Object>set(list.iterator())); - } - - public void testSetIteratorInt() { - assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().iterator(), 3)); - } - - public void testSetObjectArray() { - assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().toArray())); - } - - - // ********** singleton iterator ********** - - public void testSingletonIterator_String() { - Iterator<String> stream = CollectionTools.singletonIterator("foo"); - assertTrue(stream.hasNext()); - assertEquals("foo", stream.next()); - } - - public void testSingletonIterator_Object() { - Iterator<Object> stream = CollectionTools.<Object>singletonIterator("foo"); - assertTrue(stream.hasNext()); - assertEquals("foo", stream.next()); - } - - public void testSingletonIterator_Cast() { - Iterator<Object> stream = CollectionTools.singletonIterator((Object) "foo"); - assertTrue(stream.hasNext()); - assertEquals("foo", stream.next()); - } - - public void testSingletonListIterator_String() { - ListIterator<String> stream = CollectionTools.singletonListIterator("foo"); - assertTrue(stream.hasNext()); - assertEquals("foo", stream.next()); - assertFalse(stream.hasNext()); - assertTrue(stream.hasPrevious()); - assertEquals("foo", stream.previous()); - } - - - // ********** size ********** - - public void testSizeIterable() { - Iterable<Object> iterable = this.buildObjectList1(); - assertEquals(3, CollectionTools.size(iterable)); - } - - public void testSizeIterator() { - assertEquals(3, CollectionTools.size(this.buildObjectList1().iterator())); - } - - - // ********** sort ********** - - public void testSortIterable() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(); - ss.addAll(list); - - Iterable<String> iterable1 = list; - Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1); - assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); - } - - public void testSortIterableInt() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(); - ss.addAll(list); - - Iterable<String> iterable1 = list; - Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1, 77); - assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); - } - - public void testSortIterableComparator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); - ss.addAll(list); - - Iterable<String> iterable1 = list; - Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1, new ReverseComparator<String>()); - assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); - } - - public void testSortIterableComparatorInt() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); - ss.addAll(list); - - Iterable<String> iterable1 = list; - Iterable<String> iterable2 = CollectionTools.<String>sort(iterable1, new ReverseComparator<String>(), 77); - assertTrue(CollectionTools.elementsAreEqual(ss, iterable2)); - } - - public void testSortIterator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(); - ss.addAll(list); - - Iterator<String> iterator1 = list.iterator(); - Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1); - assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); - } - - public void testSortIteratorInt() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(); - ss.addAll(list); - - Iterator<String> iterator1 = list.iterator(); - Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1, 77); - assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); - } - - public void testSortIteratorComparator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); - ss.addAll(list); - - Iterator<String> iterator1 = list.iterator(); - Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1, new ReverseComparator<String>()); - assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); - } - - public void testSortIteratorComparatorInt() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss = new TreeSet<String>(new ReverseComparator<String>()); - ss.addAll(list); - - Iterator<String> iterator1 = list.iterator(); - Iterator<String> iterator2 = CollectionTools.<String>sort(iterator1, new ReverseComparator<String>(), 77); - assertTrue(CollectionTools.elementsAreEqual(ss.iterator(), iterator2)); - } - - - // ********** sorted set ********** - - public void testSortedSetIterable() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss1 = new TreeSet<String>(); - ss1.addAll(list); - - Iterable<String> iterable = list; - SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable); - assertEquals(ss1, ss2); - } - - public void testSortedSetIterableInt() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss1 = new TreeSet<String>(); - ss1.addAll(list); - - Iterable<String> iterable = list; - SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable, 5); - assertEquals(ss1, ss2); - } - - public void testSortedSetIterableComparator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss1 = new TreeSet<String>(new ReverseComparator<String>()); - ss1.addAll(list); - - Iterable<String> iterable = list; - SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable, new ReverseComparator<String>()); - assertEquals(ss1, ss2); - } - - public void testSortedSetIterableComparatorInt() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss1 = new TreeSet<String>(new ReverseComparator<String>()); - ss1.addAll(list); - - Iterable<String> iterable = list; - SortedSet<String> ss2 = CollectionTools.<String>sortedSet(iterable, new ReverseComparator<String>(), 5); - assertEquals(ss1, ss2); - } - - public void testSortedSetIterator() { - assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildSortedStringSet1().iterator())); - } - - public void testSortedSetIterator_TreeSet() { - SortedSet<String> ss1 = new TreeSet<String>(); - ss1.add("0"); - ss1.add("2"); - ss1.add("3"); - ss1.add("1"); - - SortedSet<String> set2 = CollectionTools.<String>sortedSet(ss1.iterator()); - assertEquals(ss1, set2); - } - - public void testSortedSetIteratorInt() { - assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildSortedStringSet1().iterator(), 8)); - } - - public void testSortedSetObjectArray() { - assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildStringSet1().toArray(new String[0]))); - } - - public void testSortedSetObjectArrayComparator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("0"); - list.add("2"); - list.add("3"); - list.add("1"); - - SortedSet<String> ss1 = new TreeSet<String>(new ReverseComparator<String>()); - ss1.addAll(list); - - String[] array = list.toArray(new String[list.size()]); - SortedSet<String> ss2 = CollectionTools.<String>sortedSet(array, new ReverseComparator<String>()); - assertEquals(ss1, ss2); - } - - - // ********** Old School Vector ********** - - public void testVectorIterable() { - Iterable<String> iterable = this.buildStringList1(); - Vector<String> v = CollectionTools.vector(iterable); - assertEquals(3, v.size()); - assertTrue(v.containsAll(this.buildStringList1())); - } - - public void testVectorIterableInt() { - Iterable<String> iterable = this.buildStringList1(); - Vector<String> v = CollectionTools.vector(iterable, 8); - assertEquals(3, v.size()); - assertTrue(v.containsAll(this.buildStringList1())); - } - - public void testVectorIterator_String() { - Vector<String> v = CollectionTools.vector(this.buildStringList1().iterator()); - assertEquals(3, v.size()); - assertTrue(v.containsAll(this.buildStringList1())); - } - - public void testVectorIterator_Object() { - Vector<Object> v = CollectionTools.<Object>vector(this.buildStringList1().iterator()); - assertEquals(3, v.size()); - assertTrue(v.containsAll(this.buildStringList1())); - } - - public void testVectorIteratorInt() { - Vector<String> v = CollectionTools.vector(this.buildStringList1().iterator(), 7); - assertEquals(3, v.size()); - assertTrue(v.containsAll(this.buildStringList1())); - } - - public void testVectorObjectArray() { - Vector<String> v = CollectionTools.vector(this.buildStringArray1()); - assertEquals(3, v.size()); - assertTrue(v.containsAll(this.buildStringList1())); - } - - - // ********** single-use iterable ********** - - public void testIterableIterator() { - Iterator<Object> emptyIterator = EmptyIterator.instance(); - Iterable<Object> emptyIterable = CollectionTools.iterable(emptyIterator); - - assertFalse(emptyIterable.iterator().hasNext()); - - boolean exceptionThrown = false; - try { - emptyIterator = emptyIterable.iterator(); - fail("invalid iterator: " + emptyIterator); - } catch (IllegalStateException ise) { - exceptionThrown = true; - } - assertTrue("IllegalStateException not thrown.", exceptionThrown); - } - - public void testIterableIterator_NPE() { - Iterator<Object> nullIterator = null; - boolean exceptionThrown = false; - try { - Iterable<Object> emptyIterable = CollectionTools.iterable(nullIterator); - fail("invalid iterable: " + emptyIterable); - } catch (NullPointerException ise) { - exceptionThrown = true; - } - assertTrue(exceptionThrown); - } - - public void testIterableIterator_ToString() { - Iterator<Object> emptyIterator = EmptyIterator.instance(); - Iterable<Object> emptyIterable = CollectionTools.iterable(emptyIterator); - assertNotNull(emptyIterable.toString()); - } - - - // ********** java.util.Collections enhancements ********** - - public void testCopyListList() { - List<String> src = this.buildStringList1(); - List<String> dest = new ArrayList<String>(); - for (String s : src) { - dest.add(s.toUpperCase()); - } - List<String> result = CollectionTools.copy(dest, src); - assertSame(dest, result); - assertTrue(CollectionTools.elementsAreIdentical(src, dest)); - } - - public void testFillListObject() { - List<String> list = this.buildStringList1(); - List<String> result = CollectionTools.fill(list, "foo"); - assertSame(list, result); - for (String string : result) { - assertEquals("foo", string); - } - } - - public void testShuffleList() { - List<String> list = this.buildStringList1(); - List<String> result = CollectionTools.shuffle(list); - assertSame(list, result); - } - - public void testShuffleListRandom() { - List<String> list = this.buildStringList1(); - List<String> result = CollectionTools.shuffle(list, new Random()); - assertSame(list, result); - } - - public void testSortList() { - List<String> list = this.buildStringList1(); - SortedSet<String> ss = new TreeSet<String>(); - ss.addAll(list); - List<String> result = CollectionTools.sort(list); - assertSame(list, result); - assertTrue(CollectionTools.elementsAreEqual(ss, result)); - } - - public void testSwapListIntInt() { - List<String> list = this.buildStringList1(); - List<String> result = CollectionTools.swap(list, 0, 1); - assertSame(list, result); - List<String> original = this.buildStringList1(); - assertEquals(original.get(0), result.get(1)); - assertEquals(original.get(1), result.get(0)); - assertEquals(original.get(2), result.get(2)); - } - - public void testConstructor() { - boolean exCaught = false; - try { - Object at = ReflectionTools.newInstance(CollectionTools.class); - fail("bogus: " + at); //$NON-NLS-1$ - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InvocationTargetException) { - if (ex.getCause().getCause() instanceof UnsupportedOperationException) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - - // ********** test harness ********** - - private Object[] buildObjectArray1() { - return new Object[] { "zero", "one", "two" }; - } - - private String[] buildStringArray1() { - return new String[] { "zero", "one", "two" }; - } - - private Object[] buildObjectArray2() { - return new Object[] { "three", "four", "five" }; - } - - private Vector<String> buildStringVector1() { - Vector<String> v = new Vector<String>(); - this.addToCollection1(v); - return v; - } - - private List<String> buildStringList1() { - List<String> l = new ArrayList<String>(); - this.addToCollection1(l); - return l; - } - - private List<Object> buildObjectList1() { - List<Object> l = new ArrayList<Object>(); - this.addToCollection1(l); - return l; - } - - private void addToCollection1(Collection<? super String> c) { - c.add("zero"); - c.add("one"); - c.add("two"); - } - - private List<String> buildStringList2() { - List<String> l = new ArrayList<String>(); - this.addToCollection2(l); - return l; - } - - private void addToCollection2(Collection<? super String> c) { - c.add("three"); - c.add("four"); - c.add("five"); - } - - private Set<String> buildStringSet1() { - Set<String> s = new HashSet<String>(); - this.addToCollection1(s); - return s; - } - - private Set<Object> buildObjectSet1() { - Set<Object> s = new HashSet<Object>(); - this.addToCollection1(s); - return s; - } - - private SortedSet<String> buildSortedStringSet1() { - SortedSet<String> s = new TreeSet<String>(); - this.addToCollection1(s); - return s; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ExceptionHandlerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ExceptionHandlerTests.java deleted file mode 100644 index 90f9977935..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ExceptionHandlerTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.ExceptionHandler; - -public class ExceptionHandlerTests extends TestCase { - - public ExceptionHandlerTests(String name) { - super(name); - } - - public void testNullExceptionHandler() { - ExceptionHandler exceptionHandler = ExceptionHandler.Null.instance(); - exceptionHandler.handleException(new NullPointerException()); // just make sure it doesn't blow up? - } - - public void testNullExceptionHandlerToString() { - ExceptionHandler exceptionHandler = ExceptionHandler.Null.instance(); - assertNotNull(exceptionHandler.toString()); - } - - public void testRuntimeExceptionHandler1() { - Exception npe = new Exception(); - ExceptionHandler exceptionHandler = ExceptionHandler.Runtime.instance(); - boolean exCaught = false; - try { - exceptionHandler.handleException(npe); - fail(); - } catch (RuntimeException ex) { - assertSame(npe, ex.getCause()); - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRuntimeExceptionHandler2() { - Exception npe = new NullPointerException(); - ExceptionHandler exceptionHandler = ExceptionHandler.Runtime.instance(); - boolean exCaught = false; - try { - exceptionHandler.handleException(npe); - fail(); - } catch (RuntimeException ex) { - assertSame(npe, ex); - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRuntimeExceptionHandlerToString() { - ExceptionHandler exceptionHandler = ExceptionHandler.Runtime.instance(); - assertNotNull(exceptionHandler.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FileToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FileToolsTests.java deleted file mode 100644 index 5483b8588d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FileToolsTests.java +++ /dev/null @@ -1,593 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.net.URL; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.FileTools; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.Tools; - -@SuppressWarnings("nls") -public class FileToolsTests extends TestCase { - private File tempDir; - - public FileToolsTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.tempDir = this.buildTempDir(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - this.deleteDir(this.tempDir); - } - - public void testFilesIn() { - Collection<File> files = CollectionTools.collection(FileTools.filesIn(this.tempDir.getPath())); - assertEquals("invalid file count", 3, files.size()); - } - - public void testDirectoriesIn() { - Collection<File> files = CollectionTools.collection(FileTools.directoriesIn(this.tempDir.getPath())); - assertEquals("invalid directory count", 2, files.size()); - } - - public void testFilesInTree() { - Collection<File> files = CollectionTools.collection(FileTools.filesInTree(this.tempDir.getPath())); - assertEquals("invalid file count", 9, files.size()); - } - - public void testDirectoriesInTree() { - Collection<File> files = CollectionTools.collection(FileTools.directoriesInTree(this.tempDir.getPath())); - assertEquals("invalid directory count", 3, files.size()); - } - - public void testDeleteDirectory() throws IOException { - // build another temporary directory just for this test - File dir = this.buildTempDir(); - assertTrue("temporary directory not created", dir.exists()); - FileTools.deleteDirectory(dir.getPath()); - assertFalse("temporary directory not deleted", dir.exists()); - } - - public void testDeleteDirectoryContents() throws IOException { - // build another temporary directory just for this test - File dir = this.buildTempDir(); - assertTrue("temporary directory not created", dir.exists()); - FileTools.deleteDirectoryContents(dir.getPath()); - assertTrue("temporary directory should not have been deleted", dir.exists()); - assertTrue("temporary directory contents not deleted", dir.listFiles().length == 0); - dir.delete(); - } - - public void testCopyToFile() throws IOException { - File destFile = new File(this.tempDir, "destfile.txt"); - this.copyToFile(destFile, "testCopyToFile"); - } - - public void testCopyToPreExistingFile() throws IOException { - File destFile = new File(this.tempDir, "destfile.txt"); - Writer writer = new OutputStreamWriter(new FileOutputStream(destFile)); - writer.write("this text should be replaced..."); - writer.close(); - this.copyToFile(destFile, "testCopyToPreExistingFile"); - } - - private void copyToFile(File destFile, String writeString) throws IOException { - File sourceFile = new File(this.tempDir, "sourcefile.txt"); - char[] readBuffer = new char[writeString.length()]; - - Writer writer = new OutputStreamWriter(new FileOutputStream(sourceFile)); - writer.write(writeString); - writer.close(); - - FileTools.copyToFile(sourceFile, destFile); - - Reader reader = new InputStreamReader(new FileInputStream(destFile)); - reader.read(readBuffer); - reader.close(); - String readString = new String(readBuffer); - assertEquals(writeString, readString); - } - - public void testCopyToDirectory() throws IOException { - File sourceFile = new File(this.tempDir, "sourcefile.txt"); - String writeString = "testCopyToDirectory"; - - File destDir = new File(this.tempDir, "destdir"); - destDir.mkdir(); - File destFile = new File(destDir, "sourcefile.txt"); - char[] readBuffer = new char[writeString.length()]; - - Writer writer = new OutputStreamWriter(new FileOutputStream(sourceFile)); - writer.write(writeString); - writer.close(); - - FileTools.copyToDirectory(sourceFile, destDir); - - Reader reader = new InputStreamReader(new FileInputStream(destFile)); - reader.read(readBuffer); - reader.close(); - String readString = new String(readBuffer); - assertEquals(writeString, readString); - - FileTools.copyToDirectory(sourceFile, destDir); //Try again with the directory is already created - reader = new InputStreamReader(new FileInputStream(destFile)); - reader.read(readBuffer); - reader.close(); - readString = new String(readBuffer); - assertEquals(writeString, readString); - } - - public void testFilter() throws IOException { - String prefix = "XXXtestFileXXX"; - File testFile1 = new File(this.tempDir, prefix + "1"); - testFile1.createNewFile(); - File testFile2 = new File(this.tempDir, prefix + "2"); - testFile2.createNewFile(); - - FileFilter filter = this.buildFileFilter(prefix); - Iterator<File> filteredFilesIterator = FileTools.filter(FileTools.filesIn(this.tempDir), filter); - Collection<File> filteredFiles = CollectionTools.collection(filteredFilesIterator); - assertEquals(2, filteredFiles.size()); - assertTrue(filteredFiles.contains(testFile1)); - assertTrue(filteredFiles.contains(testFile2)); - } - - private FileFilter buildFileFilter(final String prefix) { - return new FileFilter() { - public boolean accept(File file) { - return file.getName().startsWith(prefix); - } - }; - } - - public void testStripExtension() { - assertEquals("foo", FileTools.stripExtension("foo.xml")); - assertEquals("foo.bar", FileTools.stripExtension("foo.bar.xml")); - assertEquals("foo", FileTools.stripExtension("foo")); - assertEquals("foo", FileTools.stripExtension("foo.")); - } - - public void testExtension() { - assertEquals(".xml", FileTools.extension("foo.xml")); - assertEquals(".xml", FileTools.extension("foo.bar.xml")); - assertEquals("", FileTools.extension("foo")); - assertEquals("", FileTools.extension("foo,xml")); - assertEquals(".", FileTools.extension("foo.")); - } - - public void testEmptyTemporaryDirectory() throws IOException { - File tempDir1 = FileTools.temporaryDirectory(); - File testFile1 = new File(tempDir1, "junk"); - testFile1.createNewFile(); - - File tempDir2 = FileTools.emptyTemporaryDirectory(); - assertEquals(tempDir1, tempDir2); - assertTrue(tempDir2.isDirectory()); - assertEquals(0, tempDir2.listFiles().length); - tempDir2.delete(); - } - - public void testCanonicalFileName() { - File file1 = new File("foo"); - file1 = new File(file1, "bar"); - file1 = new File(file1, "baz"); - file1 = new File(file1, ".."); - file1 = new File(file1, ".."); - file1 = new File(file1, "bar"); - file1 = new File(file1, "baz"); - File file2 = new File(System.getProperty("user.dir")); - file2 = new File(file2, "foo"); - file2 = new File(file2, "bar"); - file2 = new File(file2, "baz"); - File file3 = FileTools.canonicalFile(file1); - assertEquals(file2, file3); - } - - public void testPathFiles() { - File[] expected; - File[] actual; - - if (Tools.osIsWindows()) { - expected = new File[] { new File("C:/"), new File("C:/foo"), new File("C:/foo/bar"), new File("C:/foo/bar/baz.txt") }; - actual = this.pathFiles(new File("C:/foo/bar/baz.txt")); - assertTrue(Arrays.equals(expected, actual)); - } - - expected = new File[] { new File("/"), new File("/foo"), new File("/foo/bar"), new File("/foo/bar/baz.txt") }; - actual = this.pathFiles(new File("/foo/bar/baz.txt")); - assertTrue(Arrays.equals(expected, actual)); - - expected = new File[] { new File("foo"), new File("foo/bar"), new File("foo/bar/baz.txt") }; - actual = this.pathFiles(new File("foo/bar/baz.txt")); - assertTrue(Arrays.equals(expected, actual)); - - expected = new File[] { new File(".."), new File("../foo"), new File("../foo/bar"), new File("../foo/bar/baz.txt") }; - actual = this.pathFiles(new File("../foo/bar/baz.txt")); - assertTrue(Arrays.equals(expected, actual)); - - expected = new File[] { new File("."), new File("./foo"), new File("./foo/bar"), new File("./foo/bar/baz.txt") }; - actual = this.pathFiles(new File("./foo/bar/baz.txt")); - assertTrue(Arrays.equals(expected, actual)); - } - - private File[] pathFiles(File file) { - return (File[]) ReflectionTools.executeStaticMethod(FileTools.class, "pathFiles", File.class, file); - } - - public void testRelativeParentFile() { - assertEquals(new File(".."), this.relativeParentFile(1)); - assertEquals(new File("../.."), this.relativeParentFile(2)); - assertEquals(new File("../../.."), this.relativeParentFile(3)); - - boolean exCaught = false; - try { - File file = this.relativeParentFile(0); - fail("invalid return: " + file); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof InvocationTargetException) { - InvocationTargetException ite = (InvocationTargetException) ex.getCause(); - if (ite.getTargetException() instanceof IllegalArgumentException) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - private File relativeParentFile(int len) { - return (File) ReflectionTools.executeStaticMethod(FileTools.class, "relativeParentFile", int.class, new Integer(len)); - } - - public void testConvertToRelativeFile() { - String prefix = Tools.osIsWindows() ? "C:" : ""; - File file; - File dir; - File relativeFile; - - if (Tools.osIsWindows()) { - // on Windows, a drive must be specified for a file to be absolute (i.e. not relative) - this.verifyUnchangedRelativeFile("/dir1/dir2/file.txt", "C:/dir1/dir2"); - // different drives - this.verifyUnchangedRelativeFile("D:/dir1/dir2/file.txt", "C:/dir1/dir2"); - } - this.verifyUnchangedRelativeFile("dir1/dir2/file.txt", prefix + "/dir1/dir2"); - this.verifyUnchangedRelativeFile("./dir1/dir2/file.txt", prefix + "/dir1/dir2"); - this.verifyUnchangedRelativeFile("../../dir1/dir2/file.txt", prefix + "/dir1/dir2"); - - file = new File(prefix + "/dir1/dir2"); - dir = new File(prefix + "/dir1/dir2"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("."), relativeFile); - - file = new File(prefix + "/dir1/dir2/file.txt"); - dir = new File(prefix + "/dir1/dir2"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("file.txt"), relativeFile); - - file = new File(prefix + "/dir1/dir2/../dir2/file.txt"); - dir = new File(prefix + "/dir1/dir2"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("file.txt"), relativeFile); - - file = new File(prefix + "/dir1/dir2/dir3/dir4/dir5/file.txt"); - dir = new File(prefix + "/dir1/dir2"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("dir3/dir4/dir5/file.txt"), relativeFile); - - file = new File(prefix + "/dir1/dir2/file.txt"); - dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("../../../file.txt"), relativeFile); - - file = new File(prefix + "/dir1/dir2/file.txt"); - dir = new File(prefix + "/dir1/dir2/dir3"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("../file.txt"), relativeFile); - - file = new File(prefix + "/dir1/dir2/dirA/dirB/dirC/file.txt"); - dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("../../../dirA/dirB/dirC/file.txt"), relativeFile); - - file = new File(prefix + "/dir1/dir2"); - dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("../../.."), relativeFile); - - file = new File(prefix + "/My Documents/My Workspace/Project 1/lib/toplink.jar"); - dir = new File(prefix + "/My Documents/My Workspace/Project 1"); - relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(new File("lib/toplink.jar"), relativeFile); - } - - private void verifyUnchangedRelativeFile(String fileName, String dirName) { - File file = new File(fileName); - File dir = new File(dirName); - File relativeFile = FileTools.convertToRelativeFile(file, dir); - assertEquals(file, relativeFile); - } - - public void testConvertToAbsoluteFile() { - String prefix = Tools.osIsWindows() ? "C:" : ""; - File file; - File dir; - File absoluteFile; - - if (Tools.osIsWindows()) { - // on Windows, a drive must be specified for a file to be absolute (i.e. not relative) - this.verifyUnchangedAbsoluteFile("C:/dir1/dir2/file.txt", "C:/dir1/dir2"); - // different drives - this.verifyUnchangedAbsoluteFile("D:/dir1/dir2/file.txt", "C:/dir1/dir2"); - } - this.verifyUnchangedAbsoluteFile(prefix + "/dir1/dir2/file.txt", prefix + "/dir1/dir2"); - this.verifyUnchangedAbsoluteFile(prefix + "/./dir1/dir2/file.txt", prefix + "/dir1/dir2"); - this.verifyUnchangedAbsoluteFile(prefix + "/dir1/dir2/../../dir1/dir2/file.txt", prefix + "/dir1/dir2"); - - file = new File("."); - dir = new File(prefix + "/dir1/dir2"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2"), absoluteFile); - - file = new File("./file.txt"); - dir = new File(prefix + "/dir1/dir2"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); - - file = new File("file.txt"); - dir = new File(prefix + "/dir1/dir2"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); - - file = new File("../dir2/file.txt"); - dir = new File(prefix + "/dir1/dir2"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); - - file = new File("dir3/dir4/dir5/file.txt"); - dir = new File(prefix + "/dir1/dir2"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/dir3/dir4/dir5/file.txt"), absoluteFile); - - file = new File("../../../file.txt"); - dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); - - // too many ".." directories will resolve to the root; - // this is consistent with Windows and Linux command shells - file = new File("../../../../../../../../file.txt"); - dir = new File(prefix + "/dir1/dir2"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/file.txt"), absoluteFile); - - file = new File("../file.txt"); - dir = new File(prefix + "/dir1/dir2/dir3"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/file.txt"), absoluteFile); - - file = new File("../../../dirA/dirB/dirC/file.txt"); - dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2/dirA/dirB/dirC/file.txt"), absoluteFile); - - file = new File("../../.."); - dir = new File(prefix + "/dir1/dir2/dir3/dir4/dir5"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/dir1/dir2"), absoluteFile); - - file = new File("lib/toplink.jar"); - dir = new File(prefix + "/My Documents/My Workspace/Project 1"); - absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(new File(prefix + "/My Documents/My Workspace/Project 1/lib/toplink.jar"), absoluteFile); - } - - public void testFileNameIsReserved() { - boolean expected = Tools.osIsWindows(); - assertEquals(expected, FileTools.fileNameIsReserved("CON")); - assertEquals(expected, FileTools.fileNameIsReserved("con")); - assertEquals(expected, FileTools.fileNameIsReserved("cON")); - assertEquals(expected, FileTools.fileNameIsReserved("AUX")); - assertEquals(expected, FileTools.fileNameIsReserved("COM3")); - assertEquals(expected, FileTools.fileNameIsReserved("LPT3")); - assertEquals(expected, FileTools.fileNameIsReserved("nUL")); - assertEquals(expected, FileTools.fileNameIsReserved("Prn")); - } - - public void testFileHasAnyReservedComponents() { - boolean expected = Tools.osIsWindows(); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("C:/CON"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("/con/foo"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("c:/temp/cON"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("bar//baz//AUX"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("COM3//ttt"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("d:/LPT3/xxx"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("c:/my docs and stuff/tuesday/nUL"))); - assertEquals(expected, FileTools.fileHasAnyReservedComponents(new File("Prn"))); - } - - public void testShortenFileNameFile() { - if (Tools.osIsWindows()) { - this.verifyShortenFileNameFileWin(); - } else { - this.verifyShortenFileNameFileNonWin(); - } - } - - private void verifyShortenFileNameFileWin() { - File file = new File("C:\\Documents and Settings\\Administrator\\Desktop\\Project\\Text.txt"); - String fileName = FileTools.shortenFileName(file); - assertEquals("C:\\Documents and Settings\\...\\Desktop\\Project\\Text.txt", fileName); - assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); - - file = new File("C:/"); - fileName = FileTools.shortenFileName(file); - assertEquals("C:\\", fileName); - assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); - } - - private void verifyShortenFileNameFileNonWin() { - File file = new File("/home/administrator/documents and settings/desktop/Project/Text.txt"); - String fileName = FileTools.shortenFileName(file); - assertEquals("/home/administrator/.../desktop/Project/Text.txt", fileName); - assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); - - file = new File("/home"); - fileName = FileTools.shortenFileName(file); - assertEquals("/home", fileName); - assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); - } - - public void testShortenFileNameFileInt() { - if (Tools.osIsWindows()) { - this.verifyShortenFileNameFileIntWin(); - } else { - this.verifyShortenFileNameFileIntNonWin(); - } - } - - private void verifyShortenFileNameFileIntWin() { - File file = new File("C:\\Documents and Settings\\Administrator\\Desktop\\Project\\Text.txt"); - String fileName = FileTools.shortenFileName(file, 31); - assertEquals("C:\\...\\Desktop\\Project\\Text.txt", fileName); - assertEquals(31, fileName.length()); - - file = new File("C:/This is the file name.txt"); - fileName = FileTools.shortenFileName(file, 10); - assertEquals("C:\\This is the file name.txt", fileName); - assertEquals(28, fileName.length()); - } - - private void verifyShortenFileNameFileIntNonWin() { - File file = new File("/home/administrator/documents and settings/desktop/Project/Text.txt"); - String fileName = FileTools.shortenFileName(file, 31); - assertEquals("/home/.../desktop/Project/Text.txt", fileName); - assertEquals(34, fileName.length()); - - file = new File("/This is the file name.txt"); - fileName = FileTools.shortenFileName(file, 10); - assertEquals("/This is the file name.txt", fileName); - assertEquals(26, fileName.length()); - } - - public void testShortenFileNameURL() throws Exception { - if (Tools.osIsWindows()) { - this.verifyShortenFileNameURLWin(); - } else { - this.verifyShortenFileNameURLNonWin(); - } - } - - private void verifyShortenFileNameURLWin() throws Exception { - URL url = new URL("file", "", "C:/Documents and Settings/Administrator/Desktop/Project/Text.txt"); - String fileName = FileTools.shortenFileName(url); - assertEquals("C:\\Documents and Settings\\...\\Desktop\\Project\\Text.txt", fileName); - assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); - } - - private void verifyShortenFileNameURLNonWin() throws Exception { - URL url = new URL("file", "", "/home/administrator/documents and settings/desktop/Project/Text.txt"); - String fileName = FileTools.shortenFileName(url); - assertEquals("/home/administrator/.../desktop/Project/Text.txt", fileName); - assertTrue(fileName.length() <= FileTools.MAXIMUM_SHORTENED_FILE_NAME_LENGTH); - } - - public void testShortenFileNameURLInt() throws Exception { - if (Tools.osIsWindows()) { - this.verifyShortenFileNameURLIntWin(); - } else { - this.verifyShortenFileNameURLIntNonWin(); - } - } - - private void verifyShortenFileNameURLIntWin() throws Exception { - URL url = new URL("file", "", "/C:/Documents and Settings/Administrator/Desktop/Project/Text.txt"); - String fileName = FileTools.shortenFileName(url, 31); - assertEquals("C:\\...\\Desktop\\Project\\Text.txt", fileName); - assertEquals(31, fileName.length()); - } - - private void verifyShortenFileNameURLIntNonWin() throws Exception { - URL url = new URL("file", "", "/home/administrator/documents and settings/desktop/Project/Text.txt"); - String fileName = FileTools.shortenFileName(url, 31); - assertEquals("/home/.../desktop/Project/Text.txt", fileName); - assertEquals(34, fileName.length()); - } - - private void verifyUnchangedAbsoluteFile(String fileName, String dirName) { - File file = new File(fileName); - File dir = new File(dirName); - File absoluteFile = FileTools.convertToAbsoluteFile(file, dir); - assertEquals(file, absoluteFile); - } - - private File buildTempDir() throws IOException { - // build a new directory for each test, to prevent any cross-test effects - File dir = FileTools.newTemporaryDirectory(this.getClass().getSimpleName() + "." + this.getName()); - - File file0a = new File(dir, "file0a"); - file0a.createNewFile(); - File file0b = new File(dir, "file0b"); - file0b.createNewFile(); - File file0c = new File(dir, "file0c"); - file0c.createNewFile(); - - File subdir1 = new File(dir, "subdir1"); - subdir1.mkdir(); - File file1a = new File(subdir1, "file1a"); - file1a.createNewFile(); - File file1b = new File(subdir1, "file1b"); - file1b.createNewFile(); - - File subdir2 = new File(dir, "subdir2"); - subdir2.mkdir(); - File file2a = new File(subdir2, "file2a"); - file2a.createNewFile(); - File file2b = new File(subdir2, "file2b"); - file2b.createNewFile(); - - File subdir3 = new File(subdir2, "subdir3"); - subdir3.mkdir(); - File file3a = new File(subdir3, "file3a"); - file3a.createNewFile(); - File file3b = new File(subdir3, "file3b"); - file3b.createNewFile(); - - return dir; - } - - private void deleteDir(File dir) { - FileTools.deleteDirectory(dir); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FilterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FilterTests.java deleted file mode 100644 index 44ec8ce09a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/FilterTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.Filter; - -@SuppressWarnings("nls") -public class FilterTests extends TestCase { - - public FilterTests(String name) { - super(name); - } - - public void testNullFilter() { - Filter<String> filter = Filter.Transparent.instance(); - assertTrue(filter.accept("")); - assertTrue(filter.accept("foo")); - assertTrue(filter.accept("bar")); - } - - public void testNullFilter_toString() { - Filter<String> filter = Filter.Transparent.instance(); - assertNotNull(filter.toString()); - } - - public void testNullFilter_serialization() throws Exception { - Filter<String> filter = Filter.Transparent.instance(); - assertSame(filter, TestTools.serialize(filter)); - } - - public void testOpaqueFilter() { - Filter<String> filter = Filter.Opaque.instance(); - assertFalse(filter.accept("")); - assertFalse(filter.accept("foo")); - assertFalse(filter.accept("bar")); - } - - public void testOpaqueFilter_toString() { - Filter<String> filter = Filter.Opaque.instance(); - assertNotNull(filter.toString()); - } - - public void testOpaqueFilter_serialization() throws Exception { - Filter<String> filter = Filter.Opaque.instance(); - assertSame(filter, TestTools.serialize(filter)); - } - - public void testDisabledFilter() { - Filter<String> filter = Filter.Disabled.instance(); - boolean exCaught = false; - try { - assertFalse(filter.accept("foo")); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledFilter_toString() { - Filter<String> filter = Filter.Disabled.instance(); - assertNotNull(filter.toString()); - } - - public void testDisabledFilter_serialization() throws Exception { - Filter<String> filter = Filter.Disabled.instance(); - assertSame(filter, TestTools.serialize(filter)); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/HashBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/HashBagTests.java deleted file mode 100644 index df2a10bd28..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/HashBagTests.java +++ /dev/null @@ -1,555 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.Tools; - -@SuppressWarnings("nls") -public class HashBagTests extends TestCase { - private HashBag<String> bag; - - public HashBagTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.bag = this.buildBag(); - } - - private HashBag<String> buildBag() { - HashBag<String> b = new HashBag<String>(); - b.add(null); - b.add(new String("one")); - b.add(new String("two")); - b.add(new String("two")); - b.add(new String("three")); - b.add(new String("three")); - b.add(new String("three")); - b.add(new String("four")); - b.add(new String("four")); - b.add(new String("four")); - b.add(new String("four")); - return b; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - private Collection<String> buildCollection() { - Collection<String> c = new ArrayList<String>(); - c.add(new String("foo")); - c.add(new String("foo")); - c.add(new String("bar")); - c.add(new String("bar")); - c.add(new String("bar")); - return c; - } - - public void testCtorCollection() { - Collection<String> c = this.buildCollection(); - Bag<String> b = new HashBag<String>(c); - for (String s : c) { - assertTrue(b.contains(s)); - } - } - - public void testCtorIntFloat() { - boolean exCaught; - - exCaught = false; - try { - this.bag = new HashBag<String>(-20, 0.66f); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.bag = new HashBag<String>(20, -0.66f); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAdd() { - // the other adds took place in setUp - assertTrue(this.bag.add("five")); - - assertTrue(this.bag.contains("one")); - assertTrue(this.bag.contains("two")); - assertTrue(this.bag.contains("three")); - assertTrue(this.bag.contains("four")); - assertTrue(this.bag.contains("five")); - } - - public void testAddCount() { - // the other adds took place in setUp - this.bag.add("minus3", -3); - this.bag.add("zero", 0); - this.bag.add("five", 5); - - assertFalse(this.bag.contains("minus3")); - assertFalse(this.bag.contains("zero")); - assertEquals(1, this.bag.count("one")); - assertEquals(2, this.bag.count("two")); - assertEquals(3, this.bag.count("three")); - assertEquals(4, this.bag.count("four")); - assertEquals(5, this.bag.count("five")); - - this.bag.add("three", 2); - assertEquals(5, this.bag.count("three")); - } - - public void testAddAll() { - Collection<String> c = this.buildCollection(); - assertTrue(this.bag.addAll(c)); - for (String s : c) { - assertTrue(this.bag.contains(s)); - } - } - - public void testClear() { - assertTrue(this.bag.contains("one")); - assertTrue(this.bag.contains("two")); - assertTrue(this.bag.contains("three")); - assertTrue(this.bag.contains("four")); - assertTrue(this.bag.contains(null)); - assertEquals(11, this.bag.size()); - this.bag.clear(); - assertFalse(this.bag.contains("one")); - assertFalse(this.bag.contains("two")); - assertFalse(this.bag.contains("three")); - assertFalse(this.bag.contains("four")); - assertFalse(this.bag.contains(null)); - assertEquals(0, this.bag.size()); - } - - public void testClone() { - Bag<String> bag2 = this.bag.clone(); - assertTrue(this.bag != bag2); - assertEquals(this.bag, bag2); - assertTrue(this.bag.hashCode() == bag2.hashCode()); - } - - public void testContains() { - assertTrue(this.bag.contains(null)); - assertTrue(this.bag.contains("one")); - assertTrue(this.bag.contains("two")); - assertTrue(this.bag.contains("three")); - assertTrue(this.bag.contains("four")); - assertTrue(this.bag.contains(new String("four"))); - assertTrue(this.bag.contains("fo" + "ur")); - assertFalse(this.bag.contains("five")); - } - - public void testContainsAll() { - Collection<String> c = new ArrayList<String>(); - c.add(null); - c.add(new String("one")); - c.add(new String("two")); - c.add(new String("three")); - c.add(new String("four")); - assertTrue(this.bag.containsAll(c)); - } - - public void testCount() { - assertEquals(0, this.bag.count("zero")); - assertEquals(1, this.bag.count("one")); - assertEquals(2, this.bag.count("two")); - assertEquals(3, this.bag.count("three")); - assertEquals(4, this.bag.count("four")); - assertEquals(0, this.bag.count("five")); - } - - public void testEquals() { - Bag<String> bag2 = this.buildBag(); - assertEquals(this.bag, bag2); - bag2.add("five"); - assertFalse(this.bag.equals(bag2)); - Collection<String> c = new ArrayList<String>(this.bag); - assertFalse(this.bag.equals(c)); - } - - public void testHashCode() { - Bag<String> bag2 = this.buildBag(); - assertEquals(this.bag.hashCode(), bag2.hashCode()); - } - - public void testIsEmpty() { - assertFalse(this.bag.isEmpty()); - this.bag.clear(); - assertTrue(this.bag.isEmpty()); - this.bag.add("foo"); - assertFalse(this.bag.isEmpty()); - } - - public void testEmptyIterator() { - this.bag.clear(); - Iterator<String> iterator = this.bag.iterator(); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - fail(element.toString()); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testIterator() { - int i = 0; - Iterator<String> iterator = this.bag.iterator(); - assertTrue(iterator.hasNext()); - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(11, i); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - fail(element.toString()); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - - iterator.remove(); - assertEquals(10, this.bag.size()); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.iterator(); - this.bag.add("five"); - exCaught = false; - try { - iterator.next(); - } catch (ConcurrentModificationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testUniqueIterator() { - int i = 0; - Iterator<String> iterator = this.bag.uniqueIterator(); - assertTrue(iterator.hasNext()); - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(5, i); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - fail(element.toString()); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.uniqueIterator(); - Object next = null; - while (iterator.hasNext() && !"four".equals(next)) { - next = iterator.next(); - } - iterator.remove(); - assertEquals(7, this.bag.size()); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.uniqueIterator(); - this.bag.add("five"); - exCaught = false; - try { - iterator.next(); - } catch (ConcurrentModificationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testEntries() { - int i = 0; - Iterator<Bag.Entry<String>> iterator = this.bag.entries(); - assertTrue(iterator.hasNext()); - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(5, i); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - fail(element.toString()); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.entries(); - Bag.Entry<String> next = null; - while (iterator.hasNext()) { - next = iterator.next(); - if (next.getElement().equals("four")) { - iterator.remove(); - break; - } - } - assertEquals(7, this.bag.size()); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.entries(); - this.bag.add("five"); - exCaught = false; - try { - iterator.next(); - } catch (ConcurrentModificationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testHashingDistribution() throws Exception { - Bag<String> bigBag = new HashBag<String>(); - for (int i = 0; i < 10000; i++) { - bigBag.add("object" + i); - } - - java.lang.reflect.Field field = bigBag.getClass().getDeclaredField("table"); - field.setAccessible(true); - Object[] table = (Object[]) field.get(bigBag); - int bucketCount = table.length; - int filledBucketCount = 0; - for (Object o : table) { - if (o != null) { - filledBucketCount++; - } - } - float loadFactor = ((float) filledBucketCount) / ((float) bucketCount); - if ((loadFactor < 0.20) || (loadFactor > 0.80)) { - String msg = "poor load factor: " + loadFactor; - if (Tools.jvmIsSun()) { - fail(msg); - } else { - // poor load factor is seen in the Eclipse build environment for some reason... - System.out.println(this.getClass().getName() + '.' + this.getName() + " - " + msg); - TestTools.printSystemProperties(); - } - } - } - - public void testRemove() { - assertTrue(this.bag.remove("one")); - assertFalse(this.bag.contains("one")); - assertFalse(this.bag.remove("one")); - - assertTrue(this.bag.remove("two")); - assertTrue(this.bag.remove("two")); - assertFalse(this.bag.contains("two")); - assertFalse(this.bag.remove("two")); - } - - public void testRemoveCount() { - assertFalse(this.bag.remove("one", 0)); - assertTrue(this.bag.contains("one")); - - assertTrue(this.bag.remove("one", 1)); - assertFalse(this.bag.contains("one")); - assertFalse(this.bag.remove("one")); - - assertFalse(this.bag.remove("two", -3)); - assertTrue(this.bag.remove("two", 1)); - assertTrue(this.bag.contains("two")); - - assertTrue(this.bag.remove("two", 1)); - assertFalse(this.bag.contains("two")); - assertFalse(this.bag.remove("two")); - - assertTrue(this.bag.remove("three", 3)); - assertFalse(this.bag.contains("three")); - assertFalse(this.bag.remove("three")); - } - - public void testRemoveAll() { - Collection<String> c = new ArrayList<String>(); - c.add("one"); - c.add("three"); - assertTrue(this.bag.removeAll(c)); - assertFalse(this.bag.contains("one")); - assertFalse(this.bag.contains("three")); - assertFalse(this.bag.remove("one")); - assertFalse(this.bag.remove("three")); - assertFalse(this.bag.removeAll(c)); - } - - public void testRetainAll() { - Collection<String> c = new ArrayList<String>(); - c.add("one"); - c.add("three"); - assertTrue(this.bag.retainAll(c)); - assertTrue(this.bag.contains("one")); - assertTrue(this.bag.contains("three")); - assertFalse(this.bag.contains("two")); - assertFalse(this.bag.contains("four")); - assertFalse(this.bag.remove("two")); - assertFalse(this.bag.remove("four")); - assertFalse(this.bag.retainAll(c)); - } - - public void testSize() { - assertTrue(this.bag.size() == 11); - this.bag.add("five"); - this.bag.add("five"); - this.bag.add("five"); - this.bag.add("five"); - this.bag.add("five"); - assertEquals(16, this.bag.size()); - } - - public void testSerialization() throws Exception { - Bag<String> bag2 = TestTools.serialize(this.bag); - - assertTrue("same object?", this.bag != bag2); - assertEquals(11, bag2.size()); - assertEquals(this.bag, bag2); - // look for similar elements - assertTrue(bag2.contains(null)); - assertTrue(bag2.contains("one")); - assertTrue(bag2.contains("two")); - assertTrue(bag2.contains("three")); - assertTrue(bag2.contains("four")); - - int nullCount = 0, oneCount = 0, twoCount = 0, threeCount = 0, fourCount = 0; - for (String s : bag2) { - if (s == null) { - nullCount++; - } else if (s.equals("one")) { - oneCount++; - } else if (s.equals("two")) { - twoCount++; - } else if (s.equals("three")) { - threeCount++; - } else if (s.equals("four")) { - fourCount++; - } - } - assertEquals(1, nullCount); - assertEquals(1, oneCount); - assertEquals(2, twoCount); - assertEquals(3, threeCount); - assertEquals(4, fourCount); - } - - public void testToArray() { - Object[] a = this.bag.toArray(); - assertEquals(11, a.length); - assertTrue(ArrayTools.contains(a, null)); - assertTrue(ArrayTools.contains(a, "one")); - assertTrue(ArrayTools.contains(a, "two")); - assertTrue(ArrayTools.contains(a, "three")); - assertTrue(ArrayTools.contains(a, "four")); - } - - public void testToArrayObjectArray() { - String[] a = new String[12]; - a[11] = "not null"; - String[] b = this.bag.toArray(a); - assertEquals(a, b); - assertEquals(12, a.length); - assertTrue(ArrayTools.contains(a, null)); - assertTrue(ArrayTools.contains(a, "one")); - assertTrue(ArrayTools.contains(a, "two")); - assertTrue(ArrayTools.contains(a, "three")); - assertTrue(ArrayTools.contains(a, "four")); - assertTrue(a[11] == null); - } - - public void testToString() { - String s = this.bag.toString(); - assertTrue(s.startsWith("[")); - assertTrue(s.endsWith("]")); - int commaCount = 0; - for (int i = 0; i < s.length(); i++) { - if (s.charAt(i) == ',') { - commaCount++; - } - } - assertEquals(10, commaCount); - assertTrue(s.indexOf("one") != -1); - assertTrue(s.indexOf("two") != -1); - assertTrue(s.indexOf("three") != -1); - assertTrue(s.indexOf("four") != -1); - assertTrue(s.indexOf("null") != -1); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IdentityHashBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IdentityHashBagTests.java deleted file mode 100644 index f1738bdeb5..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IdentityHashBagTests.java +++ /dev/null @@ -1,573 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.IdentityHashBag; -import org.eclipse.jpt.common.utility.internal.Tools; - -@SuppressWarnings("nls") -public class IdentityHashBagTests extends TestCase { - private IdentityHashBag<String> bag; - private String one = "one"; - private String two = "two"; - private String three = "three"; - private String four = "four"; - private String foo = "foo"; - private String bar = "bar"; - - public IdentityHashBagTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.bag = this.buildBag(); - } - - protected IdentityHashBag<String> buildBag() { - IdentityHashBag<String> result = new IdentityHashBag<String>(); - result.add(null); - result.add(this.one); - result.add(this.two); - result.add(this.two); - result.add(this.three); - result.add(this.three); - result.add(this.three); - result.add(this.four); - result.add(this.four); - result.add(this.four); - result.add(this.four); - return result; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - private Collection<String> buildCollection() { - Collection<String> c = new ArrayList<String>(); - c.add(this.foo); - c.add(this.foo); - c.add(this.bar); - c.add(this.bar); - c.add(this.bar); - return c; - } - - public void testCtorCollection() { - Collection<String> c = this.buildCollection(); - IdentityHashBag<String> localBag = new IdentityHashBag<String>(c); - for (String s : c) { - assertTrue(localBag.contains(s)); - } - } - - public void testCtorIntFloat() { - boolean exCaught; - - exCaught = false; - try { - this.bag = new IdentityHashBag<String>(-20, 0.66f); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue("IllegalArgumentException not thrown", exCaught); - - exCaught = false; - try { - this.bag = new IdentityHashBag<String>(20, -0.66f); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue("IllegalArgumentException not thrown", exCaught); - } - - public void testAdd() { - // the other adds took place in setUp - String five = "five"; - assertTrue(this.bag.add(five)); - - assertTrue(this.bag.contains(this.one)); - assertTrue(this.bag.contains(this.two)); - assertTrue(this.bag.contains(this.three)); - assertTrue(this.bag.contains(this.four)); - assertTrue(this.bag.contains(five)); - } - - public void testAddCount() { - String minus3 = "minus3"; - String zero = "zero"; - String five = "five"; - // the other adds took place in setUp - this.bag.add(minus3, -3); - this.bag.add(zero, 0); - this.bag.add(five, 5); - - assertFalse(this.bag.contains(minus3)); - assertFalse(this.bag.contains(zero)); - assertEquals(1, this.bag.count(this.one)); - assertEquals(2, this.bag.count(this.two)); - assertEquals(3, this.bag.count(this.three)); - assertEquals(4, this.bag.count(this.four)); - assertEquals(5, this.bag.count(five)); - - this.bag.add(this.three, 2); - assertEquals(5, this.bag.count(this.three)); - } - - public void testAddAll() { - Collection<String> c = this.buildCollection(); - assertTrue(this.bag.addAll(c)); - for (String s : c) { - assertTrue(this.bag.contains(s)); - } - } - - public void testClear() { - assertTrue(this.bag.contains(this.one)); - assertTrue(this.bag.contains(this.two)); - assertTrue(this.bag.contains(this.three)); - assertTrue(this.bag.contains(this.four)); - assertTrue(this.bag.contains(null)); - assertEquals(11, this.bag.size()); - this.bag.clear(); - assertFalse(this.bag.contains(this.one)); - assertFalse(this.bag.contains(this.two)); - assertFalse(this.bag.contains(this.three)); - assertFalse(this.bag.contains(this.four)); - assertFalse(this.bag.contains(null)); - assertEquals(0, this.bag.size()); - } - - public void testClone() { - IdentityHashBag<String> bag2 = this.bag.clone(); - assertTrue("bad clone", this.bag != bag2); - assertEquals("bad clone", this.bag, bag2); - assertTrue("bad clone", this.bag.hashCode() == bag2.hashCode()); - } - - public void testContains() { - assertTrue(this.bag.contains(null)); - assertTrue(this.bag.contains(this.one)); - assertTrue(this.bag.contains(this.two)); - assertTrue(this.bag.contains(this.three)); - assertTrue(this.bag.contains(this.four)); - - assertFalse(this.bag.contains(new String("four"))); - assertFalse(this.bag.contains("five")); - } - - public void testContainsAll() { - Collection<String> c = new ArrayList<String>(); - c.add(null); - c.add(this.one); - c.add(this.two); - c.add(this.three); - c.add(this.four); - assertTrue(this.bag.containsAll(c)); - c.add(new String(this.four)); - assertFalse(this.bag.containsAll(c)); - } - - public void testCount() { - assertEquals(0, this.bag.count("zero")); - assertEquals(1, this.bag.count("one")); - assertEquals(2, this.bag.count("two")); - assertEquals(3, this.bag.count("three")); - assertEquals(4, this.bag.count("four")); - assertEquals(0, this.bag.count("five")); - } - - public void testEquals() { - IdentityHashBag<String> bag2 = this.buildBag(); - assertEquals(this.bag, bag2); - bag2.add("five"); - assertFalse(this.bag.equals(bag2)); - Collection<String> c = new ArrayList<String>(this.bag); - assertFalse(this.bag.equals(c)); - } - - public void testHashCode() { - IdentityHashBag<String> bag2 = this.buildBag(); - assertEquals(this.bag.hashCode(), bag2.hashCode()); - } - - public void testIsEmpty() { - assertFalse(this.bag.isEmpty()); - this.bag.clear(); - assertTrue(this.bag.isEmpty()); - this.bag.add("foo"); - assertFalse(this.bag.isEmpty()); - } - - public void testEmptyIterator() { - this.bag.clear(); - Iterator<String> iterator = this.bag.iterator(); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + element, exCaught); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - - public void testIterator() { - int i = 0; - Iterator<String> iterator = this.bag.iterator(); - assertTrue(iterator.hasNext()); - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(11, i); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + element, exCaught); - - iterator.remove(); - assertEquals(10, this.bag.size()); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - - // start over - iterator = this.bag.iterator(); - this.bag.add("five"); - exCaught = false; - try { - iterator.next(); - } catch (ConcurrentModificationException ex) { - exCaught = true; - } - assertTrue("ConcurrentModificationException not thrown", exCaught); - } - - public void testUniqueIterator() { - int i = 0; - Iterator<String> iterator = this.bag.uniqueIterator(); - assertTrue(iterator.hasNext()); - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(5, i); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - fail(element.toString()); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.uniqueIterator(); - Object next = null; - while (iterator.hasNext() && !this.four.equals(next)) { - next = iterator.next(); - } - iterator.remove(); - assertEquals(7, this.bag.size()); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.uniqueIterator(); - String five = "five"; - this.bag.add(five); - exCaught = false; - try { - iterator.next(); - } catch (ConcurrentModificationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testEntries() { - int i = 0; - Iterator<org.eclipse.jpt.common.utility.internal.Bag.Entry<String>> iterator = this.bag.entries(); - assertTrue(iterator.hasNext()); - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(5, i); - assertFalse(iterator.hasNext()); - - boolean exCaught = false; - Object element = null; - try { - element = iterator.next(); - fail(element.toString()); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.entries(); - org.eclipse.jpt.common.utility.internal.Bag.Entry<String> next = null; - while (iterator.hasNext()) { - next = iterator.next(); - if (next.getElement().equals(this.four)) { - iterator.remove(); - break; - } - } - assertEquals(7, this.bag.size()); - - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - // start over - iterator = this.bag.entries(); - String five = "five"; - this.bag.add(five); - exCaught = false; - try { - iterator.next(); - } catch (ConcurrentModificationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testHashingDistribution() throws Exception { - IdentityHashBag<String> bigBag = new IdentityHashBag<String>(); - for (int i = 0; i < 10000; i++) { - bigBag.add("object" + i); - } - - java.lang.reflect.Field field = bigBag.getClass().getDeclaredField("table"); - field.setAccessible(true); - Object[] table = (Object[]) field.get(bigBag); - int bucketCount = table.length; - int filledBucketCount = 0; - for (int i = 0; i < bucketCount; i++) { - if (table[i] != null) { - filledBucketCount++; - } - } - float loadFactor = ((float) filledBucketCount) / ((float) bucketCount); - if ((loadFactor < 0.20) || (loadFactor > 0.80)) { - String msg = "poor load factor: " + loadFactor; - if (Tools.jvmIsSun()) { - fail(msg); - } else { - // poor load factor is seen in the Eclipse build environment for some reason... - System.out.println(this.getClass().getName() + '.' + this.getName() + " - " + msg); - TestTools.printSystemProperties(); - } - } - } - - public void testRemove() { - assertTrue(this.bag.remove(this.one)); - assertFalse(this.bag.contains(this.one)); - assertFalse(this.bag.remove(this.one)); - - assertTrue(this.bag.remove(this.two)); - assertTrue(this.bag.remove(this.two)); - assertFalse(this.bag.contains(this.two)); - assertFalse(this.bag.remove(this.two)); - - assertFalse(this.bag.remove(new String(this.three))); - } - - public void testRemoveCount() { - assertFalse(this.bag.remove(this.one, 0)); - assertTrue(this.bag.contains(this.one)); - - assertTrue(this.bag.remove(this.one, 1)); - assertFalse(this.bag.contains(this.one)); - assertFalse(this.bag.remove(this.one)); - - assertFalse(this.bag.remove(this.two, -3)); - assertTrue(this.bag.remove(this.two, 1)); - assertTrue(this.bag.contains(this.two)); - - assertTrue(this.bag.remove(this.two, 1)); - assertFalse(this.bag.contains(this.two)); - assertFalse(this.bag.remove(this.two)); - - assertTrue(this.bag.remove(this.three, 3)); - assertFalse(this.bag.contains(this.three)); - assertFalse(this.bag.remove(this.three)); - } - - public void testRemoveAll() { - Collection<String> c = new ArrayList<String>(); - c.add(this.one); - c.add(new String(this.two)); - c.add(this.three); - assertTrue(this.bag.removeAll(c)); - assertFalse(this.bag.contains(this.one)); - assertTrue(this.bag.contains(this.two)); - assertFalse(this.bag.contains(this.three)); - assertFalse(this.bag.remove(this.one)); - assertTrue(this.bag.remove(this.two)); - assertFalse(this.bag.remove(this.three)); - assertFalse(this.bag.removeAll(c)); - } - - public void testRetainAll() { - Collection<String> c = new ArrayList<String>(); - c.add(this.one); - c.add(new String(this.two)); - c.add(this.three); - assertTrue(this.bag.retainAll(c)); - assertTrue(this.bag.contains(this.one)); - assertFalse(this.bag.contains(this.two)); - assertTrue(this.bag.contains(this.three)); - assertFalse(this.bag.contains(this.four)); - assertFalse(this.bag.remove(this.two)); - assertFalse(this.bag.remove(this.four)); - assertFalse(this.bag.retainAll(c)); - } - - public void testSize() { - assertTrue(this.bag.size() == 11); - String five = "five"; - this.bag.add(five); - this.bag.add(five); - this.bag.add(five); - this.bag.add(five); - this.bag.add(new String(five)); - assertEquals(16, this.bag.size()); - } - - public void testSerialization() throws Exception { - IdentityHashBag<String> bag2 = TestTools.serialize(this.bag); - - assertTrue("same object?", this.bag != bag2); - assertEquals(11, bag2.size()); - assertEquals(CollectionTools.bag(this.bag.iterator()), CollectionTools.bag(bag2.iterator())); - // look for similar elements - assertTrue(CollectionTools.bag(bag2.iterator()).contains(null)); - assertTrue(CollectionTools.bag(bag2.iterator()).contains("one")); - assertTrue(CollectionTools.bag(bag2.iterator()).contains("two")); - assertTrue(CollectionTools.bag(bag2.iterator()).contains("three")); - assertTrue(CollectionTools.bag(bag2.iterator()).contains("four")); - - int nullCount = 0, oneCount = 0, twoCount = 0, threeCount = 0, fourCount = 0; - for (String next : bag2) { - if (next == null) - nullCount++; - else if (next.equals("one")) - oneCount++; - else if (next.equals("two")) - twoCount++; - else if (next.equals("three")) - threeCount++; - else if (next.equals("four")) - fourCount++; - } - assertEquals(1, nullCount); - assertEquals(1, oneCount); - assertEquals(2, twoCount); - assertEquals(3, threeCount); - assertEquals(4, fourCount); - } - - public void testToArray() { - Object[] a = this.bag.toArray(); - assertEquals(11, a.length); - assertTrue(ArrayTools.contains(a, null)); - assertTrue(ArrayTools.contains(a, this.one)); - assertTrue(ArrayTools.contains(a, this.two)); - assertTrue(ArrayTools.contains(a, this.three)); - assertTrue(ArrayTools.contains(a, this.four)); - } - - public void testToArrayObjectArray() { - String[] a = new String[12]; - a[11] = "not null"; - String[] b = this.bag.toArray(a); - assertEquals(a, b); - assertEquals(12, a.length); - assertTrue(ArrayTools.contains(a, null)); - assertTrue(ArrayTools.contains(a, this.one)); - assertTrue(ArrayTools.contains(a, this.two)); - assertTrue(ArrayTools.contains(a, this.three)); - assertTrue(ArrayTools.contains(a, this.four)); - assertTrue(a[11] == null); - } - - public void testToString() { - String s = this.bag.toString(); - assertTrue(s.startsWith("[")); - assertTrue(s.endsWith("]")); - int commaCount = 0; - for (int i = 0; i < s.length(); i++) { - if (s.charAt(i) == ',') { - commaCount++; - } - } - assertEquals("invalid number of commas", 10, commaCount); - assertTrue(s.indexOf("one") != -1); - assertTrue(s.indexOf("two") != -1); - assertTrue(s.indexOf("three") != -1); - assertTrue(s.indexOf("four") != -1); - assertTrue(s.indexOf("null") != -1); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IndentingPrintWriterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IndentingPrintWriterTests.java deleted file mode 100644 index 33d331b5f6..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/IndentingPrintWriterTests.java +++ /dev/null @@ -1,109 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.StringWriter; -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.IndentingPrintWriter; - -@SuppressWarnings("nls") -public class IndentingPrintWriterTests extends TestCase { - StringWriter sw1; - StringWriter sw2; - IndentingPrintWriter ipw1; - IndentingPrintWriter ipw2; - - static final String CR = System.getProperty("line.separator"); - - public IndentingPrintWriterTests(String name) { - super(name); - } - - @Override - public void setUp() throws Exception { - super.setUp(); - this.sw1 = new StringWriter(); - this.ipw1 = new IndentingPrintWriter(this.sw1); - this.sw2 = new StringWriter(); - this.ipw2 = new IndentingPrintWriter(this.sw2, " "); // indent with 4 spaces instead of a tab - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIndent() { - assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); - this.ipw1.indent(); - assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); - } - - public void testUndent() { - assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); - this.ipw1.indent(); - assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); - this.ipw1.undent(); - assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); - } - - public void testIncrementIndentLevel() { - assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); - this.ipw1.incrementIndentLevel(); - assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); - } - - public void testDecrementIndentLevel() { - assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); - this.ipw1.incrementIndentLevel(); - assertEquals("wrong indent level", 1, this.ipw1.getIndentLevel()); - this.ipw1.decrementIndentLevel(); - assertEquals("wrong indent level", 0, this.ipw1.getIndentLevel()); - } - - public void testPrintTab() { - String expected = "foo0" + CR + "\tfoo1" + CR + "\tfoo1" + CR + "\t\tfoo2" + CR + "\tfoo1" + CR + "\tfoo1" + CR + "foo0" + CR; - - this.ipw1.println("foo0"); - this.ipw1.indent(); - this.ipw1.println("foo1"); - this.ipw1.println("foo1"); - this.ipw1.indent(); - this.ipw1.println("foo2"); - this.ipw1.undent(); - this.ipw1.println("foo1"); - this.ipw1.println("foo1"); - this.ipw1.undent(); - this.ipw1.println("foo0"); - - assertEquals("bogus output", expected, this.sw1.toString()); - } - - public void testPrintSpaces() { - String expected = "foo0" + CR + " foo1" + CR + " foo1" + CR + " foo2" + CR + " foo1" + CR + " foo1" + CR + "foo0" + CR; - - this.ipw2.println("foo0"); - this.ipw2.indent(); - this.ipw2.println("foo1"); - this.ipw2.println("foo1"); - this.ipw2.indent(); - this.ipw2.println("foo2"); - this.ipw2.undent(); - this.ipw2.println("foo1"); - this.ipw2.println("foo1"); - this.ipw2.undent(); - this.ipw2.println("foo0"); - - assertEquals("bogus output", expected, this.sw2.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JDBCTypeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JDBCTypeTests.java deleted file mode 100644 index 7853463449..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JDBCTypeTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.sql.Types; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.JDBCType; - -@SuppressWarnings("nls") -public class JDBCTypeTests extends TestCase { - - public JDBCTypeTests(String name) { - super(name); - } - - public void testTypesSize() { - assertEquals(Types.class.getDeclaredFields().length, JDBCType.types().length); - } - - public void testName() { - JDBCType jdbcType; - jdbcType = JDBCType.type(Types.VARCHAR); - assertEquals("VARCHAR", jdbcType.name()); - - jdbcType = JDBCType.type(Types.INTEGER); - assertEquals("INTEGER", jdbcType.name()); - } - - public void testCode() { - JDBCType jdbcType; - jdbcType = JDBCType.type(Types.VARCHAR); - assertEquals(Types.VARCHAR, jdbcType.code()); - - jdbcType = JDBCType.type(Types.INTEGER); - assertEquals(Types.INTEGER, jdbcType.code()); - } - - public void testInvalidTypeCode() throws Exception { - boolean exCaught = false; - try { - JDBCType jdbcType = JDBCType.type(55); - fail("invalid JDBCType: " + jdbcType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidTypeName() throws Exception { - boolean exCaught = false; - try { - JDBCType jdbcType = JDBCType.type("VARCHAR2"); - fail("invalid JDBCType: " + jdbcType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JavaTypeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JavaTypeTests.java deleted file mode 100644 index da07a02a38..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JavaTypeTests.java +++ /dev/null @@ -1,252 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.JavaType; -import org.eclipse.jpt.common.utility.internal.SimpleJavaType; - -@SuppressWarnings("nls") -public class JavaTypeTests extends TestCase { - - public JavaTypeTests(String name) { - super(name); - } - - public void testInvalidElementTypeNull() throws Exception { - boolean exCaught = false; - try { - JavaType javaType = new SimpleJavaType(null, 0); - fail("invalid JavaType: " + javaType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidElementTypeEmpty() throws Exception { - boolean exCaught = false; - try { - JavaType javaType = new SimpleJavaType("", 0); - fail("invalid JavaType: " + javaType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidElementTypeArray() throws Exception { - boolean exCaught = false; - try { - JavaType javaType = new SimpleJavaType(java.lang.Object[].class.getName(), 0); - fail("invalid JavaType: " + javaType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidArrayDepthNegative() throws Exception { - boolean exCaught = false; - try { - JavaType javaType = new SimpleJavaType(java.lang.Object.class.getName(), -2); - fail("invalid JavaType: " + javaType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidVoidArray() throws Exception { - boolean exCaught = false; - try { - JavaType javaType = new SimpleJavaType(void.class.getName(), 2); - fail("invalid JavaType: " + javaType); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testElementTypeName() throws Exception { - JavaType javaType; - javaType = new SimpleJavaType(java.lang.Object.class); - assertEquals("java.lang.Object", javaType.getElementTypeName()); - - javaType = new SimpleJavaType(java.lang.Object[].class); - assertEquals("java.lang.Object", javaType.getElementTypeName()); - - javaType = new SimpleJavaType(int.class); - assertEquals("int", javaType.getElementTypeName()); - - javaType = new SimpleJavaType(int[].class); - assertEquals("int", javaType.getElementTypeName()); - - javaType = new SimpleJavaType(void.class); - assertEquals("void", javaType.getElementTypeName()); - - javaType = new SimpleJavaType(java.util.Map.Entry.class); - assertEquals("java.util.Map$Entry", javaType.getElementTypeName()); - - javaType = new SimpleJavaType(java.util.Map.Entry[][].class); - assertEquals("java.util.Map$Entry", javaType.getElementTypeName()); - } - - public void testArrayDepth() throws Exception { - JavaType javaType; - javaType = new SimpleJavaType(java.lang.Object.class); - assertEquals(0, javaType.getArrayDepth()); - - javaType = new SimpleJavaType(java.lang.Object[].class); - assertEquals(1, javaType.getArrayDepth()); - - javaType = new SimpleJavaType(int.class); - assertEquals(0, javaType.getArrayDepth()); - - javaType = new SimpleJavaType(int[].class); - assertEquals(1, javaType.getArrayDepth()); - - javaType = new SimpleJavaType(void.class); - assertEquals(0, javaType.getArrayDepth()); - - javaType = new SimpleJavaType(java.util.Map.Entry.class); - assertEquals(0, javaType.getArrayDepth()); - - javaType = new SimpleJavaType(java.util.Map.Entry[][].class); - assertEquals(2, javaType.getArrayDepth()); - } - - public void testIsArray() throws Exception { - JavaType javaType; - javaType = new SimpleJavaType(java.lang.Object.class); - assertFalse(javaType.isArray()); - - javaType = new SimpleJavaType(java.lang.Object[].class); - assertTrue(javaType.isArray()); - - javaType = new SimpleJavaType(int.class); - assertFalse(javaType.isArray()); - - javaType = new SimpleJavaType(int[].class); - assertTrue(javaType.isArray()); - - javaType = new SimpleJavaType(void.class); - assertFalse(javaType.isArray()); - - javaType = new SimpleJavaType(java.util.Map.Entry.class); - assertFalse(javaType.isArray()); - - javaType = new SimpleJavaType(java.util.Map.Entry[][].class); - assertTrue(javaType.isArray()); - } - - public void testJavaClass() throws Exception { - this.verifyJavaClass(java.lang.Object.class); - this.verifyJavaClass(java.lang.Object[].class); - this.verifyJavaClass(int.class); - this.verifyJavaClass(int[].class); - this.verifyJavaClass(void.class); - this.verifyJavaClass(java.util.Map.Entry.class); - this.verifyJavaClass(java.util.Map.Entry[][].class); - } - - private void verifyJavaClass(Class<?> javaClass) throws Exception { - JavaType javaType = new SimpleJavaType(javaClass); - assertEquals(javaClass, javaType.getJavaClass()); - } - - public void testJavaClassName() throws Exception { - JavaType javaType; - javaType = new SimpleJavaType(java.lang.Object.class); - assertEquals("java.lang.Object", javaType.getJavaClassName()); - - javaType = new SimpleJavaType(java.lang.Object[].class); - assertEquals("[Ljava.lang.Object;", javaType.getJavaClassName()); - - javaType = new SimpleJavaType(int.class); - assertEquals("int", javaType.getJavaClassName()); - - javaType = new SimpleJavaType(int[].class); - assertEquals("[I", javaType.getJavaClassName()); - - javaType = new SimpleJavaType(void.class); - assertEquals("void", javaType.getJavaClassName()); - - javaType = new SimpleJavaType(java.util.Map.Entry.class); - assertEquals("java.util.Map$Entry", javaType.getJavaClassName()); - - javaType = new SimpleJavaType(java.util.Map.Entry[][].class); - assertEquals("[[Ljava.util.Map$Entry;", javaType.getJavaClassName()); - } - - public void testDescribes() throws Exception { - this.verifyDescribes(java.lang.Object.class); - this.verifyDescribes(java.lang.Object[].class); - this.verifyDescribes(int.class); - this.verifyDescribes(int[].class); - this.verifyDescribes(void.class); - this.verifyDescribes(java.util.Map.Entry.class); - this.verifyDescribes(java.util.Map.Entry[][].class); - } - - private void verifyDescribes(Class<?> javaClass) throws Exception { - JavaType javaType = new SimpleJavaType(javaClass); - assertTrue(javaType.describes(javaClass)); - } - - public void testDeclaration() throws Exception { - JavaType javaType; - javaType = new SimpleJavaType(java.lang.Object.class); - assertEquals("java.lang.Object", javaType.declaration()); - - javaType = new SimpleJavaType(java.lang.Object[].class); - assertEquals("java.lang.Object[]", javaType.declaration()); - - javaType = new SimpleJavaType(int.class); - assertEquals("int", javaType.declaration()); - - javaType = new SimpleJavaType(int[].class); - assertEquals("int[]", javaType.declaration()); - - javaType = new SimpleJavaType(void.class); - assertEquals("void", javaType.declaration()); - - javaType = new SimpleJavaType(java.util.Map.Entry.class); - assertEquals("java.util.Map.Entry", javaType.declaration()); - - javaType = new SimpleJavaType(java.util.Map.Entry[][].class); - assertEquals("java.util.Map.Entry[][]", javaType.declaration()); - } - - public void testIsPrimitive() throws Exception { - JavaType javaType; - javaType = new SimpleJavaType(java.lang.Object.class); - assertFalse(javaType.isPrimitive()); - - javaType = new SimpleJavaType(java.lang.Object[].class); - assertFalse(javaType.isPrimitive()); - - javaType = new SimpleJavaType(int.class); - assertTrue(javaType.isPrimitive()); - - javaType = new SimpleJavaType(int[].class); - assertFalse(javaType.isPrimitive()); - - javaType = new SimpleJavaType(void.class); - assertTrue(javaType.isPrimitive()); - - javaType = new SimpleJavaType(java.util.Map.Entry.class); - assertFalse(javaType.isPrimitive()); - - javaType = new SimpleJavaType(java.util.Map.Entry[][].class); - assertFalse(javaType.isPrimitive()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JptCommonUtilityTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JptCommonUtilityTests.java deleted file mode 100644 index c62bad8a82..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/JptCommonUtilityTests.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.eclipse.jpt.common.utility.tests.internal.command.JptUtilityCommandTests; -import org.eclipse.jpt.common.utility.tests.internal.enumerations.JptUtilityEnumerationsTests; -import org.eclipse.jpt.common.utility.tests.internal.iterables.JptUtilityIterablesTests; -import org.eclipse.jpt.common.utility.tests.internal.iterators.JptUtilityIteratorsTests; -import org.eclipse.jpt.common.utility.tests.internal.model.JptUtilityModelTests; -import org.eclipse.jpt.common.utility.tests.internal.node.JptUtilityNodeTests; -import org.eclipse.jpt.common.utility.tests.internal.synchronizers.JptUtilitySynchronizersTests; - -/** - * decentralize test creation code - */ -public class JptCommonUtilityTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptCommonUtilityTests.class.getPackage().getName()); - - suite.addTest(JptUtilityCommandTests.suite()); - suite.addTest(JptUtilityEnumerationsTests.suite()); - suite.addTest(JptUtilityIterablesTests.suite()); - suite.addTest(JptUtilityIteratorsTests.suite()); - suite.addTest(JptUtilityModelTests.suite()); - suite.addTest(JptUtilityNodeTests.suite()); - suite.addTest(JptUtilitySynchronizersTests.suite()); - - suite.addTestSuite(ArrayToolsTests.class); - suite.addTestSuite(BagTests.class); - suite.addTestSuite(BidiFilterTests.class); - suite.addTestSuite(BidiStringConverterTests.class); - suite.addTestSuite(BidiTransformerTests.class); - suite.addTestSuite(BitToolsTests.class); - suite.addTestSuite(SimpleBooleanReferenceTests.class); - suite.addTestSuite(BooleanToolsTests.class); - suite.addTestSuite(ClasspathTests.class); - suite.addTestSuite(ClassNameTests.class); - suite.addTestSuite(CollectionToolsTests.class); - suite.addTestSuite(ExceptionHandlerTests.class); - suite.addTestSuite(FileToolsTests.class); - suite.addTestSuite(FilterTests.class); - suite.addTestSuite(HashBagTests.class); - suite.addTestSuite(IdentityHashBagTests.class); - suite.addTestSuite(IndentingPrintWriterTests.class); - suite.addTestSuite(SimpleIntReferenceTests.class); - suite.addTestSuite(JavaTypeTests.class); - suite.addTestSuite(JDBCTypeTests.class); - suite.addTestSuite(KeyedSetTests.class); - suite.addTestSuite(ListenerListTests.class); - suite.addTestSuite(MethodSignatureTests.class); - suite.addTestSuite(NameToolsTests.class); - suite.addTestSuite(NotNullFilterTests.class); - suite.addTestSuite(RangeTests.class); - suite.addTestSuite(ReflectionToolsTests.class); - suite.addTestSuite(ReverseComparatorTests.class); - suite.addTestSuite(SimpleAssociationTests.class); - suite.addTestSuite(SimpleObjectReferenceTests.class); - suite.addTestSuite(SimpleQueueTests.class); - suite.addTestSuite(SimpleStackTests.class); - suite.addTestSuite(StringToolsTests.class); - suite.addTestSuite(SynchronizedBooleanTests.class); - suite.addTestSuite(SynchronizedIntTests.class); - suite.addTestSuite(SynchronizedObjectTests.class); - suite.addTestSuite(SynchronizedQueueTests.class); - suite.addTestSuite(SynchronizedStackTests.class); - suite.addTestSuite(ToolsTests.class); - suite.addTestSuite(VersionComparatorTests.class); - suite.addTestSuite(XMLStringEncoderTests.class); - - return suite; - } - - private JptCommonUtilityTests() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/KeyedSetTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/KeyedSetTests.java deleted file mode 100644 index 7c27e5d2a6..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/KeyedSetTests.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Oracle - initial API and implementation - *******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.KeyedSet; - -@SuppressWarnings("nls") -public class KeyedSetTests - extends TestCase { - - private KeyedSet<String, String> nicknames; - - - public KeyedSetTests(String name) { - super(name); - } - - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.nicknames = this.buildNicknames(); - } - - private KeyedSet<String, String> buildNicknames() { - KeyedSet<String, String> ks = new KeyedSet<String, String>(); - ks.addItem("Jimmy", "James Sullivan"); - ks.addKey("Sully", "James Sullivan"); - ks.addItem("Bob", "Robert McKenna"); - ks.addKey("Mac", "Robert McKenna"); - return ks; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testAddItem() { - // items added in setup - assertTrue(this.nicknames.containsItem("James Sullivan")); - assertTrue(this.nicknames.containsItem("Robert McKenna")); - - assertFalse(this.nicknames.containsItem("John Teasdale")); - this.nicknames.addItem("Jack", "John Teasdale"); - assertTrue(this.nicknames.containsItem("John Teasdale")); - - this.nicknames.addItem("Teaser", "John Teasdale"); - assertTrue(this.nicknames.containsItem("John Teasdale")); - assertTrue(this.nicknames.containsKey("Teaser")); - } - - public void testAddKey() { - // items added in setup - assertTrue(this.nicknames.containsKey("Jimmy")); - assertTrue(this.nicknames.containsKey("Sully")); - assertTrue(this.nicknames.containsKey("Bob")); - assertTrue(this.nicknames.containsKey("Mac")); - - assertFalse(this.nicknames.containsKey("Robbie")); - this.nicknames.addKey("Robbie", "Robert McKenna"); - assertTrue(this.nicknames.containsKey("Robbie")); - - boolean exceptionCaught = false; - try { - this.nicknames.addKey("Teaser", "John Teasdale"); - } - catch (IllegalArgumentException iae) { - exceptionCaught = true; - } - assertTrue(exceptionCaught); - } - - public void testGetItem() { - // items added in setup - assertEquals(this.nicknames.getItem("Jimmy"), "James Sullivan"); - assertEquals(this.nicknames.getItem("Sully"), "James Sullivan"); - assertEquals(this.nicknames.getItem("Bob"), "Robert McKenna"); - assertEquals(this.nicknames.getItem("Mac"), "Robert McKenna"); - assertNull(this.nicknames.getItem("Jack")); - } - - public void testRemoveItem() { - // items added in setup - assertTrue(this.nicknames.containsItem("James Sullivan")); - assertTrue(this.nicknames.containsKey("Jimmy")); - assertTrue(this.nicknames.containsKey("Sully")); - - assertTrue(this.nicknames.removeItem("James Sullivan")); - assertFalse(this.nicknames.containsItem("James Sullivan")); - assertFalse(this.nicknames.containsKey("Jimmy")); - assertFalse(this.nicknames.containsKey("Sully")); - - assertFalse(this.nicknames.removeItem("William Goldberg")); - } - - public void testRemoveKey() { - // items added in setup - assertTrue(this.nicknames.containsItem("James Sullivan")); - assertTrue(this.nicknames.containsKey("Jimmy")); - assertTrue(this.nicknames.containsKey("Sully")); - - assertTrue(this.nicknames.removeKey("Jimmy")); - assertTrue(this.nicknames.containsItem("James Sullivan")); - assertFalse(this.nicknames.containsKey("Jimmy")); - assertTrue(this.nicknames.containsKey("Sully")); - - assertTrue(this.nicknames.removeKey("Sully")); - assertFalse(this.nicknames.containsItem("James Sullivan")); - assertFalse(this.nicknames.containsKey("Jimmy")); - assertFalse(this.nicknames.containsKey("Sully")); - - assertFalse(this.nicknames.removeKey("Billy")); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ListenerListTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ListenerListTests.java deleted file mode 100644 index 7dd0f52e9f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ListenerListTests.java +++ /dev/null @@ -1,194 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.Serializable; -import java.util.EventListener; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ListenerList; -import org.eclipse.jpt.common.utility.internal.Tools; - -@SuppressWarnings("nls") -public class ListenerListTests extends TestCase { - - public ListenerListTests(String name) { - super(name); - } - - public void testGetListeners() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener1 = new LocalListener(); - Listener listener2 = new LocalListener(); - Iterable<Listener> listeners = listenerList.getListeners(); - assertEquals(0, CollectionTools.size(listeners)); - - listenerList.add(listener1); - listenerList.add(listener2); - listeners = listenerList.getListeners(); - assertEquals(2, CollectionTools.size(listeners)); - assertTrue(CollectionTools.contains(listeners, listener1)); - assertTrue(CollectionTools.contains(listeners, listener2)); - } - - public void testSize() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener1 = new LocalListener(); - Listener listener2 = new LocalListener(); - assertEquals(0, listenerList.size()); - - listenerList.add(listener1); - listenerList.add(listener2); - assertEquals(2, listenerList.size()); - } - - public void testIsEmpty() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener1 = new LocalListener(); - Listener listener2 = new LocalListener(); - assertTrue(listenerList.isEmpty()); - - listenerList.add(listener1); - listenerList.add(listener2); - assertFalse(listenerList.isEmpty()); - } - - public void testAdd_null() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - boolean exCaught = false; - try { - listenerList.add(null); - fail("invalid listener list: " + listenerList); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAdd_duplicate() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener = new LocalListener(); - listenerList.add(listener); - - boolean exCaught = false; - try { - listenerList.add(listener); - fail("invalid listener list: " + listenerList); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemove() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener1 = new LocalListener(); - Listener listener2 = new LocalListener(); - listenerList.add(listener1); - listenerList.add(listener2); - assertTrue(CollectionTools.contains(listenerList.getListeners(), listener1)); - assertTrue(CollectionTools.contains(listenerList.getListeners(), listener2)); - - listenerList.remove(listener1); - assertFalse(CollectionTools.contains(listenerList.getListeners(), listener1)); - assertTrue(CollectionTools.contains(listenerList.getListeners(), listener2)); - - listenerList.remove(listener2); - assertFalse(CollectionTools.contains(listenerList.getListeners(), listener2)); - } - - public void testRemove_null() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - boolean exCaught = false; - try { - listenerList.remove(null); - fail("invalid listener list: " + listenerList); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemove_unregistered() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener = new LocalListener(); - listenerList.add(listener); - listenerList.remove(listener); - - boolean exCaught = false; - try { - listenerList.remove(listener); - fail("invalid listener list: " + listenerList); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testClear() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener1 = new LocalListener(); - Listener listener2 = new LocalListener(); - listenerList.add(listener1); - listenerList.add(listener2); - assertTrue(CollectionTools.contains(listenerList.getListeners(), listener1)); - assertTrue(CollectionTools.contains(listenerList.getListeners(), listener2)); - - listenerList.clear(); - assertFalse(CollectionTools.contains(listenerList.getListeners(), listener1)); - assertFalse(CollectionTools.contains(listenerList.getListeners(), listener2)); - } - - public void testSerialization() throws Exception { - // This test doesn't pass in the Eclipse build environment (Linux/IBM VM) for some reason - if (Tools.jvmIsSun()) { - this.verifySerialization(); - } - } - - private void verifySerialization() throws Exception { - ListenerList<Listener> listenerList = new ListenerList<Listener>(Listener.class); - Listener listener1 = new LocalListener(); - Listener listener2 = new LocalListener(); - listenerList.add(listener1); - listenerList.add(listener2); - - ListenerList<Listener> listenerList2 = TestTools.serialize(listenerList); - assertNotSame(listenerList, listenerList2); - assertEquals(2, listenerList2.size()); - - Listener listener3 = new NonSerializableListener(); - listenerList.add(listener3); - - listenerList2 = TestTools.serialize(listenerList); - assertNotSame(listenerList, listenerList2); - assertEquals(2, listenerList2.size()); - - } - - interface Listener extends EventListener { - void somethingHappened(); - } - - static class LocalListener implements Listener, Serializable { - public void somethingHappened() { - // do nothing - } - } - - static class NonSerializableListener implements Listener { - public void somethingHappened() { - // do nothing - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MethodSignatureTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MethodSignatureTests.java deleted file mode 100644 index 6558e2f45f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MethodSignatureTests.java +++ /dev/null @@ -1,208 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.Method; -import java.util.Arrays; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.JavaType; -import org.eclipse.jpt.common.utility.MethodSignature; -import org.eclipse.jpt.common.utility.internal.SimpleJavaType; -import org.eclipse.jpt.common.utility.internal.SimpleMethodSignature; - -@SuppressWarnings("nls") -public class MethodSignatureTests extends TestCase { - - public MethodSignatureTests(String name) { - super(name); - } - - public void testInvalidNameNull() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature((String) null); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidNameEmpty() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature(""); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterTypesNull() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", (JavaType[]) null); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterTypesNullItem() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", new JavaType[1]); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterTypesVoidItem() throws Exception { - JavaType jt = new SimpleJavaType(void.class.getName()); - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", new JavaType[] {jt}); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterTypeNamesNull() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", (String[]) null); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterTypeNamesNullItem() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", new String[1]); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterJavaClassesNull() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", (Class<?>[]) null); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidParameterJavaClassesNullItem() throws Exception { - boolean exCaught = false; - try { - MethodSignature methodSignature = new SimpleMethodSignature("foo", new Class[1]); - fail("invalid MethodSignature: " + methodSignature); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testGetSignature0() throws Exception { - MethodSignature ms = new SimpleMethodSignature(this.getMethod("method0")); - assertEquals("method0()", ms.getSignature()); - } - - public void testGetSignature1() throws Exception { - MethodSignature ms = new SimpleMethodSignature(this.getMethod("method1")); - assertEquals("method1(int)", ms.getSignature()); - } - - public void testGetSignature2() throws Exception { - MethodSignature ms = new SimpleMethodSignature(this.getMethod("method2")); - assertEquals("method2(int, java.lang.String)", ms.getSignature()); - } - - public void testGetSignature3() throws Exception { - MethodSignature ms = new SimpleMethodSignature(this.getMethod("method3")); - assertEquals("method3(int, java.lang.String, java.lang.Object[][])", ms.getSignature()); - } - - public void testGetName() throws Exception { - MethodSignature ms = new SimpleMethodSignature(this.getMethod("method2")); - assertEquals("method2", ms.getName()); - } - - public void testGetParameterTypes() throws Exception { - MethodSignature ms = new SimpleMethodSignature(this.getMethod("method3")); - JavaType[] expected = new JavaType[3]; - expected[0] = new SimpleJavaType("int"); - expected[1] = new SimpleJavaType("java.lang.String"); - expected[2] = new SimpleJavaType("java.lang.Object", 2); - assertTrue(Arrays.equals(expected, ms.getParameterTypes())); - } - - public void testEquals() throws Exception { - Object ms1 = new SimpleMethodSignature(this.getMethod("method3")); - Object ms2 = new SimpleMethodSignature(this.getMethod("method3")); - assertNotSame(ms1, ms2); - assertEquals(ms1, ms1); - assertEquals(ms1, ms2); - assertEquals(ms1.hashCode(), ms2.hashCode()); - - Object ms3 = new SimpleMethodSignature(this.getMethod("method2")); - assertNotSame(ms1, ms3); - assertFalse(ms1.equals(ms3)); - } - - public void testClone() throws Exception { - SimpleMethodSignature ms1 = new SimpleMethodSignature(this.getMethod("method3")); - SimpleMethodSignature ms2 = (SimpleMethodSignature) ms1.clone(); - assertNotSame(ms1, ms2); - assertEquals(ms1, ms2); - } - - public void testSerialization() throws Exception { - SimpleMethodSignature ms1 = new SimpleMethodSignature(this.getMethod("method3")); - SimpleMethodSignature ms2 = TestTools.serialize(ms1); - assertNotSame(ms1, ms2); - assertEquals(ms1, ms2); - } - - private Method getMethod(String methodName) { - for (Method method : this.getClass().getMethods()) { - if (method.getName().equals(methodName)) { - return method; - } - } - throw new IllegalArgumentException("method not found: " + methodName); - } - - public void method0() { /* used by tests */ } - @SuppressWarnings("unused") public void method1(int foo) { /* used by tests */ } - @SuppressWarnings("unused") public void method2(int foo, String bar) { /* used by tests */ } - @SuppressWarnings("unused") public void method3(int foo, String bar, Object[][] baz) { /* used by tests */ } - - @SuppressWarnings("unused") public void methodA(int foo, String bar) { /* used by tests */ } - @SuppressWarnings("unused") public void methodA(int foo, String bar, String baz) { /* used by tests */ } - - @SuppressWarnings("unused") public void methodB(int foo, Object bar) { /* used by tests */ } - @SuppressWarnings("unused") public void methodB(int foo, String bar) { /* used by tests */ } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MultiThreadedTestCase.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MultiThreadedTestCase.java deleted file mode 100644 index 749253a198..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/MultiThreadedTestCase.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.ArrayList; -import java.util.Vector; -import java.util.concurrent.ThreadFactory; - -import org.eclipse.jpt.common.utility.internal.CompositeException; - -import junit.framework.TestCase; - -/** - * This test case helps simplify the testing of multi-threaded code. - */ -@SuppressWarnings("nls") -public abstract class MultiThreadedTestCase - extends TestCase -{ - private final ArrayList<Thread> threads = new ArrayList<Thread>(); - /* private */ final Vector<Throwable> exceptions = new Vector<Throwable>(); - - /** - * The default "tick" is one second. - * Specify the appropriate system property to override. - */ - public static final String TICK_SYSTEM_PROPERTY_NAME = "org.eclipse.jpt.common.utility.tests.tick"; - public static final long TICK = Long.getLong(TICK_SYSTEM_PROPERTY_NAME, 1000).longValue(); - public static final long TWO_TICKS = 2 * TICK; - public static final long THREE_TICKS = 3 * TICK; - - /** - * Default constructor. - */ - public MultiThreadedTestCase() { - super(); - } - - /** - * Named constructor. - */ - public MultiThreadedTestCase(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - /** - * Stop all the threads constructed during the test case. - * If any exceptions were thrown by the threads, re-throw them here. - */ - @Override - protected void tearDown() throws Exception { - for (Thread thread : this.threads) { - if (thread.isAlive()) { - throw new IllegalStateException("thread is still alive: " + thread); - } - } - if ( ! this.exceptions.isEmpty()) { - throw new CompositeException(this.exceptions); - } - TestTools.clear(this); - super.tearDown(); - } - - protected Thread buildThread(Runnable runnable) { - return this.buildThread(runnable, null); - } - - protected Thread buildThread(Runnable runnable, String name) { - Thread thread = new Thread(new RunnableWrapper(runnable)); - if (name != null) { - thread.setName(name); - } - this.threads.add(thread); - return thread; - } - - protected ThreadFactory buildThreadFactory() { - return new TestThreadFactory(); - } - - /** - * Convenience method that handles {@link InterruptedException}. - */ - public void sleep(long millis) { - TestTools.sleep(millis); - } - - - /** - * Wrap a runnable and log any exception it throws. - */ - public class TestThreadFactory implements ThreadFactory { - public Thread newThread(Runnable r) { - return MultiThreadedTestCase.this.buildThread(r); - } - } - - /** - * Simplify runnables that execute call that throws checked exceptions. - */ - public abstract class TestRunnable implements Runnable { - public final void run() { - try { - this.run_(); - } catch (Throwable ex) { - throw new RuntimeException(ex); - } - } - protected abstract void run_() throws Throwable; - } - - /** - * Wrap a runnable and log any exception it throws. - */ - private class RunnableWrapper implements Runnable { - private final Runnable runnable; - RunnableWrapper(Runnable runnable) { - super(); - this.runnable = runnable; - } - public void run() { - try { - this.runnable.run(); - } catch (RuntimeException ex) { - MultiThreadedTestCase.this.exceptions.add(ex); - } - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NameToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NameToolsTests.java deleted file mode 100644 index d486aab6b7..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NameToolsTests.java +++ /dev/null @@ -1,226 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.NameTools; - -@SuppressWarnings("nls") -public class NameToolsTests extends TestCase { - - public NameToolsTests(String name) { - super(name); - } - - public void testStringAbsentIgnoreCase() { - List<String> colorCollection = this.buildColorCollection(); - String returned = NameTools.uniqueNameForIgnoreCase("Taupe", colorCollection); - assertEquals("Taupe", returned); - } - - public void testStringPresentCaseDiffers() { - List<String> colorCollection = this.buildColorCollection(); - String returned = NameTools.uniqueNameFor("green", colorCollection); - assertEquals("green", returned); - } - - public void testStringPresentIgnoreCase() { - List<String> colorCollection = this.buildColorCollection(); - String returned = NameTools.uniqueNameForIgnoreCase("green", colorCollection); - assertEquals("green2", returned); - } - - public void testStringPresentWithAppendices() { - List<String> colorCollection = this.buildColorCollection(); - colorCollection.add("Red1"); - colorCollection.add("red2"); - String returned = NameTools.uniqueNameForIgnoreCase("red", colorCollection); - colorCollection.remove("Red1"); - colorCollection.remove("red2"); - assertEquals("red3", returned); - } - - private List<String> buildColorCollection() { - List<String> colorCollection = new ArrayList<String>(); - colorCollection.add("Red"); - colorCollection.add("Orange"); - colorCollection.add("Yellow"); - colorCollection.add("Green"); - colorCollection.add("Blue"); - colorCollection.add("Indigo"); - colorCollection.add("Violet"); - return colorCollection; - } - - public void testUniqueNameForCollection1() { - Collection<String> strings = new ArrayList<String>(); - strings.add("Oracle"); - strings.add("Oracle Corporation"); - strings.add("Oracle2"); - strings.add("oracle1"); - strings.add("Oracl"); - - assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings)); - assertEquals("Test", NameTools.uniqueNameFor("Test", strings)); - - assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings)); - assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings)); - assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings)); - } - - public void testUniqueNameForCollection2() { - Collection<String> strings = new ArrayList<String>(); - strings.add("Oracle"); - strings.add("oracle"); - strings.add("Oracle2"); - strings.add("Oracle1"); - - assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings)); - assertEquals("Test", NameTools.uniqueNameFor("Test", strings)); - - strings.add("Oracle Corporation"); - assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings)); - assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings)); - assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings)); - } - - public void testUniqueNameForCollection3() { - Collection<String> strings = new ArrayList<String>(); - strings.add("Oracle"); - strings.add("Oracle"); - strings.add("Oracle2"); - strings.add("Oracle1"); - - assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings)); - } - - public void testUniqueNameForIterator1() { - Collection<String> strings = new ArrayList<String>(); - strings.add("Oracle"); - strings.add("Oracle Corporation"); - strings.add("Oracle2"); - strings.add("oracle1"); - strings.add("Oracl"); - - assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings.iterator())); - assertEquals("Test", NameTools.uniqueNameFor("Test", strings.iterator())); - - assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings.iterator())); - assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings.iterator())); - assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings.iterator())); - } - - public void testUniqueNameForIterator2() { - Collection<String> strings = new ArrayList<String>(); - strings.add("Oracle"); - strings.add("oracle"); - strings.add("Oracle2"); - strings.add("Oracle1"); - - assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings.iterator())); - assertEquals("Test", NameTools.uniqueNameFor("Test", strings.iterator())); - - strings.add("Oracle Corporation"); - assertEquals("Oracle3", NameTools.uniqueNameForIgnoreCase("Oracle", strings.iterator())); - assertEquals("oracle3", NameTools.uniqueNameForIgnoreCase("oracle", strings.iterator())); - assertEquals("Test", NameTools.uniqueNameForIgnoreCase("Test", strings.iterator())); - } - - public void testUniqueNameForIterator3() { - Collection<String> strings = new ArrayList<String>(); - strings.add("Oracle"); - strings.add("Oracle"); - strings.add("Oracle2"); - strings.add("Oracle1"); - - assertEquals("Oracle3", NameTools.uniqueNameFor("Oracle", strings.iterator())); - } - - public void testBuildQualifiedDatabaseObjectName() { - assertEquals("catalog.schema.name", NameTools.buildQualifiedDatabaseObjectName("catalog", "schema", "name")); - assertEquals("catalog..name", NameTools.buildQualifiedDatabaseObjectName("catalog", null, "name")); - assertEquals("schema.name", NameTools.buildQualifiedDatabaseObjectName(null, "schema", "name")); - assertEquals("name", NameTools.buildQualifiedDatabaseObjectName(null, null, "name")); - } - - public void testJavaReservedWords() { - assertTrue(CollectionTools.contains(NameTools.javaReservedWords(), "class")); - assertFalse(CollectionTools.contains(NameTools.javaReservedWords(), "Class")); - assertTrue(CollectionTools.contains(NameTools.javaReservedWords(), "private")); - } - - public void testconvertToJavaIdentifierString() { - assertEquals("foo", NameTools.convertToJavaIdentifier("foo")); - assertEquals("foo1", NameTools.convertToJavaIdentifier("foo1")); - assertEquals("private_", NameTools.convertToJavaIdentifier("private")); - assertEquals("throw_", NameTools.convertToJavaIdentifier("throw")); - assertEquals("_foo", NameTools.convertToJavaIdentifier("1foo")); - assertEquals("foo_", NameTools.convertToJavaIdentifier("foo%")); - assertEquals("foo__bar__", NameTools.convertToJavaIdentifier("foo bar ")); - } - - public void testconvertToJavaIdentifierStringChar() { - assertEquals("foo", NameTools.convertToJavaIdentifier("foo", '$')); - assertEquals("foo1", NameTools.convertToJavaIdentifier("foo1", '$')); - assertEquals("private$", NameTools.convertToJavaIdentifier("private", '$')); - assertEquals("throwss", NameTools.convertToJavaIdentifier("throw", 's')); - assertEquals("$foo", NameTools.convertToJavaIdentifier("1foo", '$')); - assertEquals("foo$", NameTools.convertToJavaIdentifier("foo%", '$')); - assertEquals("foo$$bar$$", NameTools.convertToJavaIdentifier("foo bar ", '$')); - - boolean exCaught = false; - try { - String s = NameTools.convertToJavaIdentifier("1foo", '7'); - fail("invalid string: \"" + s + "\""); - } catch (IllegalArgumentException ex) { - if (ex.getMessage().indexOf('7') != -1) { - exCaught = true; - } - } - assertTrue(exCaught); - - exCaught = false; - try { - String s = NameTools.convertToJavaIdentifier("foo%", '^'); - fail("invalid string: \"" + s + "\""); - } catch (IllegalArgumentException ex) { - if (ex.getMessage().indexOf('^') != -1) { - exCaught = true; - } - } - assertTrue(exCaught); - - exCaught = false; - try { - String s = NameTools.convertToJavaIdentifier("private", '^'); - fail("invalid string: \"" + s + "\""); - } catch (IllegalArgumentException ex) { - if (ex.getMessage().indexOf('^') != -1) { - exCaught = true; - } - } - assertTrue(exCaught); - - } - - public void testStringIsLegalJavaIdentifier() { - assertFalse(NameTools.stringIsLegalJavaIdentifier("class")); - assertTrue(NameTools.stringIsLegalJavaIdentifier("clasS")); - - assertFalse(NameTools.stringIsLegalJavaIdentifier("7foo")); - assertFalse(NameTools.stringIsLegalJavaIdentifier("foo@bar")); - assertTrue(NameTools.stringIsLegalJavaIdentifier("_foo")); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NotNullFilterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NotNullFilterTests.java deleted file mode 100644 index caf06708ae..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/NotNullFilterTests.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.Filter; -import org.eclipse.jpt.common.utility.internal.NotNullFilter; - -@SuppressWarnings("nls") -public class NotNullFilterTests extends TestCase { - - public NotNullFilterTests(String name) { - super(name); - } - - public void testNotNullFilter() { - Filter<String> filter = NotNullFilter.instance(); - assertTrue(filter.accept("")); - assertFalse(filter.accept(null)); - assertTrue(filter.accept("foo")); - assertTrue(filter.accept("bar")); - } - - public void testToString() { - Filter<String> filter = NotNullFilter.instance(); - assertNotNull(filter.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/RangeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/RangeTests.java deleted file mode 100644 index dcd959295a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/RangeTests.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Range; - -public class RangeTests extends TestCase { - - public RangeTests(String name) { - super(name); - } - - public void testIncludes() { - Range range = new Range(5, 17); - assertFalse(range.includes(-55)); - assertFalse(range.includes(0)); - assertFalse(range.includes(4)); - assertTrue(range.includes(5)); - assertTrue(range.includes(6)); - assertTrue(range.includes(16)); - assertTrue(range.includes(17)); - assertFalse(range.includes(18)); - assertFalse(range.includes(200)); - } - - public void testEquals() { - Range range1 = new Range(5, 17); - Range range2 = new Range(5, 17); - assertNotSame(range1, range2); - assertEquals(range1, range1); - assertEquals(range1, range2); - assertEquals(range2, range1); - assertEquals(range1.hashCode(), range2.hashCode()); - - range2 = new Range(17, 5); - assertFalse(range1.equals(range2)); - assertFalse(range2.equals(range1)); - // although they are unequal, they can have the same hash code - assertEquals(range1.hashCode(), range2.hashCode()); - - range2 = new Range(5, 15); - assertFalse(range1.equals(range2)); - assertFalse(range2.equals(range1)); - } - - public void testClone() { - Range range1 = new Range(5, 17); - Range range2 = range1.clone(); - assertNotSame(range1, range2); - assertEquals(range1, range1); - assertEquals(range1, range2); - assertEquals(range2, range1); - assertEquals(range1.hashCode(), range2.hashCode()); - } - - public void testSerialization() throws Exception { - Range range1 = new Range(5, 17); - Range range2 = TestTools.serialize(range1); - assertNotSame(range1, range2); - assertEquals(range1, range1); - assertEquals(range1, range2); - assertEquals(range2, range1); - assertEquals(range1.hashCode(), range2.hashCode()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReflectionToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReflectionToolsTests.java deleted file mode 100644 index d210cb0f5f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReflectionToolsTests.java +++ /dev/null @@ -1,440 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Vector; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.iterables.TransformationIterable; - -@SuppressWarnings("nls") -public class ReflectionToolsTests extends TestCase { - - private static String testStaticField; - - public ReflectionToolsTests(String name) { - super(name); - } - -// this is no longer true - it appears the JLS now defines the generated names... -// /** -// * Return the compiler-generated class name. The Eclipse compiler generates -// * "local" classes with names in the form "com.foo.Outer$1$Local"; while the -// * JDK compiler generates "com.foo.Outer$1Local". There might be other -// * differences.... ~bjv -// */ -// public static String compilerDependentClassNameFor(String className) { -// int index = className.indexOf("$1$"); -// if (index == -1) { -// return className; -// } -// try { -// Class.forName(className); -// } catch (ClassNotFoundException ex) { -// return className.substring(0, index + 2) + className.substring(index + 3); -// } -// return className; -// } -// -// private static String munge(String className) { -// return compilerDependentClassNameFor(className); -// } - - public void testAllFields() { - int fieldCount = 0; - fieldCount += java.util.Vector.class.getDeclaredFields().length; - fieldCount += java.util.AbstractList.class.getDeclaredFields().length; - fieldCount += java.util.AbstractCollection.class.getDeclaredFields().length; - fieldCount += java.lang.Object.class.getDeclaredFields().length; - Iterable<Field> fields = ReflectionTools.getAllFields(java.util.Vector.class); - assertEquals(fieldCount, CollectionTools.size(fields)); - assertTrue(CollectionTools.contains(this.fieldNames(fields), "modCount")); - assertTrue(CollectionTools.contains(this.fieldNames(fields), "serialVersionUID")); - assertTrue(CollectionTools.contains(this.fieldNames(fields), "capacityIncrement")); - assertTrue(CollectionTools.contains(this.fieldNames(fields), "elementCount")); - assertTrue(CollectionTools.contains(this.fieldNames(fields), "elementData")); - assertTrue(fields.iterator().next().isAccessible()); - } - - public void testAllMethods() { - int methodCount = 0; - methodCount += java.util.Vector.class.getDeclaredMethods().length; - methodCount += java.util.AbstractList.class.getDeclaredMethods().length; - methodCount += java.util.AbstractCollection.class.getDeclaredMethods().length; - methodCount += java.lang.Object.class.getDeclaredMethods().length; - Iterable<Method> methods = ReflectionTools.getAllMethods(java.util.Vector.class); - assertEquals(methodCount, CollectionTools.size(methods)); - assertTrue(CollectionTools.contains(this.methodNames(methods), "wait")); - assertTrue(CollectionTools.contains(this.methodNames(methods), "addElement")); - assertTrue(methods.iterator().next().isAccessible()); - } - - public void testNewInstanceClass() { - Vector<?> v = ReflectionTools.newInstance(java.util.Vector.class); - assertNotNull(v); - assertEquals(0, v.size()); - } - - public void testNewInstanceClassClassObject() { - int initialCapacity = 200; - Vector<?> v = ReflectionTools.newInstance(java.util.Vector.class, int.class, new Integer(initialCapacity)); - assertNotNull(v); - assertEquals(0, v.size()); - Object[] elementData = (Object[]) ReflectionTools.getFieldValue(v, "elementData"); - assertEquals(initialCapacity, elementData.length); - } - - public void testNewInstanceClassClassArrayObjectArray() { - int initialCapacity = 200; - Class<?>[] parmTypes = new Class[1]; - parmTypes[0] = int.class; - Object[] parms = new Object[1]; - parms[0] = new Integer(initialCapacity); - Vector<?> v = ReflectionTools.newInstance(java.util.Vector.class, parmTypes, parms); - assertNotNull(v); - assertEquals(0, v.size()); - Object[] elementData = (Object[]) ReflectionTools.getFieldValue(v, "elementData"); - assertEquals(initialCapacity, elementData.length); - - parms[0] = new Integer(-1); - boolean exCaught = false; - try { - v = ReflectionTools.newInstance(java.util.Vector.class, parmTypes, parms); - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue("RuntimeException not thrown", exCaught); - - parmTypes[0] = java.lang.String.class; - parms[0] = "foo"; - exCaught = false; - try { - v = ReflectionTools.newInstance(java.util.Vector.class, parmTypes, parms); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchMethodException) { - exCaught = true; - } - } - assertTrue("NoSuchMethodException not thrown", exCaught); - } - - public void testFieldValue() { - int initialCapacity = 200; - Vector<?> v = new Vector<Object>(initialCapacity); - Object[] elementData = (Object[]) ReflectionTools.getFieldValue(v, "elementData"); - assertEquals(initialCapacity, elementData.length); - - // test inherited field - Integer modCountInteger = (Integer) ReflectionTools.getFieldValue(v, "modCount"); - int modCount = modCountInteger.intValue(); - assertEquals(0, modCount); - - boolean exCaught = false; - Object bogusFieldValue = null; - try { - bogusFieldValue = ReflectionTools.getFieldValue(v, "bogusField"); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchFieldException) { - exCaught = true; - } - } - assertTrue("NoSuchFieldException not thrown: " + bogusFieldValue, exCaught); - } - - public void testExecuteMethodObjectString() { - Vector<String> v = new Vector<String>(); - int size = ((Integer) ReflectionTools.executeMethod(v, "size")).intValue(); - assertEquals(0, size); - - v.addElement("foo"); - size = ((Integer) ReflectionTools.executeMethod(v, "size")).intValue(); - assertEquals(1, size); - } - - public void testExecuteMethodObjectStringClassObject() { - Vector<String> v = new Vector<String>(); - boolean booleanResult = ((Boolean) ReflectionTools.executeMethod(v, "add", Object.class, "foo")).booleanValue(); - assertTrue(booleanResult); - assertTrue(v.contains("foo")); - Object voidResult = ReflectionTools.executeMethod(v, "addElement", Object.class, "bar"); - assertNull(voidResult); - } - - public void testExecuteMethodObjectStringClassArrayObjectArray() { - Vector<String> v = new Vector<String>(); - Class<?>[] parmTypes = new Class[1]; - parmTypes[0] = java.lang.Object.class; - Object[] parms = new Object[1]; - parms[0] = "foo"; - boolean booleanResult = ((Boolean) ReflectionTools.executeMethod(v, "add", parmTypes, parms)).booleanValue(); - assertTrue(booleanResult); - assertTrue(v.contains("foo")); - - boolean exCaught = false; - Object bogusMethodReturnValue = null; - try { - bogusMethodReturnValue = ReflectionTools.executeMethod(v, "bogusMethod", parmTypes, parms); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchMethodException) { - exCaught = true; - } - } - assertTrue("NoSuchMethodException not thrown: " + bogusMethodReturnValue, exCaught); - } - - public void testExecuteStaticMethodClassString() { - Double randomObject = (Double) ReflectionTools.executeStaticMethod(java.lang.Math.class, "random"); - assertNotNull(randomObject); - double random = randomObject.doubleValue(); - assertTrue(random >= 0); - assertTrue(random < 1); - } - - public void testExecuteStaticMethodClassStringClassObject() { - String s = (String) ReflectionTools.executeStaticMethod(java.lang.String.class, "valueOf", boolean.class, Boolean.TRUE); - assertNotNull(s); - assertEquals("true", s); - } - - public void testExecuteStaticMethodClassStringClassArrayObjectArray() { - Class<?>[] parmTypes = new Class[1]; - parmTypes[0] = boolean.class; - Object[] parms = new Object[1]; - parms[0] = Boolean.TRUE; - String s = (String) ReflectionTools.executeStaticMethod(java.lang.String.class, "valueOf", parmTypes, parms); - assertNotNull(s); - assertEquals("true", s); - - boolean exCaught = false; - Object bogusStaticMethodReturnValue = null; - try { - bogusStaticMethodReturnValue = ReflectionTools.executeStaticMethod(java.lang.String.class, "bogusStaticMethod", parmTypes, parms); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchMethodException) { - exCaught = true; - } - } - assertTrue("NoSuchMethodException not thrown: " + bogusStaticMethodReturnValue, exCaught); - - // test non-static method - exCaught = false; - try { - bogusStaticMethodReturnValue = ReflectionTools.executeStaticMethod(java.lang.String.class, "toString"); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchMethodException) { - exCaught = true; - } - } - assertTrue("NoSuchMethodException not thrown: " + bogusStaticMethodReturnValue, exCaught); - } - - public void testSetFieldValue() { - Vector<String> v = new Vector<String>(); - Object[] newElementData = new Object[5]; - newElementData[0] = "foo"; - ReflectionTools.setFieldValue(v, "elementData", newElementData); - ReflectionTools.setFieldValue(v, "elementCount", new Integer(1)); - // test inherited field - ReflectionTools.setFieldValue(v, "modCount", new Integer(1)); - assertTrue(v.contains("foo")); - - boolean exCaught = false; - try { - ReflectionTools.setFieldValue(v, "bogusField", "foo"); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchFieldException) { - exCaught = true; - } - } - assertTrue("NoSuchFieldException not thrown", exCaught); - } - - public void testSetStaticFieldValue() { - ReflectionTools.setStaticFieldValue(this.getClass(), "testStaticField", "new value"); - assertEquals(testStaticField, "new value"); - - boolean exCaught = false; - try { - ReflectionTools.setStaticFieldValue(this.getClass(), "bogusStaticField", "new value"); - } catch (RuntimeException ex) { - if (ex.getCause() instanceof NoSuchFieldException) { - exCaught = true; - } - } - assertTrue("NoSuchFieldException not thrown", exCaught); - } - - public void testSimpleName() { - assertEquals("Vector", java.util.Vector.class.getSimpleName()); - assertEquals("Entry", java.util.Map.Entry.class.getSimpleName()); - assertEquals("int", int.class.getSimpleName()); - assertEquals("int[]", int[].class.getSimpleName()); - assertEquals("int[][]", int[][].class.getSimpleName()); - assertEquals("void", void.class.getSimpleName()); - } - - public void testPackageName() { - assertEquals("java.util", java.util.Vector.class.getPackage().getName()); - assertEquals("java.util", java.util.Map.Entry.class.getPackage().getName()); - } - - public void testArrayDepthFor() { - assertEquals(0, ReflectionTools.getArrayDepth(java.util.Vector.class)); - assertEquals(0, ReflectionTools.getArrayDepth(int.class)); - assertEquals(0, ReflectionTools.getArrayDepth(void.class)); - assertEquals(1, ReflectionTools.getArrayDepth(java.util.Vector[].class)); - assertEquals(1, ReflectionTools.getArrayDepth(int[].class)); - assertEquals(3, ReflectionTools.getArrayDepth(java.util.Vector[][][].class)); - assertEquals(3, ReflectionTools.getArrayDepth(int[][][].class)); - } - - public void testElementTypeFor() { - assertEquals(java.util.Vector.class, ReflectionTools.getElementType(java.util.Vector.class)); - assertEquals(int.class, ReflectionTools.getElementType(int.class)); - assertEquals(void.class, ReflectionTools.getElementType(void.class)); - assertEquals(java.util.Vector.class, ReflectionTools.getElementType(java.util.Vector[].class)); - assertEquals(int.class, ReflectionTools.getElementType(int[].class)); - assertEquals(java.util.Vector.class, ReflectionTools.getElementType(java.util.Vector[][][].class)); - assertEquals(int.class, ReflectionTools.getElementType(int[][][].class)); - } - - public void testClassIsPrimitiveWrapperClass() { - assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Void.class)); - assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Boolean.class)); - assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Integer.class)); - assertTrue(ReflectionTools.classIsPrimitiveWrapper(java.lang.Float.class)); - - assertFalse(ReflectionTools.classIsPrimitiveWrapper(java.lang.String.class)); - assertFalse(ReflectionTools.classIsPrimitiveWrapper(void.class)); - assertFalse(ReflectionTools.classIsPrimitiveWrapper(int.class)); - } - - public void testClassIsVariablePrimitiveWrapperClass() { - assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Void.class)); - - assertTrue(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Boolean.class)); - assertTrue(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Integer.class)); - assertTrue(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.Float.class)); - - assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(java.lang.String.class)); - assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(void.class)); - assertFalse(ReflectionTools.classIsVariablePrimitiveWrapper(int.class)); - } - - public void testWrapperClass() { - assertEquals(java.lang.Void.class, ReflectionTools.getWrapperClass(void.class)); - assertEquals(java.lang.Integer.class, ReflectionTools.getWrapperClass(int.class)); - assertEquals(java.lang.Float.class, ReflectionTools.getWrapperClass(float.class)); - assertEquals(java.lang.Boolean.class, ReflectionTools.getWrapperClass(boolean.class)); - - assertNull(ReflectionTools.getWrapperClass(java.lang.String.class)); - } - - public void testClassForTypeDeclarationStringInt() throws Exception { - assertEquals(int.class, ReflectionTools.getClassForTypeDeclaration("int", 0)); - assertEquals(int[].class, ReflectionTools.getClassForTypeDeclaration("int", 1)); - assertEquals(int[][][].class, ReflectionTools.getClassForTypeDeclaration("int", 3)); - - assertEquals(Object.class, ReflectionTools.getClassForTypeDeclaration("java.lang.Object", 0)); - assertEquals(Object[][][].class, ReflectionTools.getClassForTypeDeclaration("java.lang.Object", 3)); - - assertEquals(void.class, ReflectionTools.getClassForTypeDeclaration("void", 0)); - try { - ReflectionTools.getClassForTypeDeclaration(void.class.getName(), 1); - fail("should not get here..."); - } catch (RuntimeException ex) { - // expected - } - } - - public void testCodeForClass() { - assertEquals('I', ReflectionTools.getCodeForClass(int.class)); - assertEquals('B', ReflectionTools.getCodeForClass(byte.class)); - } - - public void testClassNameForTypeDeclarationString() throws Exception { - assertEquals("int", ReflectionTools.getClassNameForTypeDeclaration("int")); - assertEquals("[I", ReflectionTools.getClassNameForTypeDeclaration("int[]")); - assertEquals("[[I", ReflectionTools.getClassNameForTypeDeclaration("int [ ] [ ]")); - - assertEquals("java.lang.Object", ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object")); - assertEquals("[Ljava.lang.Object;", ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object\t[]")); - assertEquals("[[Ljava.lang.Object;", ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object\t[]\t[]")); - } - - public void testArrayDepthForTypeDeclarationString() throws Exception { - assertEquals(0, ReflectionTools.getArrayDepthForTypeDeclaration("java.lang.Object")); - assertEquals(1, ReflectionTools.getArrayDepthForTypeDeclaration("java.lang.Object[]")); - assertEquals(3, ReflectionTools.getArrayDepthForTypeDeclaration("java.lang.Object[][][]")); - - assertEquals(0, ReflectionTools.getArrayDepthForTypeDeclaration("int")); - assertEquals(1, ReflectionTools.getArrayDepthForTypeDeclaration("int[]")); - assertEquals(3, ReflectionTools.getArrayDepthForTypeDeclaration("int[][][]")); - - assertEquals(0, ReflectionTools.getArrayDepthForTypeDeclaration("float")); - assertEquals(1, ReflectionTools.getArrayDepthForTypeDeclaration("float [ ]")); - assertEquals(3, ReflectionTools.getArrayDepthForTypeDeclaration("float[] [] []")); - } - - public void testElementTypeNameForTypeDeclarationString() throws Exception { - assertEquals("java.lang.Object", ReflectionTools.getElementTypeNameForTypeDeclaration("java.lang.Object")); - assertEquals("java.lang.Object", ReflectionTools.getElementTypeNameForTypeDeclaration("java.lang.Object[]")); - assertEquals("java.lang.Object", ReflectionTools.getElementTypeNameForTypeDeclaration("java.lang.Object[][][]")); - - assertEquals("int", ReflectionTools.getElementTypeNameForTypeDeclaration("int")); - assertEquals("int", ReflectionTools.getElementTypeNameForTypeDeclaration("int[]")); - assertEquals("int", ReflectionTools.getElementTypeNameForTypeDeclaration("int[][][]")); - - assertEquals("float", ReflectionTools.getElementTypeNameForTypeDeclaration("float")); - assertEquals("float", ReflectionTools.getElementTypeNameForTypeDeclaration("float [ ]")); - assertEquals("float", ReflectionTools.getElementTypeNameForTypeDeclaration("float[] [] []")); - } - - public void testClassNameForTypeDeclarationStringInt() throws Exception { - assertEquals(int.class.getName(), ReflectionTools.getClassNameForTypeDeclaration("int", 0)); - assertEquals(int[].class.getName(), ReflectionTools.getClassNameForTypeDeclaration("int", 1)); - assertEquals(int[][][].class.getName(), ReflectionTools.getClassNameForTypeDeclaration("int", 3)); - - assertEquals(Object.class.getName(), ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object", 0)); - assertEquals(Object[][][].class.getName(), ReflectionTools.getClassNameForTypeDeclaration("java.lang.Object", 3)); - - assertEquals(void.class.getName(), ReflectionTools.getClassNameForTypeDeclaration("void", 0)); - try { - ReflectionTools.getClassNameForTypeDeclaration(void.class.getName(), 1); - fail("should not get here..."); - } catch (IllegalArgumentException ex) { - // expected - } - } - - private Iterable<String> fieldNames(Iterable<Field> fields) { - return new TransformationIterable<Field, String>(fields) { - @Override - protected String transform(Field field) { - return field.getName(); - } - }; - } - - private Iterable<String> methodNames(Iterable<Method> methods) { - return new TransformationIterable<Method, String>(methods) { - @Override - protected String transform(Method method) { - return method.getName(); - } - }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReverseComparatorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReverseComparatorTests.java deleted file mode 100644 index 1287868a13..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ReverseComparatorTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReverseComparator; - -@SuppressWarnings("nls") -public class ReverseComparatorTests extends TestCase { - private Comparator<String> naturalReverseComparator; - private Comparator<String> customComparator; - private Comparator<String> customReverseComparator; - - public ReverseComparatorTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.naturalReverseComparator = new ReverseComparator<String>(); - this.customComparator = this.buildCustomComparator(); - this.customReverseComparator = new ReverseComparator<String>(this.customComparator); - } - - private Comparator<String> buildCustomComparator() { - return new Comparator<String>() { - public int compare(String s1, String s2) { - String lower1 = s1.toLowerCase(); - String lower2 = s2.toLowerCase(); - int result = lower1.compareTo(lower2); - if (result == 0) { - return s1.compareTo(s2); // use case to differentiate "equal" strings - } - return result; - } - }; - } - - private List<String> buildUnsortedList() { - List<String> result = new ArrayList<String>(); - result.add("T"); - result.add("Z"); - result.add("Y"); - result.add("M"); - result.add("m"); - result.add("a"); - result.add("B"); - result.add("b"); - result.add("A"); - return result; - } - - private List<String> buildNaturallySortedList() { - List<String> result = new ArrayList<String>(this.buildUnsortedList()); - Collections.sort(result); - return result; - } - - private List<String> buildCustomSortedList() { - List<String> result = new ArrayList<String>(this.buildUnsortedList()); - Collections.sort(result, this.customComparator); - return result; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testNatural() { - List<String> list = this.buildUnsortedList(); - Collections.sort(list, this.naturalReverseComparator); - this.verifyList(this.buildNaturallySortedList(), list); - } - - public void testCustom() { - List<String> list = this.buildUnsortedList(); - Collections.sort(list, this.customReverseComparator); - this.verifyList(this.buildCustomSortedList(), list); - } - - private void verifyList(List<String> normal, List<String> reverse) { - int size = normal.size(); - int max = size - 1; - for (int i = 0; i < size; i++) { - assertEquals(normal.get(i), reverse.get(max - i)); - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleAssociationTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleAssociationTests.java deleted file mode 100644 index 96fe163217..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleAssociationTests.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; -import org.eclipse.jpt.common.utility.internal.Association; -import org.eclipse.jpt.common.utility.internal.SimpleAssociation; - -@SuppressWarnings("nls") -public class SimpleAssociationTests extends TestCase { - private SimpleAssociation<String, String> assoc; - - public static Test suite() { - return new TestSuite(SimpleAssociationTests.class); - } - - public SimpleAssociationTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.assoc = new SimpleAssociation<String, String>("foo", "bar"); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetKey() { - assertEquals("foo", this.assoc.getKey()); - } - - public void testGetValue() { - assertEquals("bar", this.assoc.getValue()); - } - - public void testSetValue() { - assertEquals("bar", this.assoc.getValue()); - this.assoc.setValue("baz"); - assertEquals("baz", this.assoc.getValue()); - } - - public void testEquals() { - assertFalse(this.assoc.equals("foo")); - - assertEquals(this.assoc, this.copy(this.assoc)); - - SimpleAssociation<String, String> assoc2 = new SimpleAssociation<String, String>("foo", "baz"); - assertFalse(this.assoc.equals(assoc2)); - - assoc2 = new SimpleAssociation<String, String>("fop", "bar"); - assertFalse(this.assoc.equals(assoc2)); - - SimpleAssociation<String, String> assoc3 = new SimpleAssociation<String, String>(null, null); - SimpleAssociation<String, String> assoc4 = new SimpleAssociation<String, String>(null, null); - assertEquals(assoc3, assoc4); - } - - public void testHashCode() { - assertEquals(this.assoc.hashCode(), this.copy(this.assoc).hashCode()); - - SimpleAssociation<String, String> assoc2 = new SimpleAssociation<String, String>(null, null); - assertEquals(assoc2.hashCode(), this.copy(assoc2).hashCode()); - } - - public void testToString() { - assertNotNull(this.assoc.toString()); - } - - public void testClone() { - this.verifyClone(this.assoc, this.assoc.clone()); - } - - private void verifyClone(Association<String, String> expected, Association<String, String> actual) { - assertEquals(expected, actual); - assertNotSame(expected, actual); - assertEquals(expected.getKey(), actual.getKey()); - assertSame(expected.getKey(), actual.getKey()); - assertEquals(expected.getValue(), actual.getValue()); - assertSame(expected.getValue(), actual.getValue()); - } - - public void testSerialization() throws Exception { - @SuppressWarnings("cast") - Association<String, String> assoc2 = (Association<String, String>) TestTools.serialize(this.assoc); - - assertEquals(this.assoc, assoc2); - assertNotSame(this.assoc, assoc2); - assertEquals(this.assoc.getKey(), assoc2.getKey()); - assertNotSame(this.assoc.getKey(), assoc2.getKey()); - assertEquals(this.assoc.getValue(), assoc2.getValue()); - assertNotSame(this.assoc.getValue(), assoc2.getValue()); - } - - private SimpleAssociation<String, String> copy(SimpleAssociation<String, String> sa) { - return new SimpleAssociation<String, String>(sa.getKey(), sa.getValue()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleBooleanReferenceTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleBooleanReferenceTests.java deleted file mode 100644 index 04c06ddde3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleBooleanReferenceTests.java +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.SimpleBooleanReference; - -@SuppressWarnings("nls") -public class SimpleBooleanReferenceTests extends TestCase { - - public SimpleBooleanReferenceTests(String name) { - super(name); - } - - public void testGetValue() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertTrue(br.getValue()); - } - - public void testGetValueDefault() { - SimpleBooleanReference br = new SimpleBooleanReference(); - assertFalse(br.getValue()); - } - - public void testIs() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertTrue(br.is(true)); - assertFalse(br.is(false)); - } - - public void testIsNot() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertFalse(br.isNot(true)); - assertTrue(br.isNot(false)); - } - - public void testIsTrue() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertTrue(br.isTrue()); - } - - public void testIsFalse() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertFalse(br.isFalse()); - br.setFalse(); - assertTrue(br.isFalse()); - } - - public void testSetValue() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertTrue(br.getValue()); - br.setValue(false); - assertFalse(br.getValue()); - } - - public void testFlip() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertTrue(br.getValue()); - assertFalse(br.flip()); - assertFalse(br.getValue()); - assertTrue(br.flip()); - assertTrue(br.getValue()); - } - - public void testSetNotBoolean() { - SimpleBooleanReference br = new SimpleBooleanReference(false); - assertFalse(br.getValue()); - br.setNot(true); - assertFalse(br.getValue()); - br.setNot(true); - assertFalse(br.getValue()); - br.setNot(false); - assertTrue(br.getValue()); - } - - public void testSetTrue() { - SimpleBooleanReference br = new SimpleBooleanReference(false); - assertFalse(br.getValue()); - br.setTrue(); - assertTrue(br.getValue()); - } - - public void testSetFalse() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - assertTrue(br.getValue()); - br.setFalse(); - assertFalse(br.getValue()); - } - - public void testClone() { - SimpleBooleanReference br = new SimpleBooleanReference(true); - SimpleBooleanReference clone = br.clone(); - assertTrue(clone.getValue()); - } - - public void testToString() { - SimpleBooleanReference br1 = new SimpleBooleanReference(true); - assertEquals("[true]", br1.toString()); - br1.setFalse(); - assertEquals("[false]", br1.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleIntReferenceTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleIntReferenceTests.java deleted file mode 100644 index 196570b6de..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleIntReferenceTests.java +++ /dev/null @@ -1,314 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.SimpleIntReference; - -@SuppressWarnings("nls") -public class SimpleIntReferenceTests extends TestCase { - - public SimpleIntReferenceTests(String name) { - super(name); - } - - public void testCtors() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertEquals(0, ir.getValue()); - ir = new SimpleIntReference(7); - assertEquals(7, ir.getValue()); - ir = new SimpleIntReference(-7); - assertEquals(-7, ir.getValue()); - } - - public void testEqualsInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertTrue(ir.equals(0)); - assertFalse(ir.equals(7)); - - ir = new SimpleIntReference(7); - assertTrue(ir.equals(7)); - assertFalse(ir.equals(0)); - } - - public void testNotEqualInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertFalse(ir.notEqual(0)); - assertTrue(ir.notEqual(7)); - - ir = new SimpleIntReference(7); - assertFalse(ir.notEqual(7)); - assertTrue(ir.notEqual(0)); - } - - public void testIsZero() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertTrue(ir.isZero()); - - ir = new SimpleIntReference(7); - assertFalse(ir.isZero()); - } - - public void testIsNotZero() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertFalse(ir.isNotZero()); - - ir = new SimpleIntReference(7); - assertTrue(ir.isNotZero()); - } - - public void testIsGreaterThanInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertTrue(ir.isGreaterThan(-1)); - assertFalse(ir.isGreaterThan(0)); - assertFalse(ir.isGreaterThan(7)); - } - - public void testIsGreaterThanOrEqualInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertTrue(ir.isGreaterThanOrEqual(-1)); - assertTrue(ir.isGreaterThanOrEqual(0)); - assertFalse(ir.isGreaterThanOrEqual(7)); - } - - public void testIsLessThanInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertFalse(ir.isLessThan(-1)); - assertFalse(ir.isLessThan(0)); - assertTrue(ir.isLessThan(7)); - } - - public void testIsLessThanOrEqualInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(); - assertFalse(ir.isLessThanOrEqual(-1)); - assertTrue(ir.isLessThanOrEqual(0)); - assertTrue(ir.isLessThanOrEqual(7)); - } - - public void testIsPositive() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertFalse(ir.isPositive()); - - ir = new SimpleIntReference(); - assertFalse(ir.isPositive()); - - ir = new SimpleIntReference(7); - assertTrue(ir.isPositive()); - } - - public void testIsNotPositive() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertTrue(ir.isNotPositive()); - - ir = new SimpleIntReference(); - assertTrue(ir.isNotPositive()); - - ir = new SimpleIntReference(7); - assertFalse(ir.isNotPositive()); - } - - public void testIsNegative() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertTrue(ir.isNegative()); - - ir = new SimpleIntReference(); - assertFalse(ir.isNegative()); - - ir = new SimpleIntReference(7); - assertFalse(ir.isNegative()); - } - - public void testIsNotNegative() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertFalse(ir.isNotNegative()); - - ir = new SimpleIntReference(); - assertTrue(ir.isNotNegative()); - - ir = new SimpleIntReference(7); - assertTrue(ir.isNotNegative()); - } - - public void testSetValueInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertEquals(-3, ir.getValue()); - assertEquals(-3, ir.setValue(4)); - assertEquals(4, ir.getValue()); - } - - public void testAbs() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertEquals(-3, ir.getValue()); - assertEquals(3, ir.abs()); - - ir.setValue(3); - assertEquals(3, ir.getValue()); - assertEquals(3, ir.abs()); - } - - public void testNeg() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertEquals(-3, ir.getValue()); - assertEquals(3, ir.neg()); - - ir.setValue(3); - assertEquals(3, ir.getValue()); - assertEquals(-3, ir.neg()); - } - - public void testSetZero() { - SimpleIntReference ir; - ir = new SimpleIntReference(-3); - assertEquals(-3, ir.getValue()); - assertEquals(-3, ir.setZero()); - assertEquals(0, ir.getValue()); - } - - public void testAddInt() { - SimpleIntReference ir; - int value; - ir = new SimpleIntReference(); - assertEquals(0, ir.getValue()); - - value = ir.add(3); - assertEquals(3, value); - - ir.setValue(3); - value = ir.add(-7); - assertEquals(-4, value); - } - - public void testIncrement() { - SimpleIntReference ir; - int value; - ir = new SimpleIntReference(); - assertEquals(0, ir.getValue()); - - value = ir.increment(); - assertEquals(1, value); - assertEquals(1, ir.getValue()); - } - - public void testSubtractInt() { - SimpleIntReference ir; - int count; - ir = new SimpleIntReference(); - assertEquals(0, ir.getValue()); - - count = ir.subtract(3); - assertEquals(-3, count); - - ir.setValue(-3); - count = ir.subtract(-7); - assertEquals(4, count); - } - - public void testDecrement() { - SimpleIntReference ir; - int count; - ir = new SimpleIntReference(); - assertEquals(0, ir.getValue()); - - count = ir.decrement(); - assertEquals(-1, count); - assertEquals(-1, ir.getValue()); - } - - public void testMultiplyInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(3); - assertEquals(3, ir.getValue()); - assertEquals(9, ir.multiply(3)); - } - - public void testDivideInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(24); - assertEquals(24, ir.getValue()); - assertEquals(8, ir.divide(3)); - } - - public void testRemainderInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(25); - assertEquals(25, ir.getValue()); - assertEquals(1, ir.remainder(3)); - } - - public void testMinInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(25); - assertEquals(25, ir.getValue()); - assertEquals(3, ir.min(3)); - assertEquals(25, ir.min(33)); - } - - public void testMaxInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(25); - assertEquals(25, ir.getValue()); - assertEquals(25, ir.max(3)); - assertEquals(30, ir.max(30)); - } - - public void testPowInt() { - SimpleIntReference ir; - ir = new SimpleIntReference(5); - assertEquals(5, ir.getValue()); - assertTrue(ir.pow(2) == 25L); - } - - public void testCompareToIntReference() { - SimpleIntReference ir1 = new SimpleIntReference(44); - SimpleIntReference ir2 = new SimpleIntReference(44); - assertTrue(ir1.compareTo(ir2) == 0); - ir2 = new SimpleIntReference(55); - assertTrue(ir1.compareTo(ir2) < 0); - ir2 = new SimpleIntReference(33); - assertTrue(ir1.compareTo(ir2) > 0); - } - - public void testClone() { - SimpleIntReference ir1 = new SimpleIntReference(44); - SimpleIntReference ir2 = ir1.clone(); - assertEquals(44, ir2.getValue()); - assertNotSame(ir1, ir2); - } - - public void testSerialization() throws Exception { - SimpleIntReference ir1 = new SimpleIntReference(44); - SimpleIntReference ir2 = TestTools.serialize(ir1); - assertEquals(44, ir2.getValue()); - assertNotSame(ir1, ir2); - } - - public void testToString() { - SimpleIntReference ir; - ir = new SimpleIntReference(5); - assertEquals("[5]", ir.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleObjectReferenceTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleObjectReferenceTests.java deleted file mode 100644 index ea91ac9f7c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleObjectReferenceTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.SimpleObjectReference; - -@SuppressWarnings("nls") -public class SimpleObjectReferenceTests extends TestCase { - - public SimpleObjectReferenceTests(String name) { - super(name); - } - - public void testGetValue() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertNull(or.getValue()); - or.setValue("foo"); - assertEquals("foo", or.getValue()); - } - - public void testValueEqualsObject() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertTrue(or.valueEquals(null)); - assertFalse(or.valueEquals("foo")); - - or.setValue("foo"); - assertFalse(or.valueEquals(null)); - assertTrue(or.valueEquals("foo")); - } - - public void testValueNotEqualObject() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertFalse(or.valueNotEqual(null)); - assertTrue(or.valueNotEqual("foo")); - - or.setValue("foo"); - assertTrue(or.valueNotEqual(null)); - assertFalse(or.valueNotEqual("foo")); - } - - public void testIsNull() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertTrue(or.isNull()); - or.setValue("foo"); - assertFalse(or.isNull()); - } - - public void testIsNotNull() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertFalse(or.isNotNull()); - or.setValue("foo"); - assertTrue(or.isNotNull()); - } - - public void testSetNull() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertNull(or.getValue()); - or.setValue("foo"); - assertEquals("foo", or.getValue()); - or.setNull(); - assertNull(or.getValue()); - } - - public void testClone() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>("foo"); - @SuppressWarnings("cast") - SimpleObjectReference<String> clone = (SimpleObjectReference<String>) or.clone(); - assertEquals("foo", clone.getValue()); - assertNotSame(or, clone); - } - - public void testToString() { - SimpleObjectReference<String> or = new SimpleObjectReference<String>(); - assertEquals("[null]", or.toString()); - or.setValue("foo"); - assertEquals("[foo]", or.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleQueueTests.java deleted file mode 100644 index 4fb99dbc5a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleQueueTests.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.Queue; -import org.eclipse.jpt.common.utility.internal.SimpleQueue; - -@SuppressWarnings("nls") -public class SimpleQueueTests - extends MultiThreadedTestCase -{ - - public SimpleQueueTests(String name) { - super(name); - } - - Queue<String> buildQueue() { - return new SimpleQueue<String>(); - } - - public void testIsEmpty() { - Queue<String> queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.dequeue(); - assertFalse(queue.isEmpty()); - queue.dequeue(); - assertTrue(queue.isEmpty()); - } - - public void testEnqueueAndDequeue() { - Queue<String> queue = this.buildQueue(); - String first = "first"; - String second = "second"; - - queue.enqueue(first); - queue.enqueue(second); - assertEquals(first, queue.dequeue()); - assertEquals(second, queue.dequeue()); - } - - public void testEnqueueAndPeek() { - Queue<String> queue = this.buildQueue(); - String first = "first"; - String second = "second"; - - queue.enqueue(first); - queue.enqueue(second); - assertEquals(first, queue.peek()); - assertEquals(first, queue.peek()); - assertEquals(first, queue.dequeue()); - assertEquals(second, queue.peek()); - assertEquals(second, queue.peek()); - assertEquals(second, queue.dequeue()); - } - - public void testEmptyQueueExceptionPeek() { - Queue<String> queue = this.buildQueue(); - String first = "first"; - String second = "second"; - - queue.enqueue(first); - queue.enqueue(second); - assertEquals(first, queue.peek()); - assertEquals(first, queue.dequeue()); - assertEquals(second, queue.peek()); - assertEquals(second, queue.dequeue()); - - boolean exCaught = false; - try { - queue.peek(); - fail(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testEmptyQueueExceptionDequeue() { - Queue<String> queue = this.buildQueue(); - String first = "first"; - String second = "second"; - - queue.enqueue(first); - queue.enqueue(second); - assertEquals(first, queue.peek()); - assertEquals(first, queue.dequeue()); - assertEquals(second, queue.peek()); - assertEquals(second, queue.dequeue()); - - boolean exCaught = false; - try { - queue.dequeue(); - fail(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testClone() { - SimpleQueue<String> queue = (SimpleQueue<String>) this.buildQueue(); - queue.enqueue("first"); - queue.enqueue("second"); - queue.enqueue("third"); - - this.verifyClone(queue, queue.clone()); - } - - public void testSerialization() throws Exception { - Queue<String> queue = this.buildQueue(); - queue.enqueue("first"); - queue.enqueue("second"); - queue.enqueue("third"); - - this.verifyClone(queue, TestTools.serialize(queue)); - } - - private void verifyClone(Queue<String> original, Queue<String> clone) { - assertNotSame(original, clone); - assertEquals(original.peek(), clone.peek()); - assertEquals(original.dequeue(), clone.dequeue()); - assertEquals(original.peek(), clone.peek()); - assertEquals(original.dequeue(), clone.dequeue()); - assertEquals(original.isEmpty(), clone.isEmpty()); - assertEquals(original.peek(), clone.peek()); - assertEquals(original.dequeue(), clone.dequeue()); - assertTrue(original.isEmpty()); - assertEquals(original.isEmpty(), clone.isEmpty()); - - original.enqueue("fourth"); - assertFalse(original.isEmpty()); - // clone should still be empty - assertTrue(clone.isEmpty()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleStackTests.java deleted file mode 100644 index b73d8633e3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SimpleStackTests.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.EmptyStackException; - -import org.eclipse.jpt.common.utility.internal.SimpleStack; -import org.eclipse.jpt.common.utility.internal.Stack; - -@SuppressWarnings("nls") -public class SimpleStackTests - extends MultiThreadedTestCase -{ - public SimpleStackTests(String name) { - super(name); - } - - Stack<String> buildStack() { - return new SimpleStack<String>(); - } - - public void testIsEmpty() { - Stack<String> stack = this.buildStack(); - assertTrue(stack.isEmpty()); - stack.push("first"); - assertFalse(stack.isEmpty()); - stack.push("second"); - assertFalse(stack.isEmpty()); - stack.pop(); - assertFalse(stack.isEmpty()); - stack.pop(); - assertTrue(stack.isEmpty()); - } - - public void testPushAndPop() { - Stack<String> stack = this.buildStack(); - String first = "first"; - String second = "second"; - - stack.push(first); - stack.push(second); - assertEquals(second, stack.pop()); - assertEquals(first, stack.pop()); - } - - public void testPushAndPeek() { - Stack<String> stack = this.buildStack(); - String first = "first"; - String second = "second"; - - stack.push(first); - stack.push(second); - assertEquals(second, stack.peek()); - assertEquals(second, stack.peek()); - assertEquals(second, stack.pop()); - assertEquals(first, stack.peek()); - assertEquals(first, stack.peek()); - assertEquals(first, stack.pop()); - } - - public void testEmptyStackExceptionPeek() { - Stack<String> stack = this.buildStack(); - String first = "first"; - String second = "second"; - - stack.push(first); - stack.push(second); - assertEquals(second, stack.peek()); - assertEquals(second, stack.pop()); - assertEquals(first, stack.peek()); - assertEquals(first, stack.pop()); - - boolean exCaught = false; - try { - stack.peek(); - fail(); - } catch (EmptyStackException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testEmptyStackExceptionPop() { - Stack<String> stack = this.buildStack(); - String first = "first"; - String second = "second"; - - stack.push(first); - stack.push(second); - assertEquals(second, stack.peek()); - assertEquals(second, stack.pop()); - assertEquals(first, stack.peek()); - assertEquals(first, stack.pop()); - - boolean exCaught = false; - try { - stack.pop(); - fail(); - } catch (EmptyStackException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testClone() { - SimpleStack<String> stack = (SimpleStack<String>) this.buildStack(); - stack.push("first"); - stack.push("second"); - stack.push("third"); - - this.verifyClone(stack, stack.clone()); - } - - public void testSerialization() throws Exception { - Stack<String> stack = this.buildStack(); - stack.push("first"); - stack.push("second"); - stack.push("third"); - - this.verifyClone(stack, TestTools.serialize(stack)); - } - - private void verifyClone(Stack<String> original, Stack<String> clone) { - assertNotSame(original, clone); - assertEquals(original.peek(), clone.peek()); - assertEquals(original.pop(), clone.pop()); - assertEquals(original.peek(), clone.peek()); - assertEquals(original.pop(), clone.pop()); - assertEquals(original.isEmpty(), clone.isEmpty()); - assertEquals(original.peek(), clone.peek()); - assertEquals(original.pop(), clone.pop()); - assertTrue(original.isEmpty()); - assertEquals(original.isEmpty(), clone.isEmpty()); - - original.push("fourth"); - assertFalse(original.isEmpty()); - // clone should still be empty - assertTrue(clone.isEmpty()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/StringToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/StringToolsTests.java deleted file mode 100644 index b34bab2474..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/StringToolsTests.java +++ /dev/null @@ -1,1871 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2011 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.StringWriter; -import java.io.Writer; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.StringTools; - -@SuppressWarnings("nls") -public class StringToolsTests extends TestCase { - - public StringToolsTests(String name) { - super(name); - } - - private static void assertEquals(String expected, char[] actual) { - assertEquals(expected, new String(actual)); - } - - // ********** padding/truncating ********** - - public void testPad() { - assertEquals("fred", StringTools.pad("fred", 4)); - assertEquals("fred ", StringTools.pad("fred", 6)); - boolean exThrown = false; - try { - assertEquals("fr", StringTools.pad("fred", 2)); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testPadCharArray() { - assertEquals("fred", StringTools.pad(new char[] { 'f', 'r', 'e', 'd' }, 4)); - assertEquals("fred ", StringTools.pad(new char[] { 'f', 'r', 'e', 'd' }, 6)); - boolean exThrown = false; - try { - assertEquals("fr", StringTools.pad(new char[] { 'f', 'r', 'e', 'd' }, 2)); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testPadOnWriter() { - Writer writer; - writer = new StringWriter(); - StringTools.padOn("fred", 4, writer); - assertEquals("fred", writer.toString()); - - writer = new StringWriter(); - StringTools.padOn("fred", 6, writer); - assertEquals("fred ", writer.toString()); - - writer = new StringWriter(); - boolean exThrown = false; - try { - StringTools.padOn("fred", 2, writer); - fail(); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testPadOnStringBuffer() { - StringBuffer sb; - sb = new StringBuffer(); - StringTools.padOn("fred", 4, sb); - assertEquals("fred", sb.toString()); - - sb = new StringBuffer(); - StringTools.padOn("fred", 6, sb); - assertEquals("fred ", sb.toString()); - - sb = new StringBuffer(); - boolean exThrown = false; - try { - StringTools.padOn("fred", 2, sb); - fail(); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testPadOnStringBuilder() { - StringBuilder sb; - sb = new StringBuilder(); - StringTools.padOn("fred", 4, sb); - assertEquals("fred", sb.toString()); - - sb = new StringBuilder(); - StringTools.padOn("fred", 6, sb); - assertEquals("fred ", sb.toString()); - - sb = new StringBuilder(); - boolean exThrown = false; - try { - StringTools.padOn("fred", 2, sb); - fail(); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testPadOrTruncate() { - assertEquals("fred", StringTools.padOrTruncate("fred", 4)); - assertEquals("fred ", StringTools.padOrTruncate("fred", 6)); - assertEquals("fr", StringTools.padOrTruncate("fred", 2)); - } - - public void testPadOrTruncateCharArray() { - assertEquals("fred", StringTools.padOrTruncate(new char[] { 'f', 'r', 'e', 'd' }, 4)); - assertEquals("fred ", StringTools.padOrTruncate(new char[] { 'f', 'r', 'e', 'd' }, 6)); - assertEquals("fr", StringTools.padOrTruncate(new char[] { 'f', 'r', 'e', 'd' }, 2)); - } - - public void testPadOrTruncateOnWriter() { - this.verifyPadOrTruncateOnWriter("fred", "fred", 4); - this.verifyPadOrTruncateOnWriter("fred ", "fred", 6); - this.verifyPadOrTruncateOnWriter("fr", "fred", 2); - } - - private void verifyPadOrTruncateOnWriter(String expected, String string, int length) { - Writer writer = new StringWriter(); - StringTools.padOrTruncateOn(string, length, writer); - assertEquals(expected, writer.toString()); - } - - public void testPadOrTruncateOnStringBuffer() { - this.verifyPadOrTruncateOnStringBuffer("fred", "fred", 4); - this.verifyPadOrTruncateOnStringBuffer("fred ", "fred", 6); - this.verifyPadOrTruncateOnStringBuffer("fr", "fred", 2); - } - - private void verifyPadOrTruncateOnStringBuffer(String expected, String string, int length) { - StringBuffer sb = new StringBuffer(); - StringTools.padOrTruncateOn(string, length, sb); - assertEquals(expected, sb.toString()); - } - - public void testPadOrTruncateOnStringBuilder() { - this.verifyPadOrTruncateOnStringBuilder("fred", "fred", 4); - this.verifyPadOrTruncateOnStringBuilder("fred ", "fred", 6); - this.verifyPadOrTruncateOnStringBuilder("fr", "fred", 2); - } - - private void verifyPadOrTruncateOnStringBuilder(String expected, String string, int length) { - StringBuilder sb = new StringBuilder(); - StringTools.padOrTruncateOn(string, length, sb); - assertEquals(expected, sb.toString()); - } - - public void testZeroPad() { - assertEquals("1234", StringTools.zeroPad("1234", 4)); - assertEquals("001234", StringTools.zeroPad("1234", 6)); - boolean exThrown = false; - try { - assertEquals("12", StringTools.zeroPad("1234", 2)); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testZeroPadCharArray() { - assertEquals("1234", StringTools.zeroPad(new char[] { '1', '2', '3', '4' }, 4)); - assertEquals("001234", StringTools.zeroPad(new char[] { '1', '2', '3', '4' }, 6)); - boolean exThrown = false; - try { - assertEquals("12", StringTools.zeroPad(new char[] { '1', '2', '3', '4' }, 2)); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testZeroPadOnWriter() { - Writer writer; - writer = new StringWriter(); - StringTools.zeroPadOn("1234", 4, writer); - assertEquals("1234", writer.toString()); - - writer = new StringWriter(); - StringTools.zeroPadOn("1234", 6, writer); - assertEquals("001234", writer.toString()); - - writer = new StringWriter(); - boolean exThrown = false; - try { - StringTools.zeroPadOn("1234", 2, writer); - fail(); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testZeroPadOnStringBuffer() { - StringBuffer sb; - sb = new StringBuffer(); - StringTools.zeroPadOn("1234", 4, sb); - assertEquals("1234", sb.toString()); - - sb = new StringBuffer(); - StringTools.zeroPadOn("1234", 6, sb); - assertEquals("001234", sb.toString()); - - sb = new StringBuffer(); - boolean exThrown = false; - try { - StringTools.zeroPadOn("1234", 2, sb); - fail(); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testZeroPadOnStringBuilder() { - StringBuilder sb; - sb = new StringBuilder(); - StringTools.zeroPadOn("1234", 4, sb); - assertEquals("1234", sb.toString()); - - sb = new StringBuilder(); - StringTools.zeroPadOn("1234", 6, sb); - assertEquals("001234", sb.toString()); - - sb = new StringBuilder(); - boolean exThrown = false; - try { - StringTools.zeroPadOn("1234", 2, sb); - fail(); - } catch (IllegalArgumentException ex) { - exThrown = true; - } - assertTrue(exThrown); - } - - public void testZeroPadOrTruncate() { - assertEquals("1234", StringTools.zeroPadOrTruncate("1234", 4)); - assertEquals("001234", StringTools.zeroPadOrTruncate("1234", 6)); - assertEquals("34", StringTools.zeroPadOrTruncate("1234", 2)); - } - - public void testZeroPadOrTruncateCharArray() { - assertEquals("1234", StringTools.zeroPadOrTruncate(new char[] { '1', '2', '3', '4' }, 4)); - assertEquals("001234", StringTools.zeroPadOrTruncate(new char[] { '1', '2', '3', '4' }, 6)); - assertEquals("34", StringTools.zeroPadOrTruncate(new char[] { '1', '2', '3', '4' }, 2)); - } - - public void testZeroPadOrTruncateOnWriter() { - this.verifyZeroPadOrTruncateOnWriter("1234", "1234", 4); - this.verifyZeroPadOrTruncateOnWriter("001234", "1234", 6); - this.verifyZeroPadOrTruncateOnWriter("34", "1234", 2); - } - - private void verifyZeroPadOrTruncateOnWriter(String expected, String string, int length) { - Writer writer = new StringWriter(); - StringTools.zeroPadOrTruncateOn(string, length, writer); - assertEquals(expected, writer.toString()); - } - - public void testZeroPadOrTruncateOnStringBuffer() { - this.verifyZeroPadOrTruncateOnStringBuffer("1234", "1234", 4); - this.verifyZeroPadOrTruncateOnStringBuffer("001234", "1234", 6); - this.verifyZeroPadOrTruncateOnStringBuffer("34", "1234", 2); - } - - private void verifyZeroPadOrTruncateOnStringBuffer(String expected, String string, int length) { - StringBuffer sb = new StringBuffer(); - StringTools.zeroPadOrTruncateOn(string, length, sb); - assertEquals(expected, sb.toString()); - } - - public void testZeroPadOrTruncateOnStringBuilder() { - this.verifyZeroPadOrTruncateOnStringBuilder("1234", "1234", 4); - this.verifyZeroPadOrTruncateOnStringBuilder("001234", "1234", 6); - this.verifyZeroPadOrTruncateOnStringBuilder("34", "1234", 2); - } - - private void verifyZeroPadOrTruncateOnStringBuilder(String expected, String string, int length) { - StringBuilder sb = new StringBuilder(); - StringTools.zeroPadOrTruncateOn(string, length, sb); - assertEquals(expected, sb.toString()); - } - - // ********** separating ********** - - public void testSeparateStringCharInt() { - this.verifySeparate("012345", '-', 22, "012345"); - this.verifySeparate("012345", '-', 6, "012345"); - this.verifySeparate("012345", '-', 5, "01234-5"); - this.verifySeparate("012345", '-', 4, "0123-45"); - this.verifySeparate("012345", '-', 3, "012-345"); - this.verifySeparate("012345", '-', 2, "01-23-45"); - this.verifySeparate("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparate(String string, char separator, int segmentLength, String expected) { - assertEquals(expected, StringTools.separate(string, separator, segmentLength)); - } - - public void testSeparateOnStringCharIntWriter() { - this.verifySeparateOnWriter("012345", '-', 22, "012345"); - this.verifySeparateOnWriter("012345", '-', 6, "012345"); - this.verifySeparateOnWriter("012345", '-', 5, "01234-5"); - this.verifySeparateOnWriter("012345", '-', 4, "0123-45"); - this.verifySeparateOnWriter("012345", '-', 3, "012-345"); - this.verifySeparateOnWriter("012345", '-', 2, "01-23-45"); - this.verifySeparateOnWriter("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateOnWriter(String string, char separator, int segmentLength, String expected) { - Writer writer = new StringWriter(); - StringTools.separateOn(string, separator, segmentLength, writer); - assertEquals(expected, writer.toString()); - } - - public void testSeparateOnStringCharIntStringBuffer() { - this.verifySeparateOnStringBuffer("012345", '-', 22, "012345"); - this.verifySeparateOnStringBuffer("012345", '-', 6, "012345"); - this.verifySeparateOnStringBuffer("012345", '-', 5, "01234-5"); - this.verifySeparateOnStringBuffer("012345", '-', 4, "0123-45"); - this.verifySeparateOnStringBuffer("012345", '-', 3, "012-345"); - this.verifySeparateOnStringBuffer("012345", '-', 2, "01-23-45"); - this.verifySeparateOnStringBuffer("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateOnStringBuffer(String string, char separator, int segmentLength, String expected) { - StringBuffer sb = new StringBuffer(); - StringTools.separateOn(string, separator, segmentLength, sb); - assertEquals(expected, sb.toString()); - } - - public void testSeparateOnStringCharIntStringBuilder() { - this.verifySeparateOnStringBuilder("012345", '-', 22, "012345"); - this.verifySeparateOnStringBuilder("012345", '-', 6, "012345"); - this.verifySeparateOnStringBuilder("012345", '-', 5, "01234-5"); - this.verifySeparateOnStringBuilder("012345", '-', 4, "0123-45"); - this.verifySeparateOnStringBuilder("012345", '-', 3, "012-345"); - this.verifySeparateOnStringBuilder("012345", '-', 2, "01-23-45"); - this.verifySeparateOnStringBuilder("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateOnStringBuilder(String string, char separator, int segmentLength, String expected) { - StringBuilder sb = new StringBuilder(); - StringTools.separateOn(string, separator, segmentLength, sb); - assertEquals(expected, sb.toString()); - } - - public void testSeparateCharArrayCharInt() { - this.verifySeparateCharArray("012345", '-', 22, "012345"); - this.verifySeparateCharArray("012345", '-', 6, "012345"); - this.verifySeparateCharArray("012345", '-', 5, "01234-5"); - this.verifySeparateCharArray("012345", '-', 4, "0123-45"); - this.verifySeparateCharArray("012345", '-', 3, "012-345"); - this.verifySeparateCharArray("012345", '-', 2, "01-23-45"); - this.verifySeparateCharArray("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateCharArray(String string, char separator, int segmentLength, String expected) { - assertEquals(expected, StringTools.separate(string.toCharArray(), separator, segmentLength)); - } - - public void testSeparateOnCharArrayCharIntWriter() { - this.verifySeparateCharArrayOnWriter("012345", '-', 22, "012345"); - this.verifySeparateCharArrayOnWriter("012345", '-', 6, "012345"); - this.verifySeparateCharArrayOnWriter("012345", '-', 5, "01234-5"); - this.verifySeparateCharArrayOnWriter("012345", '-', 4, "0123-45"); - this.verifySeparateCharArrayOnWriter("012345", '-', 3, "012-345"); - this.verifySeparateCharArrayOnWriter("012345", '-', 2, "01-23-45"); - this.verifySeparateCharArrayOnWriter("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateCharArrayOnWriter(String string, char separator, int segmentLength, String expected) { - Writer writer = new StringWriter(); - StringTools.separateOn(string.toCharArray(), separator, segmentLength, writer); - assertEquals(expected, writer.toString()); - } - - public void testSeparateOnCharArrayCharIntStringBuffer() { - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 22, "012345"); - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 6, "012345"); - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 5, "01234-5"); - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 4, "0123-45"); - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 3, "012-345"); - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 2, "01-23-45"); - this.verifySeparateCharArrayOnStringBuffer("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateCharArrayOnStringBuffer(String string, char separator, int segmentLength, String expected) { - StringBuffer sb = new StringBuffer(); - StringTools.separateOn(string.toCharArray(), separator, segmentLength, sb); - assertEquals(expected, sb.toString()); - } - - public void testSeparateOnCharArrayCharIntStringBuilder() { - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 22, "012345"); - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 6, "012345"); - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 5, "01234-5"); - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 4, "0123-45"); - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 3, "012-345"); - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 2, "01-23-45"); - this.verifySeparateCharArrayOnStringBuilder("012345", '-', 1, "0-1-2-3-4-5"); - } - - private void verifySeparateCharArrayOnStringBuilder(String string, char separator, int segmentLength, String expected) { - StringBuilder sb = new StringBuilder(); - StringTools.separateOn(string.toCharArray(), separator, segmentLength, sb); - assertEquals(expected, sb.toString()); - } - - // ********** delimiting ********** - - public void testDelimit() { - this.verifyDelimit("Employee", "123", "123Employee123"); - this.verifyDelimit("123", "123", "123123123"); - this.verifyDelimit("", "123", "123123"); - } - - private void verifyDelimit(String string, String delimiter, String expectedString) { - assertEquals(expectedString, StringTools.delimit(string, delimiter)); - } - - public void testDelimitOnWriter() { - this.verifyDelimitOnWriter("Employee", "123", "123Employee123"); - this.verifyDelimitOnWriter("123", "123", "123123123"); - this.verifyDelimitOnWriter("", "123", "123123"); - } - - private void verifyDelimitOnWriter(String string, String delimiter, String expectedString) { - Writer writer = new StringWriter(); - StringTools.delimitOn(string, delimiter, writer); - assertEquals(expectedString, writer.toString()); - } - - public void testDelimitOnStringBuffer() { - this.verifyDelimitOnStringBuffer("Employee", "123", "123Employee123"); - this.verifyDelimitOnStringBuffer("123", "123", "123123123"); - this.verifyDelimitOnStringBuffer("", "123", "123123"); - } - - private void verifyDelimitOnStringBuffer(String string, String delimiter, String expectedString) { - StringBuffer sb = new StringBuffer(); - StringTools.delimitOn(string, delimiter, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testDelimitOnStringBuilder() { - this.verifyDelimitOnStringBuilder("Employee", "123", "123Employee123"); - this.verifyDelimitOnStringBuilder("123", "123", "123123123"); - this.verifyDelimitOnStringBuilder("", "123", "123123"); - } - - private void verifyDelimitOnStringBuilder(String string, String delimiter, String expectedString) { - StringBuilder sb = new StringBuilder(); - StringTools.delimitOn(string, delimiter, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testQuote() { - this.verifyQuote("Employee", "\"Employee\""); - this.verifyQuote("123", "\"123\""); - this.verifyQuote("", "\"\""); - this.verifyQuote("Emp\"loyee", "\"Emp\"\"loyee\""); - } - - private void verifyQuote(String string, String expectedString) { - assertEquals(expectedString, StringTools.quote(string)); - } - - public void testQuoteOnWriter() { - this.verifyQuoteOnWriter("Employee", "\"Employee\""); - this.verifyQuoteOnWriter("123", "\"123\""); - this.verifyQuoteOnWriter("", "\"\""); - this.verifyQuoteOnWriter("Emp\"loyee", "\"Emp\"\"loyee\""); - } - - private void verifyQuoteOnWriter(String string, String expectedString) { - Writer writer = new StringWriter(); - StringTools.quoteOn(string, writer); - assertEquals(expectedString, writer.toString()); - } - - public void testQuoteOnStringBuffer() { - this.verifyQuoteOnStringBuffer("Employee", "\"Employee\""); - this.verifyQuoteOnStringBuffer("123", "\"123\""); - this.verifyQuoteOnStringBuffer("", "\"\""); - this.verifyQuoteOnStringBuffer("Emp\"loyee", "\"Emp\"\"loyee\""); - } - - private void verifyQuoteOnStringBuffer(String string, String expectedString) { - StringBuffer sb = new StringBuffer(); - StringTools.quoteOn(string, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testQuoteOnStringBuilder() { - this.verifyQuoteOnStringBuilder("Employee", "\"Employee\""); - this.verifyQuoteOnStringBuilder("123", "\"123\""); - this.verifyQuoteOnStringBuilder("", "\"\""); - this.verifyQuoteOnStringBuilder("Emp\"loyee", "\"Emp\"\"loyee\""); - } - - private void verifyQuoteOnStringBuilder(String string, String expectedString) { - StringBuilder sb = new StringBuilder(); - StringTools.quoteOn(string, sb); - assertEquals(expectedString, sb.toString()); - } - - // ********** removing characters ********** - - public void testRemoveFirstOccurrence() { - this.verifyRemoveFirstOccurrence("Emplo&yee", '&', "Employee"); - this.verifyRemoveFirstOccurrence("Emplo&yee&", '&', "Employee&"); - this.verifyRemoveFirstOccurrence("Employee &Foo", '&', "Employee Foo"); - this.verifyRemoveFirstOccurrence("Employee&", '&', "Employee"); - this.verifyRemoveFirstOccurrence("&Employee", '&', "Employee"); - } - - private void verifyRemoveFirstOccurrence(String string, char charToRemove, String expectedString) { - assertEquals(expectedString, StringTools.removeFirstOccurrence(string, charToRemove)); - } - - public void testRemoveFirstOccurrenceCharArray() { - this.verifyRemoveFirstOccurrenceCharArray("Emplo&yee", '&', "Employee"); - this.verifyRemoveFirstOccurrenceCharArray("Emplo&yee&", '&', "Employee&"); - this.verifyRemoveFirstOccurrenceCharArray("Employee &Foo", '&', "Employee Foo"); - this.verifyRemoveFirstOccurrenceCharArray("Employee&", '&', "Employee"); - this.verifyRemoveFirstOccurrenceCharArray("&Employee", '&', "Employee"); - } - - private void verifyRemoveFirstOccurrenceCharArray(String string, char charToRemove, String expectedString) { - assertEquals(expectedString, StringTools.removeFirstOccurrence(string.toCharArray(), charToRemove)); - } - - public void testRemoveFirstOccurrenceOnWriter() { - this.verifyRemoveFirstOccurrenceOnWriter("Emplo&yee", '&', "Employee"); - this.verifyRemoveFirstOccurrenceOnWriter("Emplo&yee&", '&', "Employee&"); - this.verifyRemoveFirstOccurrenceOnWriter("Employee &Foo", '&', "Employee Foo"); - this.verifyRemoveFirstOccurrenceOnWriter("Employee&", '&', "Employee"); - this.verifyRemoveFirstOccurrenceOnWriter("&Employee", '&', "Employee"); - } - - private void verifyRemoveFirstOccurrenceOnWriter(String string, char charToRemove, String expectedString) { - Writer writer = new StringWriter(); - StringTools.removeFirstOccurrenceOn(string, charToRemove, writer); - assertEquals(expectedString, writer.toString()); - } - - public void testRemoveFirstOccurrenceOnStringBuffer() { - this.verifyRemoveFirstOccurrenceOnStringBuffer("Emplo&yee", '&', "Employee"); - this.verifyRemoveFirstOccurrenceOnStringBuffer("Emplo&yee&", '&', "Employee&"); - this.verifyRemoveFirstOccurrenceOnStringBuffer("Employee &Foo", '&', "Employee Foo"); - this.verifyRemoveFirstOccurrenceOnStringBuffer("Employee&", '&', "Employee"); - this.verifyRemoveFirstOccurrenceOnStringBuffer("&Employee", '&', "Employee"); - } - - private void verifyRemoveFirstOccurrenceOnStringBuffer(String string, char charToRemove, String expectedString) { - StringBuffer sb = new StringBuffer(); - StringTools.removeFirstOccurrenceOn(string, charToRemove, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testRemoveFirstOccurrenceOnStringBuilder() { - this.verifyRemoveFirstOccurrenceOnStringBuilder("Emplo&yee", '&', "Employee"); - this.verifyRemoveFirstOccurrenceOnStringBuilder("Emplo&yee&", '&', "Employee&"); - this.verifyRemoveFirstOccurrenceOnStringBuilder("Employee &Foo", '&', "Employee Foo"); - this.verifyRemoveFirstOccurrenceOnStringBuilder("Employee&", '&', "Employee"); - this.verifyRemoveFirstOccurrenceOnStringBuilder("&Employee", '&', "Employee"); - } - - private void verifyRemoveFirstOccurrenceOnStringBuilder(String string, char charToRemove, String expectedString) { - StringBuilder sb = new StringBuilder(); - StringTools.removeFirstOccurrenceOn(string, charToRemove, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testRemoveAllOccurrences() { - this.verifyRemoveAllOccurrences("Employee Fred", ' ', "EmployeeFred"); - this.verifyRemoveAllOccurrences(" Employee ", ' ', "Employee"); - this.verifyRemoveAllOccurrences("Employee Foo", ' ', "EmployeeFoo"); - this.verifyRemoveAllOccurrences(" Emp loyee Foo", ' ', "EmployeeFoo"); - } - - private void verifyRemoveAllOccurrences(String string, char charToRemove, String expectedString) { - assertEquals(expectedString, StringTools.removeAllOccurrences(string, charToRemove)); - } - - public void testRemoveAllOccurrencesCharArray() { - this.verifyRemoveAllOccurrencesCharArray("Employee Fred", ' ', "EmployeeFred"); - this.verifyRemoveAllOccurrencesCharArray(" Employee ", ' ', "Employee"); - this.verifyRemoveAllOccurrencesCharArray("Employee Foo", ' ', "EmployeeFoo"); - this.verifyRemoveAllOccurrencesCharArray(" Emp loyee Foo", ' ', "EmployeeFoo"); - } - - private void verifyRemoveAllOccurrencesCharArray(String string, char charToRemove, String expectedString) { - assertEquals(expectedString, StringTools.removeAllOccurrences(string.toCharArray(), charToRemove)); - } - - public void testRemoveAllOccurrencesOnWriter() { - this.verifyRemoveAllOccurrencesOnWriter("Employee Fred", ' ', "EmployeeFred"); - this.verifyRemoveAllOccurrencesOnWriter(" Employee ", ' ', "Employee"); - this.verifyRemoveAllOccurrencesOnWriter("Employee Foo", ' ', "EmployeeFoo"); - this.verifyRemoveAllOccurrencesOnWriter(" Emp loyee Foo", ' ', "EmployeeFoo"); - } - - private void verifyRemoveAllOccurrencesOnWriter(String string, char charToRemove, String expectedString) { - Writer writer = new StringWriter(); - StringTools.removeAllOccurrencesOn(string, charToRemove, writer); - assertEquals(expectedString, writer.toString()); - } - - public void testRemoveAllOccurrencesOnStringBuffer() { - this.verifyRemoveAllOccurrencesOnStringBuffer("Employee Fred", ' ', "EmployeeFred"); - this.verifyRemoveAllOccurrencesOnStringBuffer(" Employee ", ' ', "Employee"); - this.verifyRemoveAllOccurrencesOnStringBuffer("Employee Foo", ' ', "EmployeeFoo"); - this.verifyRemoveAllOccurrencesOnStringBuffer(" Emp loyee Foo", ' ', "EmployeeFoo"); - } - - private void verifyRemoveAllOccurrencesOnStringBuffer(String string, char charToRemove, String expectedString) { - StringBuffer sb = new StringBuffer(); - StringTools.removeAllOccurrencesOn(string, charToRemove, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testRemoveAllOccurrencesOnStringBuilder() { - this.verifyRemoveAllOccurrencesOnStringBuilder("Employee Fred", ' ', "EmployeeFred"); - this.verifyRemoveAllOccurrencesOnStringBuilder(" Employee ", ' ', "Employee"); - this.verifyRemoveAllOccurrencesOnStringBuilder("Employee Foo", ' ', "EmployeeFoo"); - this.verifyRemoveAllOccurrencesOnStringBuilder(" Emp loyee Foo", ' ', "EmployeeFoo"); - } - - private void verifyRemoveAllOccurrencesOnStringBuilder(String string, char charToRemove, String expectedString) { - StringBuilder sb = new StringBuilder(); - StringTools.removeAllOccurrencesOn(string, charToRemove, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testRemoveAllWhitespace() { - this.verifyRemoveAllWhitespace("Employee Fred\t", "EmployeeFred"); - this.verifyRemoveAllWhitespace("\tEmployee\n", "Employee"); - this.verifyRemoveAllWhitespace("Employee \t Foo", "EmployeeFoo"); - this.verifyRemoveAllWhitespace(" Emp\tloyee \n Foo", "EmployeeFoo"); - } - - private void verifyRemoveAllWhitespace(String string, String expectedString) { - assertEquals(expectedString, StringTools.removeAllWhitespace(string)); - } - - public void testRemoveAllWhitespaceCharArray() { - this.verifyRemoveAllWhitespaceCharArray("Employee Fred\t", "EmployeeFred"); - this.verifyRemoveAllWhitespaceCharArray("\tEmployee\n", "Employee"); - this.verifyRemoveAllWhitespaceCharArray("Employee \t Foo", "EmployeeFoo"); - this.verifyRemoveAllWhitespaceCharArray(" Emp\tloyee \n Foo", "EmployeeFoo"); - } - - private void verifyRemoveAllWhitespaceCharArray(String string, String expectedString) { - assertEquals(expectedString, StringTools.removeAllWhitespace(string.toCharArray())); - } - - public void testRemoveAllWhitespaceOnWriter() { - this.verifyRemoveAllWhitespaceOnWriter("Employee Fred\t", "EmployeeFred"); - this.verifyRemoveAllWhitespaceOnWriter("\tEmployee\n", "Employee"); - this.verifyRemoveAllWhitespaceOnWriter("Employee \t Foo", "EmployeeFoo"); - this.verifyRemoveAllWhitespaceOnWriter(" Emp\tloyee \n Foo", "EmployeeFoo"); - } - - private void verifyRemoveAllWhitespaceOnWriter(String string, String expectedString) { - Writer writer = new StringWriter(); - StringTools.removeAllWhitespaceOn(string, writer); - assertEquals(expectedString, writer.toString()); - } - - public void testRemoveAllWhitespaceOnStringBuffer() { - this.verifyRemoveAllWhitespaceOnStringBuffer("Employee Fred\t", "EmployeeFred"); - this.verifyRemoveAllWhitespaceOnStringBuffer("\tEmployee\n", "Employee"); - this.verifyRemoveAllWhitespaceOnStringBuffer("Employee \t Foo", "EmployeeFoo"); - this.verifyRemoveAllWhitespaceOnStringBuffer(" Emp\tloyee \n Foo", "EmployeeFoo"); - } - - private void verifyRemoveAllWhitespaceOnStringBuffer(String string, String expectedString) { - StringBuffer sb = new StringBuffer(); - StringTools.removeAllWhitespaceOn(string, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testRemoveAllWhitespaceOnStringBuilder() { - this.verifyRemoveAllWhitespaceOnStringBuilder("Employee Fred\t", "EmployeeFred"); - this.verifyRemoveAllWhitespaceOnStringBuilder("\tEmployee\n", "Employee"); - this.verifyRemoveAllWhitespaceOnStringBuilder("Employee \t Foo", "EmployeeFoo"); - this.verifyRemoveAllWhitespaceOnStringBuilder(" Emp\tloyee \n Foo", "EmployeeFoo"); - } - - private void verifyRemoveAllWhitespaceOnStringBuilder(String string, String expectedString) { - StringBuilder sb = new StringBuilder(); - StringTools.removeAllWhitespaceOn(string, sb); - assertEquals(expectedString, sb.toString()); - } -////////////////////////////// - public void testCompressWhitespace() { - this.verifyCompressWhitespace("Employee Fred\t", "Employee Fred "); - this.verifyCompressWhitespace("\tEmployee \n", " Employee "); - this.verifyCompressWhitespace("Employee \t Foo", "Employee Foo"); - this.verifyCompressWhitespace(" Emp\tloyee \n Foo ", " Emp loyee Foo "); - } - - private void verifyCompressWhitespace(String string, String expectedString) { - assertEquals(expectedString, StringTools.compressWhitespace(string)); - } - - public void testCompressWhitespaceCharArray() { - this.verifyCompressWhitespaceCharArray("Employee Fred\t", "Employee Fred "); - this.verifyCompressWhitespaceCharArray("\tEmployee \n", " Employee "); - this.verifyCompressWhitespaceCharArray("Employee \t Foo", "Employee Foo"); - this.verifyCompressWhitespaceCharArray(" Emp\tloyee \n Foo ", " Emp loyee Foo "); - } - - private void verifyCompressWhitespaceCharArray(String string, String expectedString) { - assertEquals(expectedString, StringTools.compressWhitespace(string.toCharArray())); - } - - public void testCompressWhitespaceOnWriter() { - this.verifyCompressWhitespaceOnWriter("Employee Fred\t", "Employee Fred "); - this.verifyCompressWhitespaceOnWriter("\tEmployee \n", " Employee "); - this.verifyCompressWhitespaceOnWriter("Employee \t Foo", "Employee Foo"); - this.verifyCompressWhitespaceOnWriter(" Emp\tloyee \n Foo ", " Emp loyee Foo "); - } - - private void verifyCompressWhitespaceOnWriter(String string, String expectedString) { - Writer writer = new StringWriter(); - StringTools.compressWhitespaceOn(string, writer); - assertEquals(expectedString, writer.toString()); - } - - public void testCompressWhitespaceOnStringBuffer() { - this.verifyCompressWhitespaceOnStringBuffer("Employee Fred\t", "Employee Fred "); - this.verifyCompressWhitespaceOnStringBuffer("\tEmployee \n", " Employee "); - this.verifyCompressWhitespaceOnStringBuffer("Employee \t Foo", "Employee Foo"); - this.verifyCompressWhitespaceOnStringBuffer(" Emp\tloyee \n Foo ", " Emp loyee Foo "); - } - - private void verifyCompressWhitespaceOnStringBuffer(String string, String expectedString) { - StringBuffer sb = new StringBuffer(); - StringTools.compressWhitespaceOn(string, sb); - assertEquals(expectedString, sb.toString()); - } - - public void testCompressWhitespaceOnStringBuilder() { - this.verifyCompressWhitespaceOnStringBuilder("Employee Fred\t", "Employee Fred "); - this.verifyCompressWhitespaceOnStringBuilder("\tEmployee \n", " Employee "); - this.verifyCompressWhitespaceOnStringBuilder("Employee \t Foo", "Employee Foo"); - this.verifyCompressWhitespaceOnStringBuilder(" Emp\tloyee \n Foo ", " Emp loyee Foo "); - } - - private void verifyCompressWhitespaceOnStringBuilder(String string, String expectedString) { - StringBuilder sb = new StringBuilder(); - StringTools.compressWhitespaceOn(string, sb); - assertEquals(expectedString, sb.toString()); - } - - // ********** common prefix ********** - - public void testCommonPrefixLength() { - assertEquals(3, StringTools.commonPrefixLength("fooZZZ", "fooBBB")); - assertEquals(3, StringTools.commonPrefixLength("foo", "fooBBB")); - assertEquals(3, StringTools.commonPrefixLength("fooZZZ", "foo")); - assertEquals(3, StringTools.commonPrefixLength("foo", "foo")); - } - - public void testCommonPrefixLengthMax() { - assertEquals(2, StringTools.commonPrefixLength("fooZZZ", "fooBBB", 2)); - assertEquals(2, StringTools.commonPrefixLength("foo", "fooBBB", 2)); - assertEquals(2, StringTools.commonPrefixLength("fooZZZ", "foo", 2)); - assertEquals(2, StringTools.commonPrefixLength("foo", "foo", 2)); - } - - // ********** capitalization ********** - - public void testCapitalizeCharArray() { - this.verifyCapitalizeCharArray("Oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeCharArray("Oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeCharArray(" ", new char[] { ' ', ' ', ' ' }); - this.verifyCapitalizeCharArray("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyCapitalizeCharArray("", new char[0]); - this.verifyCapitalizeCharArray("A", new char[] { 'a' }); - this.verifyCapitalizeCharArray("\u00C9cole", new char[] { '\u00E9', 'c', 'o', 'l', 'e' }); - } - - private void verifyCapitalizeCharArray(String expected, char[] string) { - assertEquals(expected, StringTools.capitalize(string)); - } - - public void testCapitalizeString() { - this.verifyCapitalizeString("Oracle", "Oracle"); - this.verifyCapitalizeString("Oracle", "oracle"); - this.verifyCapitalizeString(" ", " "); - this.verifyCapitalizeString("ORACLE", "ORACLE"); - this.verifyCapitalizeString("", ""); - this.verifyCapitalizeString("A", "a"); - this.verifyCapitalizeString("\u00C9cole", "\u00E9cole"); // �cole->�COLE - } - - private void verifyCapitalizeString(String expected, String string) { - assertEquals(expected, StringTools.capitalize(string)); - } - - public void testCapitalizeOnCharArrayStringBuffer() { - this.verifyCapitalizeOnCharArrayStringBuffer("Oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeOnCharArrayStringBuffer("Oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeOnCharArrayStringBuffer(" ", new char[] { ' ', ' ', ' ' }); - this.verifyCapitalizeOnCharArrayStringBuffer("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyCapitalizeOnCharArrayStringBuffer("", new char[0]); - this.verifyCapitalizeOnCharArrayStringBuffer("A", new char[] { 'a' }); - this.verifyCapitalizeOnCharArrayStringBuffer("\u00C9cole", new char[] { '\u00E9', 'c', 'o', 'l', 'e' }); - } - - private void verifyCapitalizeOnCharArrayStringBuffer(String expected, char[] string) { - StringBuffer sb = new StringBuffer(); - StringTools.capitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testCapitalizeOnCharArrayStringBuilder() { - this.verifyCapitalizeOnCharArrayStringBuilder("Oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeOnCharArrayStringBuilder("Oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeOnCharArrayStringBuilder(" ", new char[] { ' ', ' ', ' ' }); - this.verifyCapitalizeOnCharArrayStringBuilder("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyCapitalizeOnCharArrayStringBuilder("", new char[0]); - this.verifyCapitalizeOnCharArrayStringBuilder("A", new char[] { 'a' }); - this.verifyCapitalizeOnCharArrayStringBuilder("\u00C9cole", new char[] { '\u00E9', 'c', 'o', 'l', 'e' }); - } - - private void verifyCapitalizeOnCharArrayStringBuilder(String expected, char[] string) { - StringBuilder sb = new StringBuilder(); - StringTools.capitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testCapitalizeOnStringStringBuffer() { - this.verifyCapitalizeOnStringStringBuffer("Oracle", "Oracle"); - this.verifyCapitalizeOnStringStringBuffer("Oracle", "oracle"); - this.verifyCapitalizeOnStringStringBuffer(" ", " "); - this.verifyCapitalizeOnStringStringBuffer("ORACLE", "ORACLE"); - this.verifyCapitalizeOnStringStringBuffer("", ""); - this.verifyCapitalizeOnStringStringBuffer("A", "a"); - this.verifyCapitalizeOnStringStringBuffer("\u00C9cole", "\u00E9cole"); // �cole->�COLE - } - - private void verifyCapitalizeOnStringStringBuffer(String expected, String string) { - StringBuffer sb = new StringBuffer(); - StringTools.capitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testCapitalizeOnStringStringBuilder() { - this.verifyCapitalizeOnStringStringBuilder("Oracle", "Oracle"); - this.verifyCapitalizeOnStringStringBuilder("Oracle", "oracle"); - this.verifyCapitalizeOnStringStringBuilder(" ", " "); - this.verifyCapitalizeOnStringStringBuilder("ORACLE", "ORACLE"); - this.verifyCapitalizeOnStringStringBuilder("", ""); - this.verifyCapitalizeOnStringStringBuilder("A", "a"); - this.verifyCapitalizeOnStringStringBuilder("\u00C9cole", "\u00E9cole"); // �cole->�COLE - } - - private void verifyCapitalizeOnStringStringBuilder(String expected, String string) { - StringBuilder sb = new StringBuilder(); - StringTools.capitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testCapitalizeOnCharArrayWriter() { - this.verifyCapitalizeOnCharArrayWriter("Oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeOnCharArrayWriter("Oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyCapitalizeOnCharArrayWriter(" ", new char[] { ' ', ' ', ' ' }); - this.verifyCapitalizeOnCharArrayWriter("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyCapitalizeOnCharArrayWriter("", new char[0]); - this.verifyCapitalizeOnCharArrayWriter("A", new char[] { 'a' }); - this.verifyCapitalizeOnCharArrayWriter("\u00C9cole", new char[] { '\u00E9', 'c', 'o', 'l', 'e' }); - } - - private void verifyCapitalizeOnCharArrayWriter(String expected, char[] string) { - Writer writer = new StringWriter(); - StringTools.capitalizeOn(string, writer); - assertEquals(expected, writer.toString()); - } - - public void testCapitalizeOnStringWriter() { - this.verifyCapitalizeOnStringWriter("Oracle", "Oracle"); - this.verifyCapitalizeOnStringWriter("Oracle", "oracle"); - this.verifyCapitalizeOnStringWriter(" ", " "); - this.verifyCapitalizeOnStringWriter("ORACLE", "ORACLE"); - this.verifyCapitalizeOnStringWriter("", ""); - this.verifyCapitalizeOnStringWriter("A", "a"); - this.verifyCapitalizeOnStringWriter("\u00C9cole", "\u00E9cole"); // �cole->�COLE - } - - private void verifyCapitalizeOnStringWriter(String expected, String string) { - Writer writer = new StringWriter(); - StringTools.capitalizeOn(string, writer); - assertEquals(expected, writer.toString()); - } - - public void testUnapitalizeCharArray() { - this.verifyUncapitalizeCharArray("oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeCharArray("oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeCharArray(" ", new char[] { ' ', ' ', ' ' }); - this.verifyUncapitalizeCharArray("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyUncapitalizeCharArray("", new char[0]); - this.verifyUncapitalizeCharArray("a", new char[] { 'A' }); - this.verifyUncapitalizeCharArray("\u00E9cole", new char[] { '\u00C9', 'c', 'o', 'l', 'e' }); - } - - private void verifyUncapitalizeCharArray(String expected, char[] string) { - assertEquals(expected, StringTools.uncapitalize(string)); - } - - public void testUncapitalizeString() { - this.verifyUncapitalizeString("oracle", "Oracle"); - this.verifyUncapitalizeString("oracle", "oracle"); - this.verifyUncapitalizeString(" ", " "); - this.verifyUncapitalizeString("ORACLE", "ORACLE"); - this.verifyUncapitalizeString("", ""); - this.verifyUncapitalizeString("a", "A"); - this.verifyUncapitalizeString("\u00E9cole", "\u00C9cole"); // �cole->�COLE - } - - private void verifyUncapitalizeString(String expected, String string) { - assertEquals(expected, StringTools.uncapitalize(string)); - } - - public void testUncapitalizeOnCharArrayStringBuffer() { - this.verifyUncapitalizeOnCharArrayStringBuffer("oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeOnCharArrayStringBuffer("oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeOnCharArrayStringBuffer(" ", new char[] { ' ', ' ', ' ' }); - this.verifyUncapitalizeOnCharArrayStringBuffer("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyUncapitalizeOnCharArrayStringBuffer("", new char[0]); - this.verifyUncapitalizeOnCharArrayStringBuffer("a", new char[] { 'A' }); - this.verifyUncapitalizeOnCharArrayStringBuffer("\u00E9cole", new char[] { '\u00C9', 'c', 'o', 'l', 'e' }); - } - - private void verifyUncapitalizeOnCharArrayStringBuffer(String expected, char[] string) { - StringBuffer sb = new StringBuffer(); - StringTools.uncapitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testUncapitalizeOnCharArrayStringBuilder() { - this.verifyUncapitalizeOnCharArrayStringBuilder("oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeOnCharArrayStringBuilder("oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeOnCharArrayStringBuilder(" ", new char[] { ' ', ' ', ' ' }); - this.verifyUncapitalizeOnCharArrayStringBuilder("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyUncapitalizeOnCharArrayStringBuilder("", new char[0]); - this.verifyUncapitalizeOnCharArrayStringBuilder("a", new char[] { 'A' }); - this.verifyUncapitalizeOnCharArrayStringBuilder("\u00E9cole", new char[] { '\u00C9', 'c', 'o', 'l', 'e' }); - } - - private void verifyUncapitalizeOnCharArrayStringBuilder(String expected, char[] string) { - StringBuilder sb = new StringBuilder(); - StringTools.uncapitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testUncapitalizeOnStringStringBuffer() { - this.verifyUncapitalizeOnStringStringBuffer("oracle", "Oracle"); - this.verifyUncapitalizeOnStringStringBuffer("oracle", "oracle"); - this.verifyUncapitalizeOnStringStringBuffer(" ", " "); - this.verifyUncapitalizeOnStringStringBuffer("ORACLE", "ORACLE"); - this.verifyUncapitalizeOnStringStringBuffer("", ""); - this.verifyUncapitalizeOnStringStringBuffer("a", "A"); - this.verifyUncapitalizeOnStringStringBuffer("\u00E9cole", "\u00C9cole"); // �cole->�COLE - } - - private void verifyUncapitalizeOnStringStringBuffer(String expected, String string) { - StringBuffer sb = new StringBuffer(); - StringTools.uncapitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testUncapitalizeOnStringStringBuilder() { - this.verifyUncapitalizeOnStringStringBuilder("oracle", "Oracle"); - this.verifyUncapitalizeOnStringStringBuilder("oracle", "oracle"); - this.verifyUncapitalizeOnStringStringBuilder(" ", " "); - this.verifyUncapitalizeOnStringStringBuilder("ORACLE", "ORACLE"); - this.verifyUncapitalizeOnStringStringBuilder("", ""); - this.verifyUncapitalizeOnStringStringBuilder("a", "A"); - this.verifyUncapitalizeOnStringStringBuilder("\u00E9cole", "\u00C9cole"); // �cole->�COLE - } - - private void verifyUncapitalizeOnStringStringBuilder(String expected, String string) { - StringBuilder sb = new StringBuilder(); - StringTools.uncapitalizeOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testUncapitalizeOnCharArrayWriter() { - this.verifyUncapitalizeOnCharArrayWriter("oracle", new char[] { 'O', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeOnCharArrayWriter("oracle", new char[] { 'o', 'r', 'a', 'c', 'l', 'e' }); - this.verifyUncapitalizeOnCharArrayWriter(" ", new char[] { ' ', ' ', ' ' }); - this.verifyUncapitalizeOnCharArrayWriter("ORACLE", new char[] { 'O', 'R', 'A', 'C', 'L', 'E' }); - this.verifyUncapitalizeOnCharArrayWriter("", new char[0]); - this.verifyUncapitalizeOnCharArrayWriter("a", new char[] { 'A' }); - this.verifyUncapitalizeOnCharArrayWriter("\u00E9cole", new char[] { '\u00C9', 'c', 'o', 'l', 'e' }); - } - - private void verifyUncapitalizeOnCharArrayWriter(String expected, char[] string) { - Writer writer = new StringWriter(); - StringTools.uncapitalizeOn(string, writer); - assertEquals(expected, writer.toString()); - } - - public void testUncapitalizeOnStringWriter() { - this.verifyUncapitalizeOnStringWriter("oracle", "Oracle"); - this.verifyUncapitalizeOnStringWriter("oracle", "oracle"); - this.verifyUncapitalizeOnStringWriter(" ", " "); - this.verifyUncapitalizeOnStringWriter("ORACLE", "ORACLE"); - this.verifyUncapitalizeOnStringWriter("", ""); - this.verifyUncapitalizeOnStringWriter("a", "A"); - this.verifyUncapitalizeOnStringWriter("\u00E9cole", "\u00C9cole"); // �cole->�COLE - } - - private void verifyUncapitalizeOnStringWriter(String expected, String string) { - Writer writer = new StringWriter(); - StringTools.uncapitalizeOn(string, writer); - assertEquals(expected, writer.toString()); - } - - // ********** #toString() ********** - - public void testBuildToStringClassName_anonymous() { - Object o = new Object(){/*anonymous subclass of Object*/}; - assertEquals("Object", StringTools.buildToStringClassName(o.getClass())); - } - - public void testBuildToStringClassName_member() { - assertEquals("Map.Entry", StringTools.buildToStringClassName(java.util.Map.Entry.class)); - } - - public void testBuildToStringClassName_local() { - class Foo { - Bar bar = new Bar(); - class Bar { - Bar() { - super(); - } - } - Foo() { - super(); - } - } - Foo foo = new Foo(); - assertEquals("StringToolsTests.Foo", StringTools.buildToStringClassName(foo.getClass())); - assertEquals("StringToolsTests.Foo.Bar", StringTools.buildToStringClassName(foo.bar.getClass())); - } - - // ********** queries ********** - - public void testStringIsEmptyString() { - assertTrue(StringTools.stringIsEmpty((String) null)); - assertTrue(StringTools.stringIsEmpty("")); - assertTrue(StringTools.stringIsEmpty(" ")); - assertTrue(StringTools.stringIsEmpty(" \t\t ")); - assertTrue(StringTools.stringIsEmpty(" \t\t " + StringTools.CR)); - } - - public void testStringIsEmptyCharArray() { - assertTrue(StringTools.stringIsEmpty((char[]) null)); - this.verifyStringIsEmptyCharArray(""); - this.verifyStringIsEmptyCharArray(" \t\t "); - this.verifyStringIsEmptyCharArray(" "); - this.verifyStringIsEmptyCharArray(" \t\t " + StringTools.CR); - } - - private void verifyStringIsEmptyCharArray(String string) { - assertTrue(StringTools.stringIsEmpty(string.toCharArray())); - } - - public void testStringsAreEqualStringString() { - assertTrue(StringTools.stringsAreEqual((String) null, (String) null)); - assertFalse(StringTools.stringsAreEqual(null, "asdf")); - assertFalse(StringTools.stringsAreEqual("asdf", null)); - assertTrue(StringTools.stringsAreEqual("asdf", "asdf")); - assertFalse(StringTools.stringsAreEqual("asdf", "ASDF")); - } - - public void testStringsAreEqualCharArrayCharArray() { - assertTrue(StringTools.stringsAreEqual((char[]) null, (char[]) null)); - assertFalse(StringTools.stringsAreEqual((char[]) null, "asdf".toCharArray())); - assertFalse(StringTools.stringsAreEqual("asdf".toCharArray(), (char[]) null)); - assertTrue(StringTools.stringsAreEqual("asdf".toCharArray(), "asdf".toCharArray())); - assertFalse(StringTools.stringsAreEqual("asdf".toCharArray(), "ASDF".toCharArray())); - } - - public void testStringsAreEqualIgnoreCaseStringString() { - assertTrue(StringTools.stringsAreEqualIgnoreCase((String) null, (String) null)); - assertFalse(StringTools.stringsAreEqualIgnoreCase(null, "asdf")); - assertFalse(StringTools.stringsAreEqualIgnoreCase("asdf", null)); - assertTrue(StringTools.stringsAreEqualIgnoreCase("asdf", "asdf")); - assertTrue(StringTools.stringsAreEqualIgnoreCase("asdf", "ASDF")); - } - - public void testStringsAreEqualIgnoreCaseCharArrayCharArray() { - assertTrue(StringTools.stringsAreEqualIgnoreCase((char[]) null, (char[]) null)); - assertFalse(StringTools.stringsAreEqualIgnoreCase((char[]) null, "asdf".toCharArray())); - assertFalse(StringTools.stringsAreEqualIgnoreCase("asdf".toCharArray(), (char[]) null)); - assertTrue(StringTools.stringsAreEqualIgnoreCase("asdf".toCharArray(), "asdf".toCharArray())); - assertTrue(StringTools.stringsAreEqualIgnoreCase("asdf".toCharArray(), "ASDF".toCharArray())); - } - - public void testStringStartsWithIgnoreCaseStringString() { - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf", "as")); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf", "aS")); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf", "")); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf", "A")); - - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf", "bsdf")); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf", "g")); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf", "asdg")); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf", "asdfg")); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf", "asdfgggggg")); - } - - public void testStringStartsWithIgnoreCaseCharArrayCharArray() { - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "as".toCharArray())); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "aS".toCharArray())); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "".toCharArray())); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "A".toCharArray())); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "ASDF".toCharArray())); - assertTrue(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "asdf".toCharArray())); - - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "bsdf".toCharArray())); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "g".toCharArray())); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "asdg".toCharArray())); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "asdfg".toCharArray())); - assertFalse(StringTools.stringStartsWithIgnoreCase("asdf".toCharArray(), "asdfgggggg".toCharArray())); - } - - public void testCharactersAreEqualIgnoreCase() { - assertTrue(StringTools.charactersAreEqualIgnoreCase('a', 'a')); - assertTrue(StringTools.charactersAreEqualIgnoreCase('a', 'A')); - assertTrue(StringTools.charactersAreEqualIgnoreCase('A', 'a')); - assertTrue(StringTools.charactersAreEqualIgnoreCase('A', 'A')); - - assertFalse(StringTools.charactersAreEqualIgnoreCase('a', 'b')); - assertFalse(StringTools.charactersAreEqualIgnoreCase('A', 'b')); - } - - public void testStringIsUppercase() { - this.verifyStringIsUppercase("FOO"); - this.verifyStringIsUppercase("FOO2"); - this.verifyStringIsUppercase("F O O"); - this.denyStringIsUppercase("Foo"); - this.denyStringIsUppercase(""); - } - - private void verifyStringIsUppercase(String s) { - assertTrue(StringTools.stringIsUppercase(s)); - assertTrue(StringTools.stringIsUppercase(s.toCharArray())); - } - - private void denyStringIsUppercase(String s) { - assertFalse(StringTools.stringIsUppercase(s)); - assertFalse(StringTools.stringIsUppercase(s.toCharArray())); - } - - public void testStringIsLowercase() { - this.verifyStringIsLowercase("foo"); - this.verifyStringIsLowercase("foo2"); - this.verifyStringIsLowercase("f o o"); - this.denyStringIsLowercase("Foo"); - this.denyStringIsLowercase(""); - } - - private void verifyStringIsLowercase(String s) { - assertTrue(StringTools.stringIsLowercase(s)); - assertTrue(StringTools.stringIsLowercase(s.toCharArray())); - } - - private void denyStringIsLowercase(String s) { - assertFalse(StringTools.stringIsLowercase(s)); - assertFalse(StringTools.stringIsLowercase(s.toCharArray())); - } - - // ********** convert camel-case to all-caps ********** - - public void testConvertCamelCaseToAllCaps() { - assertEquals("TEST", StringTools.convertCamelCaseToAllCaps("test")); - assertEquals("TEST", StringTools.convertCamelCaseToAllCaps("TEST")); - assertEquals("TEST_TEST", StringTools.convertCamelCaseToAllCaps("testTest")); - assertEquals("TEST_TEST", StringTools.convertCamelCaseToAllCaps("TestTest")); - assertEquals("TEST_TEST_TEST", StringTools.convertCamelCaseToAllCaps("testTESTTest")); - assertEquals("TEST_TEST_TEST", StringTools.convertCamelCaseToAllCaps("TestTESTTest")); - assertEquals("TEST_TEST_TEST_T", StringTools.convertCamelCaseToAllCaps("TestTESTTestT")); - } - - public void testConvertCamelCaseToAllCapsOnWriter() { - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST", "test"); - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST", "TEST"); - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST_TEST", "testTest"); - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST_TEST", "TestTest"); - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST_TEST_TEST", "testTESTTest"); - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST_TEST_TEST", "TestTESTTest"); - this.verifyConvertCamelCaseToAllCapsOnWriter("TEST_TEST_TEST_T", "TestTESTTestT"); - } - - private void verifyConvertCamelCaseToAllCapsOnWriter(String expected, String string) { - Writer writer = new StringWriter(); - StringTools.convertCamelCaseToAllCapsOn(string, writer); - assertEquals(expected, writer.toString()); - } - - public void testConvertCamelCaseToAllCapsOnStringBuffer() { - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST", "test"); - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST", "TEST"); - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST_TEST", "testTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST_TEST", "TestTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST_TEST_TEST", "testTESTTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST_TEST_TEST", "TestTESTTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuffer("TEST_TEST_TEST_T", "TestTESTTestT"); - } - - private void verifyConvertCamelCaseToAllCapsOnStringBuffer(String expected, String string) { - StringBuffer sb = new StringBuffer(); - StringTools.convertCamelCaseToAllCapsOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testConvertCamelCaseToAllCapsOnStringBuilder() { - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST", "test"); - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST", "TEST"); - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST_TEST", "testTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST_TEST", "TestTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST_TEST_TEST", "testTESTTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST_TEST_TEST", "TestTESTTest"); - this.verifyConvertCamelCaseToAllCapsOnStringBuilder("TEST_TEST_TEST_T", "TestTESTTestT"); - } - - private void verifyConvertCamelCaseToAllCapsOnStringBuilder(String expected, String string) { - StringBuilder sb = new StringBuilder(); - StringTools.convertCamelCaseToAllCapsOn(string, sb); - assertEquals(expected, sb.toString()); - } - - public void testConvertCamelCaseToAllCapsMaxLength() { - assertEquals("TEST", StringTools.convertCamelCaseToAllCaps("test", 44)); - assertEquals("TEST", StringTools.convertCamelCaseToAllCaps("test", 4)); - assertEquals("TES", StringTools.convertCamelCaseToAllCaps("test", 3)); - assertEquals("TEST", StringTools.convertCamelCaseToAllCaps("TEST", 5)); - assertEquals("TE", StringTools.convertCamelCaseToAllCaps("TEST", 2)); - assertEquals("TEST_TEST", StringTools.convertCamelCaseToAllCaps("testTest", 9)); - assertEquals("TEST_TES", StringTools.convertCamelCaseToAllCaps("testTest", 8)); - assertEquals("TEST_T", StringTools.convertCamelCaseToAllCaps("testTest", 6)); - assertEquals("TEST_", StringTools.convertCamelCaseToAllCaps("testTest", 5)); - assertEquals("TEST", StringTools.convertCamelCaseToAllCaps("testTest", 4)); - assertEquals("TEST_TEST", StringTools.convertCamelCaseToAllCaps("TestTest", 9)); - assertEquals("TEST_TEST", StringTools.convertCamelCaseToAllCaps("TestTest", 1100)); - assertEquals("TEST_TEST_", StringTools.convertCamelCaseToAllCaps("testTESTTest", 10)); - assertEquals("TEST_TEST_TEST", StringTools.convertCamelCaseToAllCaps("TestTESTTest", 14)); - assertEquals("TEST_TEST_TEST_T", StringTools.convertCamelCaseToAllCaps("TestTESTTestT", 16)); - assertEquals("TEST_TEST_TEST_", StringTools.convertCamelCaseToAllCaps("TestTESTTestT", 15)); - } - - public void testConvertCamelCaseToAllCapsMaxLengthOnWriter() { - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST", "test", 44); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST", "test", 4); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TES", "test", 3); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST", "TEST", 5); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TE", "TEST", 2); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST", "testTest", 9); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TES", "testTest", 8); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_T", "testTest", 6); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_", "testTest", 5); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST", "testTest", 4); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST", "TestTest", 9); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST", "TestTest", 1100); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST_", "testTESTTest", 10); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST_TEST", "TestTESTTest", 14); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST_TEST_T", "TestTESTTestT", 16); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnWriter("TEST_TEST_TEST_", "TestTESTTestT", 15); - } - - private void verifyConvertCamelCaseToAllCapsMaxLengthOnWriter(String expected, String string, int max) { - Writer writer = new StringWriter(); - StringTools.convertCamelCaseToAllCapsOn(string, max, writer); - assertEquals(expected, writer.toString()); - } - - public void testConvertCamelCaseToAllCapsMaxLengthOnStringBuffer() { - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST", "test", 44); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST", "test", 4); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TES", "test", 3); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST", "TEST", 5); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TE", "TEST", 2); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST", "testTest", 9); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TES", "testTest", 8); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_T", "testTest", 6); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_", "testTest", 5); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST", "testTest", 4); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST", "TestTest", 9); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST", "TestTest", 1100); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST_", "testTESTTest", 10); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST_TEST", "TestTESTTest", 14); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST_TEST_T", "TestTESTTestT", 16); - this.verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer("TEST_TEST_TEST_", "TestTESTTestT", 15); - } - - private void verifyConvertCamelCaseToAllCapsMaxLengthOnStringBuffer(String expected, String string, int max) { - StringBuffer sb = new StringBuffer(); - StringTools.convertCamelCaseToAllCapsOn(string, max, sb); - assertEquals(expected, sb.toString()); - } - - // ********** convert underscores to all-caps ********** - - public void testConvertUnderscoresToCamelCase() { - assertEquals("test", StringTools.convertUnderscoresToCamelCase("TEST", false)); - assertEquals("test", StringTools.convertUnderscoresToCamelCase("TEST_", false)); - assertEquals("test", StringTools.convertUnderscoresToCamelCase("TEST____", false)); - assertEquals("Test", StringTools.convertUnderscoresToCamelCase("TEST", true)); - assertEquals("test", StringTools.convertUnderscoresToCamelCase("TeST", false)); - assertEquals("testTest", StringTools.convertUnderscoresToCamelCase("TEST_TEST", false)); - assertEquals("testTest", StringTools.convertUnderscoresToCamelCase("TEST___TEST", false)); - assertEquals("TestTest", StringTools.convertUnderscoresToCamelCase("TEST_TEST", true)); - assertEquals("testTestTest", StringTools.convertUnderscoresToCamelCase("TEST_TEST_TEST", false)); - assertEquals("TestTestTest", StringTools.convertUnderscoresToCamelCase("TEST_TEST_TEST", true)); - assertEquals("testTestTestT", StringTools.convertUnderscoresToCamelCase("TEST_TEST_TEST_T", false)); - assertEquals("testTestTestT", StringTools.convertUnderscoresToCamelCase("_TEST_TEST_TEST_T", false)); - assertEquals("testTestTestT", StringTools.convertUnderscoresToCamelCase("__TEST_TEST_TEST_T", false)); - assertEquals("TestTestTestT", StringTools.convertUnderscoresToCamelCase("TEST_TEST_TEST_T", true)); - assertEquals("TestTestTestT", StringTools.convertUnderscoresToCamelCase("_TEST_TEST_TEST_T", true)); - assertEquals("TestTestTestT", StringTools.convertUnderscoresToCamelCase("__TEST_TEST_TEST_T", true)); - } - - public void testConvertUnderscoresToCamelCaseLowercase() { - assertEquals("test", StringTools.convertUnderscoresToCamelCase("test", false)); - assertEquals("test", StringTools.convertUnderscoresToCamelCase("test_", false)); - assertEquals("test", StringTools.convertUnderscoresToCamelCase("test____", false)); - assertEquals("Test", StringTools.convertUnderscoresToCamelCase("test", true)); - assertEquals("test", StringTools.convertUnderscoresToCamelCase("test", false)); - assertEquals("testTest", StringTools.convertUnderscoresToCamelCase("test_test", false)); - assertEquals("testTest", StringTools.convertUnderscoresToCamelCase("test___test", false)); - assertEquals("TestTest", StringTools.convertUnderscoresToCamelCase("test_test", true)); - assertEquals("testTestTest", StringTools.convertUnderscoresToCamelCase("test_test_test", false)); - assertEquals("TestTestTest", StringTools.convertUnderscoresToCamelCase("test_test_test", true)); - assertEquals("testTestTestT", StringTools.convertUnderscoresToCamelCase("test_test_test_t", false)); - assertEquals("testTestTestT", StringTools.convertUnderscoresToCamelCase("_test_test_test_t", false)); - assertEquals("testTestTestT", StringTools.convertUnderscoresToCamelCase("__test_test_test_t", false)); - assertEquals("TestTestTestT", StringTools.convertUnderscoresToCamelCase("test_test_test_t", true)); - assertEquals("TestTestTestT", StringTools.convertUnderscoresToCamelCase("_test_test_test_t", true)); - assertEquals("TestTestTestT", StringTools.convertUnderscoresToCamelCase("__test_test_test_t", true)); - } - - public void testConvertUnderscoresToCamelCaseOnWriter() { - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "TEST_", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "TEST____", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("Test", "TEST", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "TeST", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTest", "TEST_TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTest", "TEST___TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTest", "TEST_TEST", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTest", "TEST_TEST_TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTest", "TEST_TEST_TEST", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTestT", "TEST_TEST_TEST_T", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTestT", "_TEST_TEST_TEST_T", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTestT", "__TEST_TEST_TEST_T", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTestT", "TEST_TEST_TEST_T", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTestT", "_TEST_TEST_TEST_T", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTestT", "__TEST_TEST_TEST_T", true); - } - - public void testConvertUnderscoresToCamelCaseOnWriterLowercase() { - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "test", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "test_", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "test____", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("Test", "test", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("test", "test", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTest", "test_test", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTest", "test___test", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTest", "test_test", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTest", "test_test_test", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTest", "test_test_test", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTestT", "test_test_test_t", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTestT", "_test_test_test_t", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("testTestTestT", "__test_test_test_t", false); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTestT", "test_test_test_t", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTestT", "_test_test_test_t", true); - this.verifyConvertUnderscoresToCamelCaseOnWriter("TestTestTestT", "__test_test_test_t", true); - } - - private void verifyConvertUnderscoresToCamelCaseOnWriter(String expected, String string, boolean capitalizeFirstLetter) { - Writer writer = new StringWriter(); - StringTools.convertUnderscoresToCamelCaseOn(string, capitalizeFirstLetter, writer); - assertEquals(expected, writer.toString()); - } - - public void testConvertUnderscoresToCamelCaseOnStringBuffer() { - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "TEST_", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "TEST____", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("Test", "TEST", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "TeST", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTest", "TEST_TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTest", "TEST___TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTest", "TEST_TEST", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTest", "TEST_TEST_TEST", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTest", "TEST_TEST_TEST", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTestT", "TEST_TEST_TEST_T", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTestT", "_TEST_TEST_TEST_T", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTestT", "__TEST_TEST_TEST_T", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTestT", "TEST_TEST_TEST_T", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTestT", "_TEST_TEST_TEST_T", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTestT", "__TEST_TEST_TEST_T", true); - } - - public void testConvertUnderscoresToCamelCaseOnStringBufferLowercase() { - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "test", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "test_", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "test____", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("Test", "test", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("test", "test", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTest", "test_test", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTest", "test___test", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTest", "test_test", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTest", "test_test_test", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTest", "test_test_test", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTestT", "test_test_test_t", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTestT", "_test_test_test_t", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("testTestTestT", "__test_test_test_t", false); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTestT", "test_test_test_t", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTestT", "_test_test_test_t", true); - this.verifyConvertUnderscoresToCamelCaseOnStringBuffer("TestTestTestT", "__test_test_test_t", true); - } - - private void verifyConvertUnderscoresToCamelCaseOnStringBuffer(String expected, String string, boolean capitalizeFirstLetter) { - StringBuffer sb = new StringBuffer(); - StringTools.convertUnderscoresToCamelCaseOn(string, capitalizeFirstLetter, sb); - assertEquals(expected, sb.toString()); - } - - // ********** delimiting ********** - - public void testStringIsQuoted() { - this.denyStringIsQuoted("foo"); - this.verifyStringIsQuoted("\"foo\""); - - this.denyStringIsQuoted(""); - this.verifyStringIsQuoted("\"\""); - - this.denyStringIsQuoted("\""); - this.denyStringIsQuoted(" "); - this.denyStringIsQuoted("''"); - this.denyStringIsQuoted("'foo'"); - } - - private void verifyStringIsQuoted(String s) { - assertTrue(StringTools.stringIsQuoted(s)); - assertTrue(StringTools.stringIsQuoted(s.toCharArray())); - } - - private void denyStringIsQuoted(String s) { - assertFalse(StringTools.stringIsQuoted(s)); - assertFalse(StringTools.stringIsQuoted(s.toCharArray())); - } - - public void testStringIsParenthetical() { - this.denyStringIsParenthetical("foo"); - this.verifyStringIsParenthetical("(foo)"); - - this.denyStringIsParenthetical(""); - this.verifyStringIsParenthetical("()"); - - this.denyStringIsParenthetical("("); - this.denyStringIsParenthetical(" "); - this.denyStringIsParenthetical("''"); - this.denyStringIsParenthetical("'foo'"); - } - - private void verifyStringIsParenthetical(String s) { - assertTrue(StringTools.stringIsParenthetical(s)); - assertTrue(StringTools.stringIsParenthetical(s.toCharArray())); - } - - private void denyStringIsParenthetical(String s) { - assertFalse(StringTools.stringIsParenthetical(s)); - assertFalse(StringTools.stringIsParenthetical(s.toCharArray())); - } - - public void testStringIsBracketed() { - this.denyStringIsBracketed("foo"); - this.verifyStringIsBracketed("[foo]"); - - this.denyStringIsBracketed(""); - this.verifyStringIsBracketed("[]"); - - this.denyStringIsBracketed("["); - this.denyStringIsBracketed(" "); - this.denyStringIsBracketed("''"); - this.denyStringIsBracketed("'foo'"); - } - - private void verifyStringIsBracketed(String s) { - assertTrue(StringTools.stringIsBracketed(s)); - assertTrue(StringTools.stringIsBracketed(s.toCharArray())); - } - - private void denyStringIsBracketed(String s) { - assertFalse(StringTools.stringIsBracketed(s)); - assertFalse(StringTools.stringIsBracketed(s.toCharArray())); - } - - public void testStringIsBraced() { - this.denyStringIsBraced("foo"); - this.verifyStringIsBraced("{foo}"); - - this.denyStringIsBraced(""); - this.verifyStringIsBraced("{}"); - - this.denyStringIsBraced("{"); - this.denyStringIsBraced(" "); - this.denyStringIsBraced("''"); - this.denyStringIsBraced("'foo'"); - } - - private void verifyStringIsBraced(String s) { - assertTrue(StringTools.stringIsBraced(s)); - assertTrue(StringTools.stringIsBraced(s.toCharArray())); - } - - private void denyStringIsBraced(String s) { - assertFalse(StringTools.stringIsBraced(s)); - assertFalse(StringTools.stringIsBraced(s.toCharArray())); - } - - public void testStringIsChevroned() { - this.denyStringIsChevroned("foo"); - this.verifyStringIsChevroned("<foo>"); - - this.denyStringIsChevroned(""); - this.verifyStringIsChevroned("<>"); - - this.denyStringIsChevroned("{"); - this.denyStringIsChevroned(" "); - this.denyStringIsChevroned("''"); - this.denyStringIsChevroned("'foo'"); - } - - private void verifyStringIsChevroned(String s) { - assertTrue(StringTools.stringIsChevroned(s)); - assertTrue(StringTools.stringIsChevroned(s.toCharArray())); - } - - private void denyStringIsChevroned(String s) { - assertFalse(StringTools.stringIsChevroned(s)); - assertFalse(StringTools.stringIsChevroned(s.toCharArray())); - } - - public void testStringIsDelimited() { - this.denyStringIsDelimited("foo", '?'); - this.verifyStringIsDelimited("?foo?", '?'); - - this.denyStringIsDelimited("", '?'); - this.verifyStringIsDelimited("\"\"", '"'); - this.verifyStringIsDelimited("?xx?", '?'); - this.denyStringIsDelimited("?xx]", '?'); - - this.denyStringIsDelimited("\"", '"'); - this.denyStringIsDelimited(" ", ' '); - this.denyStringIsDelimited("''", '"'); - this.denyStringIsDelimited("'foo'", '?'); - } - - private void verifyStringIsDelimited(String s, char c) { - assertTrue(StringTools.stringIsDelimited(s, c)); - assertTrue(StringTools.stringIsDelimited(s.toCharArray(), c)); - } - - private void denyStringIsDelimited(String s, char c) { - assertFalse(StringTools.stringIsDelimited(s, c)); - assertFalse(StringTools.stringIsDelimited(s.toCharArray(), c)); - } - - public void testStringIsDelimited2() { - this.denyStringIsDelimited2("foo", '[', ']'); - this.verifyStringIsDelimited2("{foo}", '{', '}'); - - this.denyStringIsDelimited2("", '[', ']'); - this.verifyStringIsDelimited2("[]", '[', ']'); - this.verifyStringIsDelimited2("[xx]", '[', ']'); - this.denyStringIsDelimited2("?xx]", '[', ']'); - - this.denyStringIsDelimited2("\"", '[', ']'); - this.denyStringIsDelimited2(" ", '[', ']'); - this.denyStringIsDelimited2("''", '[', ']'); - this.denyStringIsDelimited2("'foo'", '[', ']'); - } - - private void verifyStringIsDelimited2(String s, char start, char end) { - assertTrue(StringTools.stringIsDelimited(s, start, end)); - assertTrue(StringTools.stringIsDelimited(s.toCharArray(), start, end)); - } - - private void denyStringIsDelimited2(String s, char start, char end) { - assertFalse(StringTools.stringIsDelimited(s, start, end)); - assertFalse(StringTools.stringIsDelimited(s.toCharArray(), start, end)); - } - - // ********** undelimiting ********** - - public void testUndelimit() { - this.verifyUndelimit("\"foo\"", "foo"); - this.verifyUndelimit("\"\"", ""); - this.verifyUndelimit("'foo'", "foo"); - this.verifyUndelimit("\"fo\"\"o\"", "fo\"o"); - this.verifyUndelimit("\"foo\"\"\"", "foo\""); - this.verifyUndelimit("\"\"\"foo\"", "\"foo"); - this.verifyUndelimit("[foo]", "foo"); - this.verifyUndelimit("\"\"\"", "\""); - this.verifyUndelimit("\"foo\"bar\"", "foo\""); - this.verifyUndelimit("\"foo\"\"", "foo\""); - } - - private void verifyUndelimit(String s, String expected) { - assertEquals(expected, StringTools.undelimit(s)); - assertEquals(expected, StringTools.undelimit(s.toCharArray())); - } - - public void testUndelimitInt() { - this.verifyUndelimitInt("\"foo\"", 2, "o"); - this.verifyUndelimitInt("\"\"foo\"\"", 2, "foo"); - this.verifyUndelimitInt("'foo'", 2, "o"); - } - - private void verifyUndelimitInt(String s, int count, String expected) { - assertEquals(expected, StringTools.undelimit(s, count)); - assertEquals(expected, StringTools.undelimit(s.toCharArray(), count)); - } - - public void testUndelimitIntException() { - this.denyUndelimitInt("\"\"", 2); - this.denyUndelimitInt("'o'", 2); - } - - private void denyUndelimitInt(String s, int count) { - boolean exCaught = false; - try { - String bogus = StringTools.undelimit(s, count); - fail("invalid string: " + bogus); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - char[] bogus = StringTools.undelimit(s.toCharArray(), count); - fail("invalid string: " + new String(bogus)); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testUndelimitOnWriter() { - this.verifyUndelimitOnWriter("\"foo\"", "foo"); - this.verifyUndelimitOnWriter("\"\"", ""); - this.verifyUndelimitOnWriter("'foo'", "foo"); - this.verifyUndelimitOnWriter("\"fo\"\"o\"", "fo\"o"); - this.verifyUndelimitOnWriter("\"foo\"\"\"", "foo\""); - this.verifyUndelimitOnWriter("\"\"\"foo\"", "\"foo"); - this.verifyUndelimitOnWriter("[foo]", "foo"); - this.verifyUndelimitOnWriter("\"\"\"", "\""); - this.verifyUndelimitOnWriter("\"foo\"bar\"", "foo\""); - this.verifyUndelimitOnWriter("\"foo\"\"", "foo\""); - } - - private void verifyUndelimitOnWriter(String s, String expected) { - Writer writer = new StringWriter(); - StringTools.undelimitOn(s, writer); - assertEquals(expected, writer.toString()); - - writer = new StringWriter(); - StringTools.undelimitOn(s.toCharArray(), writer); - assertEquals(expected, writer.toString()); - } - - public void testUndelimitOnStringBuffer() { - this.verifyUndelimitOnStringBuffer("\"foo\"", "foo"); - this.verifyUndelimitOnStringBuffer("\"\"", ""); - this.verifyUndelimitOnStringBuffer("'foo'", "foo"); - this.verifyUndelimitOnStringBuffer("\"fo\"\"o\"", "fo\"o"); - this.verifyUndelimitOnStringBuffer("\"foo\"\"\"", "foo\""); - this.verifyUndelimitOnStringBuffer("\"\"\"foo\"", "\"foo"); - this.verifyUndelimitOnStringBuffer("[foo]", "foo"); - this.verifyUndelimitOnStringBuffer("\"\"\"", "\""); - this.verifyUndelimitOnStringBuffer("\"foo\"bar\"", "foo\""); - this.verifyUndelimitOnStringBuffer("\"foo\"\"", "foo\""); - } - - private void verifyUndelimitOnStringBuffer(String s, String expected) { - StringBuffer sb = new StringBuffer(); - StringTools.undelimitOn(s, sb); - assertEquals(expected, sb.toString()); - - sb = new StringBuffer(); - StringTools.undelimitOn(s.toCharArray(), sb); - assertEquals(expected, sb.toString()); - } - - public void testUndelimitOnStringBuilder() { - this.verifyUndelimitOnStringBuilder("\"foo\"", "foo"); - this.verifyUndelimitOnStringBuilder("\"\"", ""); - this.verifyUndelimitOnStringBuilder("'foo'", "foo"); - this.verifyUndelimitOnStringBuilder("\"fo\"\"o\"", "fo\"o"); - this.verifyUndelimitOnStringBuilder("\"foo\"\"\"", "foo\""); - this.verifyUndelimitOnStringBuilder("\"\"\"foo\"", "\"foo"); - this.verifyUndelimitOnStringBuilder("[foo]", "foo"); - this.verifyUndelimitOnStringBuilder("\"\"\"", "\""); - this.verifyUndelimitOnStringBuilder("\"foo\"bar\"", "foo\""); - this.verifyUndelimitOnStringBuilder("\"foo\"\"", "foo\""); - } - - private void verifyUndelimitOnStringBuilder(String s, String expected) { - StringBuilder sb = new StringBuilder(); - StringTools.undelimitOn(s, sb); - assertEquals(expected, sb.toString()); - - sb = new StringBuilder(); - StringTools.undelimitOn(s.toCharArray(), sb); - assertEquals(expected, sb.toString()); - } - - public void testUndelimitOnWriterCount() { - this.verifyUndelimitOnWriterCount("\"foo\"", 2, "o"); - this.verifyUndelimitOnWriterCount("\"\"\"\"", 2, ""); - this.verifyUndelimitOnWriterCount("XXfooXX", 2, "foo"); - } - - private void verifyUndelimitOnWriterCount(String s, int count, String expected) { - Writer writer = new StringWriter(); - StringTools.undelimitOn(s, count, writer); - assertEquals(expected, writer.toString()); - - writer = new StringWriter(); - StringTools.undelimitOn(s.toCharArray(), count, writer); - assertEquals(expected, writer.toString()); - } - - public void testUndelimitOnStringBufferCount() { - this.verifyUndelimitOnStringBufferCount("\"foo\"", 2, "o"); - this.verifyUndelimitOnStringBufferCount("\"\"\"\"", 2, ""); - this.verifyUndelimitOnStringBufferCount("XXfooXX", 2, "foo"); - } - - private void verifyUndelimitOnStringBufferCount(String s, int count, String expected) { - StringBuffer sb = new StringBuffer(); - StringTools.undelimitOn(s, count, sb); - assertEquals(expected, sb.toString()); - - sb = new StringBuffer(); - StringTools.undelimitOn(s.toCharArray(), count, sb); - assertEquals(expected, sb.toString()); - } - - public void testUndelimitOnStringBuilderCount() { - this.verifyUndelimitOnStringBuilderCount("\"foo\"", 2, "o"); - this.verifyUndelimitOnStringBuilderCount("\"\"\"\"", 2, ""); - this.verifyUndelimitOnStringBuilderCount("XXfooXX", 2, "foo"); - } - - private void verifyUndelimitOnStringBuilderCount(String s, int count, String expected) { - StringBuilder sb = new StringBuilder(); - StringTools.undelimitOn(s, count, sb); - assertEquals(expected, sb.toString()); - - sb = new StringBuilder(); - StringTools.undelimitOn(s.toCharArray(), count, sb); - assertEquals(expected, sb.toString()); - } - - // ********** converting to Java string literal ********** - - public void testConvertToJavaStringLiteral() { - this.verifyConvertToJavaStringLiteral("", "\"\""); - this.verifyConvertToJavaStringLiteral("\"\"", "\"\\\"\\\"\""); - this.verifyConvertToJavaStringLiteral("'foo'", "\"'foo'\""); - this.verifyConvertToJavaStringLiteral("foo\bbar", "\"foo\\bbar\""); - this.verifyConvertToJavaStringLiteral("foo\n\tbar", "\"foo\\n\\tbar\""); - this.verifyConvertToJavaStringLiteral("foo\"bar", "\"foo\\\"bar\""); - this.verifyConvertToJavaStringLiteral("foo\\bar", "\"foo\\\\bar\""); - } - - private void verifyConvertToJavaStringLiteral(String s, String expected) { - assertEquals(expected, StringTools.convertToJavaStringLiteral(s)); - assertEquals(expected, StringTools.convertToJavaStringLiteral(s.toCharArray())); - } - - public void testConvertToJavaStringLiteralOnStringBuffer() { - this.verifyConvertToJavaStringLiteralOnStringBuffer("", "\"\""); - this.verifyConvertToJavaStringLiteralOnStringBuffer("\"\"", "\"\\\"\\\"\""); - this.verifyConvertToJavaStringLiteralOnStringBuffer("'foo'", "\"'foo'\""); - this.verifyConvertToJavaStringLiteralOnStringBuffer("foo\bbar", "\"foo\\bbar\""); - this.verifyConvertToJavaStringLiteralOnStringBuffer("foo\n\tbar", "\"foo\\n\\tbar\""); - this.verifyConvertToJavaStringLiteralOnStringBuffer("foo\"bar", "\"foo\\\"bar\""); - this.verifyConvertToJavaStringLiteralOnStringBuffer("foo\\bar", "\"foo\\\\bar\""); - } - - private void verifyConvertToJavaStringLiteralOnStringBuffer(String s, String expected) { - StringBuffer sb = new StringBuffer(); - StringTools.convertToJavaStringLiteralOn(s, sb); - assertEquals(expected, sb.toString()); - - sb = new StringBuffer(); - StringTools.convertToJavaStringLiteralOn(s.toCharArray(), sb); - assertEquals(expected, sb.toString()); - } - - public void testConvertToJavaStringLiteralOnStringBuilder() { - this.verifyConvertToJavaStringLiteralOnStringBuilder("", "\"\""); - this.verifyConvertToJavaStringLiteralOnStringBuilder("\"\"", "\"\\\"\\\"\""); - this.verifyConvertToJavaStringLiteralOnStringBuilder("'foo'", "\"'foo'\""); - this.verifyConvertToJavaStringLiteralOnStringBuilder("foo\bbar", "\"foo\\bbar\""); - this.verifyConvertToJavaStringLiteralOnStringBuilder("foo\n\tbar", "\"foo\\n\\tbar\""); - this.verifyConvertToJavaStringLiteralOnStringBuilder("foo\"bar", "\"foo\\\"bar\""); - this.verifyConvertToJavaStringLiteralOnStringBuilder("foo\\bar", "\"foo\\\\bar\""); - } - - private void verifyConvertToJavaStringLiteralOnStringBuilder(String s, String expected) { - StringBuilder sb = new StringBuilder(); - StringTools.convertToJavaStringLiteralOn(s, sb); - assertEquals(expected, sb.toString()); - - sb = new StringBuilder(); - StringTools.convertToJavaStringLiteralOn(s.toCharArray(), sb); - assertEquals(expected, sb.toString()); - } - - public void testConvertToJavaStringLiteralOnWriter() { - this.verifyConvertToJavaStringLiteralOnWriter("", "\"\""); - this.verifyConvertToJavaStringLiteralOnWriter("\"\"", "\"\\\"\\\"\""); - this.verifyConvertToJavaStringLiteralOnWriter("'foo'", "\"'foo'\""); - this.verifyConvertToJavaStringLiteralOnWriter("foo\bbar", "\"foo\\bbar\""); - this.verifyConvertToJavaStringLiteralOnWriter("foo\n\tbar", "\"foo\\n\\tbar\""); - this.verifyConvertToJavaStringLiteralOnWriter("foo\"bar", "\"foo\\\"bar\""); - this.verifyConvertToJavaStringLiteralOnWriter("foo\\bar", "\"foo\\\\bar\""); - } - - private void verifyConvertToJavaStringLiteralOnWriter(String s, String expected) { - Writer writer = new StringWriter(); - StringTools.convertToJavaStringLiteralOn(s, writer); - assertEquals(expected, writer.toString()); - - writer = new StringWriter(); - StringTools.convertToJavaStringLiteralOn(s.toCharArray(), writer); - assertEquals(expected, writer.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedBooleanTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedBooleanTests.java deleted file mode 100644 index d5f31f861b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedBooleanTests.java +++ /dev/null @@ -1,341 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2011 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import org.eclipse.jpt.common.utility.internal.SynchronizedBoolean; - -public class SynchronizedBooleanTests - extends MultiThreadedTestCase -{ - private volatile SynchronizedBoolean sb; - volatile boolean timeoutOccurred; - volatile long startTime; - volatile long endTime; - - - public SynchronizedBooleanTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.sb = new SynchronizedBoolean(); - this.timeoutOccurred = false; - this.startTime = 0; - this.endTime = 0; - } - - public void testGetValue() throws Exception { - assertFalse(this.sb.getValue()); - } - - public void testIs() throws Exception { - assertTrue(this.sb.is(false)); - } - - public void testIsNot() throws Exception { - assertTrue(this.sb.isNot(true)); - } - - public void testIsTrue() throws Exception { - assertFalse(this.sb.isTrue()); - } - - public void testIsFalse() throws Exception { - assertTrue(this.sb.isFalse()); - } - - public void testSetValueFalse() throws Exception { - this.sb.setValue(false); - assertFalse(this.sb.getValue()); - assertFalse(this.sb.isTrue()); - assertTrue(this.sb.isFalse()); - } - - public void testSetValueTrue() throws Exception { - this.sb.setValue(true); - assertTrue(this.sb.getValue()); - assertTrue(this.sb.isTrue()); - assertFalse(this.sb.isFalse()); - } - - public void testFlip() throws Exception { - assertTrue(this.sb.flip()); - assertFalse(this.sb.flip()); - } - - public void testFalseAndTrue() throws Exception { - assertFalse(this.sb.and(true)); - assertFalse(this.sb.getValue()); - } - - public void testTrueAndTrue() throws Exception { - this.sb.setValue(true); - assertTrue(this.sb.and(true)); - assertTrue(this.sb.getValue()); - } - - public void testFalseAndFalse() throws Exception { - assertFalse(this.sb.and(false)); - assertFalse(this.sb.getValue()); - } - - public void testTrueAndFalse() throws Exception { - this.sb.setValue(true); - assertFalse(this.sb.and(false)); - assertFalse(this.sb.getValue()); - } - - public void testFalseOrTrue() throws Exception { - assertTrue(this.sb.or(true)); - assertTrue(this.sb.getValue()); - } - - public void testTrueOrTrue() throws Exception { - this.sb.setValue(true); - assertTrue(this.sb.or(true)); - assertTrue(this.sb.getValue()); - } - - public void testFalseOrFalse() throws Exception { - assertFalse(this.sb.or(false)); - assertFalse(this.sb.getValue()); - } - - public void testTrueOrFalse() throws Exception { - this.sb.setValue(true); - assertTrue(this.sb.or(false)); - assertTrue(this.sb.getValue()); - } - - public void testFalseXorTrue() throws Exception { - assertTrue(this.sb.xor(true)); - assertTrue(this.sb.getValue()); - } - - public void testTrueXorTrue() throws Exception { - this.sb.setValue(true); - assertFalse(this.sb.xor(true)); - assertFalse(this.sb.getValue()); - } - - public void testFalseXorFalse() throws Exception { - assertFalse(this.sb.xor(false)); - assertFalse(this.sb.getValue()); - } - - public void testTrueXorFalse() throws Exception { - this.sb.setValue(true); - assertTrue(this.sb.xor(false)); - assertTrue(this.sb.getValue()); - } - - public void testSetNotTrue() throws Exception { - this.sb.setNot(true); - assertFalse(this.sb.getValue()); - assertFalse(this.sb.isTrue()); - assertTrue(this.sb.isFalse()); - } - - public void testSetNotFalse() throws Exception { - this.sb.setNot(false); - assertTrue(this.sb.getValue()); - assertTrue(this.sb.isTrue()); - assertFalse(this.sb.isFalse()); - } - - public void testSetFalse() throws Exception { - this.sb.setFalse(); - assertFalse(this.sb.getValue()); - assertFalse(this.sb.isTrue()); - assertTrue(this.sb.isFalse()); - } - - public void testSetTrue() throws Exception { - this.sb.setTrue(); - assertTrue(this.sb.getValue()); - assertTrue(this.sb.isTrue()); - assertFalse(this.sb.isFalse()); - } - - public void testCommitFalseSuccess() throws Exception { - assertTrue(this.sb.commit(false, false)); - assertFalse(this.sb.getValue()); - } - - public void testCommitTrueSuccess() throws Exception { - assertTrue(this.sb.commit(false, true)); - assertTrue(this.sb.getValue()); - } - - public void testCommitFalseFailure() throws Exception { - assertFalse(this.sb.commit(true, false)); - assertFalse(this.sb.getValue()); - } - - public void testCommitTrueFailure() throws Exception { - assertFalse(this.sb.commit(true, true)); - assertFalse(this.sb.getValue()); - } - - public void testSwapSame() throws Exception { - assertFalse(this.sb.swap(this.sb)); - assertFalse(this.sb.getValue()); - } - - public void testSwapSameValue() throws Exception { - SynchronizedBoolean sb2 = new SynchronizedBoolean(); - assertFalse(this.sb.swap(sb2)); - assertFalse(this.sb.getValue()); - assertFalse(sb2.getValue()); - } - - public void testSwapDifferentValue() throws Exception { - SynchronizedBoolean sb2 = new SynchronizedBoolean(true); - assertTrue(this.sb.swap(sb2)); - assertTrue(this.sb.getValue()); - assertFalse(sb2.getValue()); - } - - public void testGetMutexThis() throws Exception { - assertSame(this.sb, this.sb.getMutex()); - } - - public void testGetMutexObject() throws Exception { - Object mutex = new Object(); - SynchronizedBoolean syncBool = new SynchronizedBoolean(mutex); - assertSame(mutex, syncBool.getMutex()); - } - - /** - * t2 will wait indefinitely until t1 sets the value to true - */ - public void testWaitUntilTrue() throws Exception { - this.verifyWaitUntilTrue(0); // 0 = indefinite wait - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the value should be set to true by t2 - assertTrue(this.sb.getValue()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() > TICK); - } - - /** - * t2 will time out waiting for t1 to set the value to true - */ - public void testWaitUntilTrueTimeout() throws Exception { - this.verifyWaitUntilTrue(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the value will eventually be set to true by t1 - assertTrue(this.sb.getValue()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() < THREE_TICKS); - } - - private void verifyWaitUntilTrue(long t2Timeout) throws Exception { - this.executeThreads(this.buildSetTrueCommand(), this.buildWaitUntilTrueCommand(t2Timeout)); - } - - /** - * t2 will wait indefinitely until t1 sets the value to false - */ - public void testWaitToSetFalse() throws Exception { - this.verifyWaitToSetFalse(0); // 0 = indefinite wait - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the value should be set to false by t2 - assertFalse(this.sb.getValue()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() > TICK); - } - - /** - * t2 will time out waiting for t1 to set the value to false - */ - public void testWaitToSetFalseTimeout() throws Exception { - this.verifyWaitToSetFalse(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the value will eventually be set to true by t1 - assertTrue(this.sb.getValue()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() < THREE_TICKS); - } - - private void verifyWaitToSetFalse(long t2Timeout) throws Exception { - this.executeThreads(this.buildSetTrueCommand(), this.buildWaitToSetFalseCommand(t2Timeout)); - } - - private void executeThreads(Command t1Command, Command t2Command) throws Exception { - this.sb.setFalse(); - Runnable r1 = this.buildRunnable(t1Command, this.sb, TWO_TICKS); - Runnable r2 = this.buildRunnable(t2Command, this.sb, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - private Command buildSetTrueCommand() { - return new Command() { - public void execute(SynchronizedBoolean syncBool) { - syncBool.setTrue(); - } - }; - } - - private Command buildWaitUntilTrueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedBoolean syncBool) throws InterruptedException { - SynchronizedBooleanTests.this.startTime = System.currentTimeMillis(); - SynchronizedBooleanTests.this.timeoutOccurred = ! syncBool.waitUntilTrue(timeout); - SynchronizedBooleanTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildWaitToSetFalseCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedBoolean syncBool) throws InterruptedException { - SynchronizedBooleanTests.this.startTime = System.currentTimeMillis(); - SynchronizedBooleanTests.this.timeoutOccurred = ! syncBool.waitToSetFalse(timeout); - SynchronizedBooleanTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Runnable buildRunnable(final Command command, final SynchronizedBoolean syncBool, final long delay) { - return new TestRunnable() { - @Override - public void run_() throws InterruptedException { - if (delay != 0) { - Thread.sleep(delay); - } - command.execute(syncBool); - } - }; - } - - long calculateElapsedTime() { - return this.endTime - this.startTime; - } - - - // ********** Command interface ********** - - private interface Command { - void execute(SynchronizedBoolean syncBool) throws InterruptedException; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedIntTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedIntTests.java deleted file mode 100644 index b666004427..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedIntTests.java +++ /dev/null @@ -1,361 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import org.eclipse.jpt.common.utility.internal.SynchronizedInt; - -@SuppressWarnings("nls") -public class SynchronizedIntTests - extends MultiThreadedTestCase -{ - private volatile SynchronizedInt si; - volatile boolean timeoutOccurred; - volatile int value = 7; - volatile long startTime; - volatile long endTime; - volatile int sIntValue; - - - public SynchronizedIntTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.si = new SynchronizedInt(); - this.timeoutOccurred = false; - this.startTime = 0; - this.endTime = 0; - this.sIntValue = 0; - } - - public void testGetValue() throws Exception { - assertEquals(0, this.si.getValue()); - } - - public void testEqualsInt() throws Exception { - assertTrue(this.si.equals(0)); - this.si.setValue(this.value); - assertTrue(this.si.equals(7)); - } - - public void testNotEqualInt() throws Exception { - assertTrue(this.si.notEqual(7)); - this.si.setValue(this.value); - assertTrue(this.si.notEqual(0)); - } - - public void testIsZero() throws Exception { - assertTrue(this.si.isZero()); - this.si.setValue(this.value); - assertFalse(this.si.isZero()); - } - - public void testIsNotZero() throws Exception { - assertFalse(this.si.isNotZero()); - this.si.setValue(this.value); - assertTrue(this.si.isNotZero()); - } - - public void testIsGreaterThan() throws Exception { - assertTrue(this.si.isGreaterThan(-1)); - assertFalse(this.si.isGreaterThan(0)); - assertFalse(this.si.isGreaterThan(1)); - this.si.setValue(this.value); - assertTrue(this.si.isGreaterThan(-1)); - assertFalse(this.si.isGreaterThan(7)); - assertFalse(this.si.isGreaterThan(8)); - } - - public void testIsGreaterThanOrEqual() throws Exception { - assertTrue(this.si.isGreaterThanOrEqual(-1)); - assertTrue(this.si.isGreaterThanOrEqual(0)); - assertFalse(this.si.isGreaterThanOrEqual(1)); - this.si.setValue(this.value); - assertTrue(this.si.isGreaterThanOrEqual(-1)); - assertTrue(this.si.isGreaterThanOrEqual(7)); - assertFalse(this.si.isGreaterThanOrEqual(8)); - } - - public void testIsLessThan() throws Exception { - assertFalse(this.si.isLessThan(-1)); - assertFalse(this.si.isLessThan(0)); - assertTrue(this.si.isLessThan(1)); - this.si.setValue(this.value); - assertFalse(this.si.isLessThan(-1)); - assertFalse(this.si.isLessThan(7)); - assertTrue(this.si.isLessThan(8)); - } - - public void testIsLessThanOrEqual() throws Exception { - assertFalse(this.si.isLessThanOrEqual(-1)); - assertTrue(this.si.isLessThanOrEqual(0)); - assertTrue(this.si.isLessThanOrEqual(1)); - this.si.setValue(this.value); - assertFalse(this.si.isLessThanOrEqual(-1)); - assertTrue(this.si.isLessThanOrEqual(7)); - assertTrue(this.si.isLessThanOrEqual(8)); - } - - public void testIsPositive() throws Exception { - assertFalse(this.si.isPositive()); - this.si.setValue(this.value); - assertTrue(this.si.isPositive()); - this.si.setValue(-3); - assertFalse(this.si.isPositive()); - } - - public void testIsNotPositive() throws Exception { - assertTrue(this.si.isNotPositive()); - this.si.setValue(this.value); - assertFalse(this.si.isNotPositive()); - this.si.setValue(-3); - assertTrue(this.si.isNotPositive()); - } - - public void testIsNegative() throws Exception { - assertFalse(this.si.isNegative()); - this.si.setValue(this.value); - assertFalse(this.si.isNegative()); - this.si.setValue(-3); - assertTrue(this.si.isNegative()); - } - - public void testIsNotNegative() throws Exception { - assertTrue(this.si.isNotNegative()); - this.si.setValue(this.value); - assertTrue(this.si.isNotNegative()); - this.si.setValue(-3); - assertFalse(this.si.isNotNegative()); - } - - public void testSetValue() throws Exception { - this.si.setValue(0); - assertEquals(0, this.si.getValue()); - assertFalse(this.si.isNotZero()); - assertTrue(this.si.isZero()); - - this.si.setValue(this.value); - assertEquals(this.value, this.si.getValue()); - assertTrue(this.si.isNotZero()); - assertFalse(this.si.isZero()); - } - - public void testAbs() throws Exception { - assertEquals(0, this.si.abs()); - assertEquals(0, this.si.getValue()); - this.si.setValue(this.value); - assertEquals(this.value, this.si.abs()); - assertEquals(this.value, this.si.getValue()); - this.si.setValue(-this.value); - assertEquals(this.value, this.si.abs()); - } - - public void testNeg() throws Exception { - assertEquals(0, this.si.neg()); - assertEquals(0, this.si.getValue()); - this.si.setValue(this.value); - assertEquals(-this.value, this.si.neg()); - this.si.setValue(-this.value); - assertEquals(this.value, this.si.neg()); - } - - public void testSetZero() throws Exception { - this.si.setZero(); - assertEquals(0, this.si.getValue()); - assertFalse(this.si.isNotZero()); - assertTrue(this.si.isZero()); - } - - public void testGetMutexThis() throws Exception { - assertSame(this.si, this.si.getMutex()); - } - - /** - * t2 will wait indefinitely until t1 sets the value to 0 - */ - public void testWaitUntilZero() throws Exception { - this.verifyWaitUntilZero(0); // 0 = indefinite wait - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the value should be set to 0 by t2 - assertEquals(0, this.si.getValue()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit early (expected value should be > " + TICK + "): " + time, time > TICK); - } - - /** - * t2 will time out waiting for t1 to set the value to 0 - */ - public void testWaitUntilZeroTimeout() throws Exception { - this.verifyWaitUntilZero(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the value will eventually be set to 0 by t1 - assertEquals(0, this.si.getValue()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit late (expected value should be < " + THREE_TICKS + "): " + time, time < THREE_TICKS); - } - - private void verifyWaitUntilZero(long t2Timeout) throws Exception { - this.executeThreads(this.buildSetZeroCommand(), this.buildWaitUntilZeroCommand(t2Timeout)); - } - - /** - * t2 will wait indefinitely until t1 sets the value to 0; - * then t2 will set the value to 7 - */ - public void testWaitToSetValue() throws Exception { - this.verifyWaitToSetValue(0); // 0 = indefinite wait - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the value should be set to an object by t2 - assertTrue(this.si.isNotZero()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit early (expected value should be > " + TICK + "): " + time, time > TICK); - } - - /** - * t2 will time out waiting for t1 to set the value to 0 - */ - public void testWaitToSetValueTimeout() throws Exception { - this.verifyWaitToSetValue(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the value will eventually be set to zero by t1 - assertTrue(this.si.isZero()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit late (expected value should be < " + THREE_TICKS + "): " + time, time < THREE_TICKS); - } - - private void verifyWaitToSetValue(long t2Timeout) throws Exception { - this.executeThreads(this.buildSetZeroCommand(), this.buildWaitToSetValueCommand(t2Timeout)); - } - - /** - * t2 will wait until t1 is finished "initializing" the value; - * then t2 will get the newly-initialized value (42) - */ - public void testExecute() throws Exception { - this.si.setValue(0); - Runnable r1 = this.buildRunnable(this.buildInitializeValueCommand(), this.si, 0); - // give t1 a head start - Runnable r2 = this.buildRunnable(this.buildGetValueCommand(), this.si, TICK); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - assertEquals(42, this.si.getValue()); - assertEquals(42, this.sIntValue); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit early (expected value should be > " + TWO_TICKS + "): " + time, time > TWO_TICKS); - } - - private void executeThreads(Command t1Command, Command t2Command) throws Exception { - this.si.setValue(this.value); - Runnable r1 = this.buildRunnable(t1Command, this.si, TWO_TICKS); - Runnable r2 = this.buildRunnable(t2Command, this.si, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - private Command buildSetZeroCommand() { - return new Command() { - public void execute(SynchronizedInt sInt) { - sInt.setZero(); - } - }; - } - - private Command buildWaitUntilZeroCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedInt sInt) throws InterruptedException { - SynchronizedIntTests.this.startTime = System.currentTimeMillis(); - SynchronizedIntTests.this.timeoutOccurred = ! sInt.waitUntilZero(timeout); - SynchronizedIntTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildWaitToSetValueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedInt sInt) throws InterruptedException { - SynchronizedIntTests.this.startTime = System.currentTimeMillis(); - SynchronizedIntTests.this.timeoutOccurred = ! sInt.waitToSetValue(SynchronizedIntTests.this.value, timeout); - SynchronizedIntTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildInitializeValueCommand() { - return new Command() { - public void execute(final SynchronizedInt sInt) throws InterruptedException { - sInt.execute( - new org.eclipse.jpt.common.utility.command.Command() { - public void execute() { - // pretend to perform some long initialization process - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - sInt.setValue(42); - } - } - ); - } - }; - } - - private Command buildGetValueCommand() { - return new Command() { - public void execute(SynchronizedInt sInt) throws InterruptedException { - SynchronizedIntTests.this.startTime = System.currentTimeMillis(); - SynchronizedIntTests.this.sIntValue = sInt.getValue(); - SynchronizedIntTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Runnable buildRunnable(final Command command, final SynchronizedInt sInt, final long sleep) { - return new TestRunnable() { - @Override - protected void run_() throws InterruptedException { - if (sleep != 0) { - Thread.sleep(sleep); - } - command.execute(sInt); - } - }; - } - - private long calculateElapsedTime() { - return this.endTime - this.startTime; - } - - - // ********** Command interface ********** - - private interface Command { - void execute(SynchronizedInt sInt) throws InterruptedException; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedObjectTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedObjectTests.java deleted file mode 100644 index d0fa703b62..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedObjectTests.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import org.eclipse.jpt.common.utility.internal.SynchronizedObject; - -@SuppressWarnings("nls") -public class SynchronizedObjectTests - extends MultiThreadedTestCase -{ - private volatile SynchronizedObject<Object> so; - volatile boolean timeoutOccurred; - volatile Object value = new Object(); - volatile long startTime; - volatile long endTime; - volatile Object soValue; - - - public SynchronizedObjectTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.so = new SynchronizedObject<Object>(); - this.timeoutOccurred = false; - this.startTime = 0; - this.endTime = 0; - this.soValue = null; - } - - public void testAccessors() throws Exception { - this.so.setValue(null); - assertNull(this.so.getValue()); - assertFalse(this.so.isNotNull()); - assertTrue(this.so.isNull()); - - this.so.setValue(this.value); - assertEquals(this.value, this.so.getValue()); - assertTrue(this.so.isNotNull()); - assertFalse(this.so.isNull()); - - this.so.setNull(); - assertNull(this.so.getValue()); - assertFalse(this.so.isNotNull()); - assertTrue(this.so.isNull()); - - assertSame(this.so, this.so.getMutex()); - } - - /** - * t2 will wait indefinitely until t1 sets the value to null - */ - public void testWaitUntilNull() throws Exception { - this.verifyWaitUntilNull(0); - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the value should be set to null by t2 - assertNull(this.so.getValue()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit early (expected value should be > " + TICK + "): " + time, time > TICK); - } - - /** - * t2 will time out waiting for t1 to set the value to null - */ - public void testWaitUntilNullTimeout() throws Exception { - this.verifyWaitUntilNull(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the value will eventually be set to null by t1 - assertNull(this.so.getValue()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit late (expected value should be < " + THREE_TICKS + "): " + time, time < THREE_TICKS); - } - - private void verifyWaitUntilNull(long t2Timeout) throws Exception { - this.executeThreads(this.buildSetNullCommand(), this.buildWaitUntilNullCommand(t2Timeout)); - } - - /** - * t2 will wait indefinitely until t1 sets the value to null; - * then t2 will set the value to an object - */ - public void testWaitToSetValue() throws Exception { - this.verifyWaitToSetValue(0); - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the value should be set to an object by t2 - assertTrue(this.so.isNotNull()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit early (expected value should be > " + TICK + "): " + time, time > TICK); - } - - /** - * t2 will time out waiting for t1 to set the value to null - */ - public void testWaitToSetValueTimeout() throws Exception { - this.verifyWaitToSetValue(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the value will eventually be set to null by t1 - assertTrue(this.so.isNull()); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit late (expected value should be < " + THREE_TICKS + "): " + time, time < THREE_TICKS); - } - - private void verifyWaitToSetValue(long t2Timeout) throws Exception { - this.executeThreads(this.buildSetNullCommand(), this.buildWaitToSetValueCommand(t2Timeout)); - } - - /** - * t2 will wait until t1 is finished "initializing" the value; - * then t2 will get the newly-initialized value ("foo") - */ - public void testExecute() throws Exception { - this.so.setValue(null); - Runnable r1 = this.buildRunnable(this.buildInitializeValueCommand(), this.so, 0); - // give t1 a head start of 100 ms - Runnable r2 = this.buildRunnable(this.buildGetValueCommand(), this.so, TICK); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - assertEquals("foo", this.so.getValue()); - assertEquals("foo", this.soValue); - // make a reasonable guess about how long t2 took - long time = this.calculateElapsedTime(); - assertTrue("t2 finished a bit early (expected value should be > " + TWO_TICKS + "): " + time, time > TWO_TICKS); - } - - private void executeThreads(Command t1Command, Command t2Command) throws Exception { - this.so.setValue(this.value); - Runnable r1 = this.buildRunnable(t1Command, this.so, TWO_TICKS); - Runnable r2 = this.buildRunnable(t2Command, this.so, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - private Command buildSetNullCommand() { - return new Command() { - public void execute(SynchronizedObject<Object> sObject) { - sObject.setNull(); - } - }; - } - - private Command buildWaitUntilNullCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedObject<Object> sObject) throws InterruptedException { - SynchronizedObjectTests.this.startTime = System.currentTimeMillis(); - SynchronizedObjectTests.this.timeoutOccurred = ! sObject.waitUntilNull(timeout); - SynchronizedObjectTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildWaitToSetValueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedObject<Object> sObject) throws InterruptedException { - SynchronizedObjectTests.this.startTime = System.currentTimeMillis(); - SynchronizedObjectTests.this.timeoutOccurred = ! sObject.waitToSetValue(SynchronizedObjectTests.this.value, timeout); - SynchronizedObjectTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildInitializeValueCommand() { - return new Command() { - public void execute(final SynchronizedObject<Object> sObject) throws InterruptedException { - sObject.execute( - new org.eclipse.jpt.common.utility.command.Command() { - public void execute() { - // pretend to perform some long initialization process - try { - Thread.sleep(5 * TICK); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - sObject.setValue("foo"); - } - } - ); - } - }; - } - - private Command buildGetValueCommand() { - return new Command() { - public void execute(SynchronizedObject<Object> sObject) throws InterruptedException { - SynchronizedObjectTests.this.startTime = System.currentTimeMillis(); - SynchronizedObjectTests.this.soValue = sObject.getValue(); - SynchronizedObjectTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Runnable buildRunnable(final Command command, final SynchronizedObject<Object> sObject, final long sleep) { - return new TestRunnable() { - @Override - protected void run_() throws InterruptedException { - if (sleep != 0) { - Thread.sleep(sleep); - } - command.execute(sObject); - } - }; - } - - private long calculateElapsedTime() { - return this.endTime - this.startTime; - } - - - // ********** Command interface ********** - - private interface Command { - void execute(SynchronizedObject<Object> so) throws InterruptedException; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedQueueTests.java deleted file mode 100644 index c2d7687e17..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedQueueTests.java +++ /dev/null @@ -1,256 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.Queue; -import org.eclipse.jpt.common.utility.internal.SimpleQueue; -import org.eclipse.jpt.common.utility.internal.SynchronizedQueue; - -@SuppressWarnings("nls") -public class SynchronizedQueueTests extends SimpleQueueTests { - private volatile SynchronizedQueue<String> sq; - volatile boolean timeoutOccurred; - volatile long startTime; - volatile long endTime; - volatile Object dequeuedObject; - - static final String ITEM_1 = new String(); - static final String ITEM_2 = new String(); - - public SynchronizedQueueTests(String name) { - super(name); - } - - @Override - Queue<String> buildQueue() { - return new SynchronizedQueue<String>(); - } - - @Override - public void testClone() { - // synchronized queue is not cloneable - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.sq = new SynchronizedQueue<String>(); - this.timeoutOccurred = false; - this.startTime = 0; - this.endTime = 0; - this.dequeuedObject = null; - } - - /** - * test first with an unsynchronized queue, - * then with a synchronized queue - */ - public void testConcurrentAccess() throws Exception { - this.verifyConcurrentAccess(new SlowSimpleQueue<String>(), "first"); - this.verifyConcurrentAccess(new SlowSynchronizedQueue<String>(), "second"); - } - - private void verifyConcurrentAccess(SlowQueue<String> slowQueue, String expected) throws Exception { - slowQueue.enqueue("first"); - slowQueue.enqueue("second"); - - Thread thread = this.buildThread(this.buildRunnable(slowQueue)); - thread.start(); - Thread.sleep(TWO_TICKS); - - assertEquals(expected, slowQueue.dequeue()); - thread.join(); - assertTrue(slowQueue.isEmpty()); - } - - private Runnable buildRunnable(final SlowQueue<String> slowQueue) { - return new Runnable() { - public void run() { - slowQueue.slowDequeue(); - } - }; - } - - - private interface SlowQueue<E> extends Queue<E> { - Object slowDequeue(); - } - - private class SlowSimpleQueue<E> extends SimpleQueue<E> implements SlowQueue<E> { - SlowSimpleQueue() { - super(); - } - public Object slowDequeue() { - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - return this.dequeue(); - } - - } - - private class SlowSynchronizedQueue<E> extends SynchronizedQueue<E> implements SlowQueue<E> { - SlowSynchronizedQueue() { - super(); - } - public synchronized Object slowDequeue() { - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - return this.dequeue(); - } - - } - - - // ********** waits ********** - - public void testWaitToDequeue() throws Exception { - this.verifyWaitToDequeue(0); - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and an item should have been dequeued by t2... - assertSame(ITEM_1, this.dequeuedObject); - // ...and the queue should be empty - assertTrue(this.sq.isEmpty()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() > TICK); - } - - public void testWaitToDequeueTimeout() throws Exception { - this.verifyWaitToDequeue(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the queue was never dequeued... - assertNull(this.dequeuedObject); - // ...and it still holds the item - assertSame(ITEM_1, this.sq.peek()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() < THREE_TICKS); - } - - private void verifyWaitToDequeue(long timeout) throws Exception { - Runnable r1 = this.buildRunnable(this.buildEnqueueCommand(), this.sq, TWO_TICKS); - Runnable r2 = this.buildRunnable(this.buildWaitToDequeueCommand(timeout), this.sq, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - public void testWaitToEnqueue() throws Exception { - this.verifyWaitToEnqueue(0); - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the queue gets dequeued by t1... - assertSame(ITEM_1, this.dequeuedObject); - // ...and an item is enqueued on to the queue by t2 - assertFalse(this.sq.isEmpty()); - assertSame(ITEM_2, this.sq.peek()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() > TICK); - } - - public void testWaitToEnqueueTimeout() throws Exception { - this.verifyWaitToEnqueue(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the queue is eventually dequeued by t1... - assertSame(ITEM_1, this.dequeuedObject); - // ...but nothing is enqueued on to the queue by t2 - assertTrue(this.sq.isEmpty()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() < THREE_TICKS); - } - - private void verifyWaitToEnqueue(long timeout) throws Exception { - this.sq.enqueue(ITEM_1); - Runnable r1 = this.buildRunnable(this.buildDequeueCommand(), this.sq, TWO_TICKS); - Runnable r2 = this.buildRunnable(this.buildWaitToEnqueueCommand(timeout), this.sq, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - private Command buildEnqueueCommand() { - return new Command() { - public void execute(SynchronizedQueue<String> synchronizedQueue) { - synchronizedQueue.enqueue(ITEM_1); - } - }; - } - - private Command buildWaitToDequeueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedQueue<String> synchronizedQueue) throws InterruptedException { - SynchronizedQueueTests.this.startTime = System.currentTimeMillis(); - try { - SynchronizedQueueTests.this.dequeuedObject = synchronizedQueue.waitToDequeue(timeout); - } catch (NoSuchElementException ex) { - SynchronizedQueueTests.this.timeoutOccurred = true; - } - SynchronizedQueueTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildDequeueCommand() { - return new Command() { - public void execute(SynchronizedQueue<String> synchronizedQueue) { - SynchronizedQueueTests.this.dequeuedObject = synchronizedQueue.dequeue(); - } - }; - } - - private Command buildWaitToEnqueueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedQueue<String> synchronizedQueue) throws InterruptedException { - SynchronizedQueueTests.this.startTime = System.currentTimeMillis(); - SynchronizedQueueTests.this.timeoutOccurred = ! synchronizedQueue.waitToEnqueue(ITEM_2, timeout); - SynchronizedQueueTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Runnable buildRunnable(final Command command, final SynchronizedQueue<String> synchronizedQueue, final long sleep) { - return new TestRunnable() { - @Override - protected void run_() throws Throwable { - if (sleep != 0) { - Thread.sleep(sleep); - } - command.execute(synchronizedQueue); - } - }; - } - - long calculateElapsedTime() { - return this.endTime - this.startTime; - } - - - // ********** Command interface ********** - - private interface Command { - void execute(SynchronizedQueue<String> synchronizedQueue) throws InterruptedException; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedStackTests.java deleted file mode 100644 index 16cb62f345..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/SynchronizedStackTests.java +++ /dev/null @@ -1,257 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.util.EmptyStackException; -import org.eclipse.jpt.common.utility.internal.SimpleStack; -import org.eclipse.jpt.common.utility.internal.Stack; -import org.eclipse.jpt.common.utility.internal.SynchronizedStack; - -@SuppressWarnings("nls") -public class SynchronizedStackTests - extends SimpleStackTests -{ - private volatile SynchronizedStack<String> ss; - volatile boolean timeoutOccurred; - volatile long startTime; - volatile long endTime; - volatile Object poppedObject; - - static final String ITEM_1 = new String(); - static final String ITEM_2 = new String(); - - public SynchronizedStackTests(String name) { - super(name); - } - - @Override - Stack<String> buildStack() { - return new SynchronizedStack<String>(); - } - - @Override - public void testClone() { - // synchronized stack is not cloneable - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.ss = new SynchronizedStack<String>(); - this.timeoutOccurred = false; - this.startTime = 0; - this.endTime = 0; - this.poppedObject = null; - } - - /** - * test first with an unsynchronized stack, - * then with a synchronized stack - */ - public void testConcurrentAccess() throws Exception { - this.verifyConcurrentAccess(new SlowSimpleStack<String>(), "second"); - this.verifyConcurrentAccess(new SlowSynchronizedStack<String>(), "first"); - } - - private void verifyConcurrentAccess(SlowStack<String> slowStack, String expected) throws Exception { - slowStack.push("first"); - slowStack.push("second"); - - Thread thread = this.buildThread(this.buildRunnable(slowStack)); - thread.start(); - Thread.sleep(TWO_TICKS); - - assertEquals(expected, slowStack.pop()); - thread.join(); - assertTrue(slowStack.isEmpty()); - } - - private Runnable buildRunnable(final SlowStack<String> slowStack) { - return new Runnable() { - public void run() { - slowStack.slowPop(); - } - }; - } - - - private interface SlowStack<E> extends Stack<E> { - Object slowPop(); - } - - private class SlowSimpleStack<E> extends SimpleStack<E> implements SlowStack<E> { - SlowSimpleStack() { - super(); - } - public Object slowPop() { - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - return this.pop(); - } - - } - - private class SlowSynchronizedStack<E> extends SynchronizedStack<E> implements SlowStack<E> { - SlowSynchronizedStack() { - super(); - } - public synchronized Object slowPop() { - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - return this.pop(); - } - - } - - - // ********** waits ********** - - public void testWaitToPop() throws Exception { - this.verifyWaitToPop(0); - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and an item should have been popped by t2... - assertSame(ITEM_1, this.poppedObject); - // ...and the stack should be empty - assertTrue(this.ss.isEmpty()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() > TICK); - } - - public void testWaitToPopTimeout() throws Exception { - this.verifyWaitToPop(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the stack was never popped... - assertNull(this.poppedObject); - // ...and it still holds the item - assertSame(ITEM_1, this.ss.peek()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() < THREE_TICKS); - } - - private void verifyWaitToPop(long timeout) throws Exception { - Runnable r1 = this.buildRunnable(this.buildPushCommand(), this.ss, TWO_TICKS); - Runnable r2 = this.buildRunnable(this.buildWaitToPopCommand(timeout), this.ss, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - public void testWaitToPush() throws Exception { - this.verifyWaitToPush(0); - // no timeout occurs... - assertFalse(this.timeoutOccurred); - // ...and the stack gets popped by t1... - assertSame(ITEM_1, this.poppedObject); - // ...and an item is pushed on to the stack by t2 - assertFalse(this.ss.isEmpty()); - assertSame(ITEM_2, this.ss.peek()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() > TICK); - } - - public void testWaitToPushTimeout() throws Exception { - this.verifyWaitToPush(TICK); - // timeout occurs... - assertTrue(this.timeoutOccurred); - // ...and the stack is eventually popped by t1... - assertSame(ITEM_1, this.poppedObject); - // ...but nothing is pushed on to the stack by t2 - assertTrue(this.ss.isEmpty()); - // make a reasonable guess about how long t2 took - assertTrue(this.calculateElapsedTime() < THREE_TICKS); - } - - private void verifyWaitToPush(long timeout) throws Exception { - this.ss.push(ITEM_1); - Runnable r1 = this.buildRunnable(this.buildPopCommand(), this.ss, TWO_TICKS); - Runnable r2 = this.buildRunnable(this.buildWaitToPushCommand(timeout), this.ss, 0); - Thread t1 = this.buildThread(r1); - Thread t2 = this.buildThread(r2); - t1.start(); - t2.start(); - t1.join(); - t2.join(); - } - - private Command buildPushCommand() { - return new Command() { - public void execute(SynchronizedStack<String> synchronizedStack) { - synchronizedStack.push(ITEM_1); - } - }; - } - - private Command buildWaitToPopCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedStack<String> synchronizedStack) throws InterruptedException { - SynchronizedStackTests.this.startTime = System.currentTimeMillis(); - try { - SynchronizedStackTests.this.poppedObject = synchronizedStack.waitToPop(timeout); - } catch (EmptyStackException ex) { - SynchronizedStackTests.this.timeoutOccurred = true; - } - SynchronizedStackTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Command buildPopCommand() { - return new Command() { - public void execute(SynchronizedStack<String> synchronizedStack) { - SynchronizedStackTests.this.poppedObject = synchronizedStack.pop(); - } - }; - } - - private Command buildWaitToPushCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedStack<String> synchronizedStack) throws InterruptedException { - SynchronizedStackTests.this.startTime = System.currentTimeMillis(); - SynchronizedStackTests.this.timeoutOccurred = ! synchronizedStack.waitToPush(ITEM_2, timeout); - SynchronizedStackTests.this.endTime = System.currentTimeMillis(); - } - }; - } - - private Runnable buildRunnable(final Command command, final SynchronizedStack<String> synchronizedStack, final long sleep) { - return new TestRunnable() { - @Override - protected void run_() throws Throwable { - if (sleep != 0) { - Thread.sleep(sleep); - } - command.execute(synchronizedStack); - } - }; - } - - long calculateElapsedTime() { - return this.endTime - this.startTime; - } - - - // ********** Command interface ********** - - private interface Command { - void execute(SynchronizedStack<String> synchronizedStack) throws InterruptedException; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/TestCommand.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/TestCommand.java deleted file mode 100644 index 34040e489f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/TestCommand.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -/** - * Command that can be used to execute tests; i.e. a command that allows its - * implementation to throw exceptions. - */ -public interface TestCommand { - void execute() throws Exception; -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/TestTools.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/TestTools.java deleted file mode 100644 index 5fff2ff48b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/TestTools.java +++ /dev/null @@ -1,254 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.SortedSet; -import java.util.TreeSet; - -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestFailure; -import junit.framework.TestResult; -import junit.textui.TestRunner; - -import org.eclipse.jpt.common.utility.internal.ReflectionTools; - -/** - * Various tools that can be used by test cases. - */ -@SuppressWarnings("nls") -public final class TestTools { - - /** - * Convenience method that handles {@link InterruptedException}. - */ - public static void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - } - - /** - * Execute the specified command. If it throws an exception, re-execute it - * repeatedly until it executes without an exception. - * There will be a one-second delay between each execution. - * This is useful when calling third-party code that intermittently throws - * exceptions but will <em>eventually</em> execute successfully (e.g. when - * there are problems deleting files). - */ - public static void execute(TestCommand command) { - execute(command, -1); - } - - /** - * Execute the specified command. If it throws an exception, re-execute it - * repeatedly until it executes without an exception. Execute the command - * up to the specified number of attempts. - * There will be a one-second delay between each execution. - * This is useful when calling third-party code that intermittently throws - * exceptions but will <em>eventually</em> execute successfully (e.g. when - * there are problems deleting files). - */ - public static void execute(TestCommand command, int attempts) { - execute(command, attempts, 1000); - } - - /** - * Execute the specified command. If it throws an exception, re-execute it - * repeatedly until it executes without an exception. Execute the command - * up to the specified number of attemptsl with specified delay between - * each execution. - * This is useful when calling third-party code that intermittently throws - * exceptions but will <em>eventually</em> execute successfully (e.g. when - * there are problems deleting files). - */ - public static void execute(TestCommand command, int attempts, long delay) { - for (int i = 1; i <= attempts; i++) { // NB: start with 1 - try { - command.execute(); - return; - } catch (Exception ex) { - if ((attempts != -1) && (i == attempts)) { - throw new RuntimeException("attempts: " + i, ex); - } - sleep(delay); - } - } - } - - /** - * Test an object's implementation of {@link Serializable} by serializing the - * specified object to a byte array; then de-serializing the byte array and - * returning the resultant object. - */ - public static <T> T serialize(T o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(2000); - ObjectOutputStream outStream = new ObjectOutputStream(baOutStream); - outStream.writeObject(o); - outStream.close(); - - ByteArrayInputStream baInStream = new ByteArrayInputStream(baOutStream.toByteArray()); - ObjectInputStream inStream = new ObjectInputStream(baInStream); - T o2 = readObject(inStream); - inStream.close(); - - return o2; - } - - @SuppressWarnings("unchecked") - private static <T> T readObject(ObjectInput objectInput) throws IOException, ClassNotFoundException { - return (T) objectInput.readObject(); - } - - /** - * Redirect std out and std err to the specified stream. - */ - public static void redirectSystemStreamsTo(OutputStream outputStream) { - redirectSystemStreamsTo(new PrintStream(outputStream)); - } - - /** - * Redirect std out and std err to the specified stream. - */ - public static void redirectSystemStreamsTo(PrintStream printStream) { - System.setOut(printStream); - System.setErr(printStream); - } - - /** - * Sort and print out all the current Java System properties on the - * console. - */ - public static void printSystemProperties() { - synchronized (System.out) { - printSystemPropertiesOn(System.out); - } - } - - /** - * Sort and print out all the current Java System properties on the - * specified print stream. - */ - public static void printSystemPropertiesOn(PrintStream stream) { - SortedSet<String> sortedKeys = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); - for (Object key : System.getProperties().keySet()) { - sortedKeys.add((String) key); - } - for (String key : sortedKeys) { - stream.print(key); - stream.print(" => "); - stream.print(System.getProperty(key)); - stream.println(); - } - } - - /** - * Execute the specified test and return a text output of its results. - */ - public static String execute(TestCase testCase) { - long start = System.currentTimeMillis(); - TestResult result = testCase.run(); - long end = System.currentTimeMillis(); - - StringWriter stringWriter = new StringWriter(); - PrintWriter writer = new PrintWriter(stringWriter); - writer.print(testCase.getName()); - writer.print(": "); - if (result.wasSuccessful()) { - writer.println("OK"); - } else { - TestFailure failure = null; - if (result.failures().hasMoreElements()) { - failure = result.failures().nextElement(); - } else { - failure = result.errors().nextElement(); - } - failure.thrownException().printStackTrace(writer); - } - writer.print("elapsed time: "); - long elapsed = end - start; - writer.print(elapsed / 1000L); - writer.println(" sec."); - return stringWriter.toString(); - } - - /** - * Clear out all the instance variable of the specified test case, allowing - * the various test fixtures to be garbage-collected. Typically this is - * called in the test case's implementation of {@link TestCase#tearDown()}. - */ - public static void clear(TestCase testCase) throws IllegalAccessException { - for (Class<?> clazz = testCase.getClass(); clazz != TestCase_class; clazz = clazz.getSuperclass()) { - for (Field field : clazz.getDeclaredFields()) { - // leave primitives alone - they don't get garbage-collected, and we can't set them to null... - if (field.getType().isPrimitive()) { - continue; - } - // leave static fields alone (?) - if (Modifier.isStatic(field.getModifiers())) { - continue; - } - field.setAccessible(true); - field.set(testCase, null); - } - } - } - - /** - * Return the value of the specified class's <code>DEBUG</code> constant. - */ - public static boolean debug(Class<?> clazz) { - Boolean debug = (Boolean) ReflectionTools.getStaticFieldValue(clazz, "DEBUG"); - return debug.booleanValue(); - } - - /** - * Verify the specified class's <code>DEBUG</code> constant is set to - * <code>false</code>. - */ - public static void assertFalseDEBUG(Class<?> clazz) { - Assert.assertFalse("Recompile with \"DEBUG = false\": " + clazz.getName(), debug(clazz)); - } - - private static final Class<TestCase> TestCase_class = TestCase.class; - - /** - * Workaround for a JUnit bug: JUnit does not configure the testing {@link Thread} - * with a context class loader. This should probably happen in - * {@link TestRunner#doRun(Test)}, just before starting the thread. - */ - public static void setUpJUnitThreadContextClassLoader() { - Thread.currentThread().setContextClassLoader(TestTools.class.getClassLoader()); - } - - /** - * suppressed constructor - */ - private TestTools() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ToolsTests.java deleted file mode 100644 index bf7fcba128..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/ToolsTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import org.eclipse.jpt.common.utility.internal.Tools; - -import junit.framework.TestCase; - -@SuppressWarnings("nls") -public class ToolsTests extends TestCase { - - public ToolsTests(String name) { - super(name); - } - - public void testValuesAreEqual1() { - assertTrue(Tools.valuesAreEqual(null, null)); - } - - public void testValuesAreEqual2() { - assertFalse(Tools.valuesAreEqual(null, "foo")); - } - - public void testValuesAreEqual3() { - assertFalse(Tools.valuesAreEqual("foo", null)); - } - - public void testValuesAreEqual4() { - assertTrue(Tools.valuesAreEqual("foo", "foo")); - } - - public void testValuesAreEqual5() { - assertFalse(Tools.valuesAreEqual("foo", "bar")); - } - - public void testValuesAreDifferent1() { - assertFalse(Tools.valuesAreDifferent(null, null)); - } - - public void testValuesAreDifferent2() { - assertTrue(Tools.valuesAreDifferent(null, "foo")); - } - - public void testValuesAreDifferent3() { - assertTrue(Tools.valuesAreDifferent("foo", null)); - } - - public void testValuesAreDifferent4() { - assertFalse(Tools.valuesAreDifferent("foo", "foo")); - } - - public void testValuesAreDifferent5() { - assertTrue(Tools.valuesAreDifferent("foo", "bar")); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/VersionComparatorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/VersionComparatorTests.java deleted file mode 100644 index 3a7eff17a3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/VersionComparatorTests.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Comparator; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.StringTools; -import org.eclipse.jpt.common.utility.internal.VersionComparator; -import org.eclipse.jpt.common.utility.internal.VersionComparator.SegmentParser; - -@SuppressWarnings("nls") -public class VersionComparatorTests - extends TestCase -{ - public VersionComparatorTests(String name) { - super(name); - } - - public void testVersionIsEqual_integer() { - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.0", "2.0.0") == 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.0", "2.0.0.0") == 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.0.0.0.0.0000", "2.0") == 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.-1", "2.0.-1") == 0); - } - - public void testVersionIsLess_integer() { - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.0", "2.0.1") < 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.5.0", "2.14") < 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.5.0", "2.5.0.0.1.0") < 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.5.0.0.0.-1", "2.5") < 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.-1", "2.0.0") < 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.-1", "2") < 0); - } - - public void testVersionIsGreater_integer() { - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.2", "2.0.1") > 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.2", "2.0.1") > 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.5.0.0.1.0", "2.5.0") > 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.5", "2.5.0.0.0.-1") > 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.0", "2.0.-1") > 0); - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2", "2.0.-1") > 0); - } - - public void testVersionIsEqual_integer_comma() { - Comparator<String> versionComparator = new VersionComparator<BigDecimal>(",", DecimalSegmentParser.instance()); - assertTrue(versionComparator.compare("2,0,0", "2,0,0") == 0); - assertTrue(versionComparator.compare("2,0.0,0", "2,0,0") == 0); - assertTrue(versionComparator.compare("2,0.0,0", "2,0,0.0") == 0); - assertTrue(versionComparator.compare("2.0,0.0,0", "2,0,0.0") == 0); - } - - public void testVersionIsLess_integer_comma() { - Comparator<String> versionComparator = new VersionComparator<BigDecimal>(",", DecimalSegmentParser.instance()); - assertTrue(versionComparator.compare("2,0,0", "2,0,1") < 0); - assertTrue(versionComparator.compare("2,0.0,0", "2,0,1") < 0); - assertTrue(versionComparator.compare("2,0,0", "2,0,1.0") < 0); - assertTrue(versionComparator.compare("2.0,0,0", "2,0,1") < 0); - } - - public void testVersionIsGreater_integer_comma() { - Comparator<String> versionComparator = new VersionComparator<BigDecimal>(",", DecimalSegmentParser.instance()); - assertTrue(versionComparator.compare("2,0,2", "2,0,1") > 0); - assertTrue(versionComparator.compare("2,0,2.1", "2,0,1") > 0); - assertTrue(versionComparator.compare("2,0,2", "2,0,1.9") > 0); - assertTrue(versionComparator.compare("2.000,0,2", "2,0,1") > 0); - } - - public void testVersionIsEqual_subclass() { - Comparator<String> versionComparator = new VersionComparator<Integer>() { - @Override - protected Integer parseSegment(int index, String s) { - return Integer.valueOf(s); - } - @Override - protected Integer getZero() { - return Integer.valueOf(0); - } - }; - assertTrue(versionComparator.compare("2.0.0", "2.0.0") == 0); - assertTrue(versionComparator.compare("2.0.0", "2.0.0.0") == 0); - assertTrue(versionComparator.compare("2.0.0.0", "2.0") == 0); - assertTrue(versionComparator.compare("2.0.-1", "2.0.-1") == 0); - } - - public void testVersionIsLess_subclass() { - Comparator<String> versionComparator = new VersionComparator<Integer>() { - @Override - protected Integer parseSegment(int index, String s) { - return Integer.valueOf(s); - } - @Override - protected Integer getZero() { - return Integer.valueOf(0); - } - }; - assertTrue(versionComparator.compare("2.0.0", "2.0.1") < 0); - assertTrue(versionComparator.compare("2.5.0", "2.14") < 0); - assertTrue(versionComparator.compare("2.5.0", "2.5.0.0.1.0") < 0); - assertTrue(versionComparator.compare("2.0.-1", "2.0.0") < 0); - assertTrue(versionComparator.compare("2.0.-1", "2") < 0); - } - - public void testVersionIsGreater_subclass() { - Comparator<String> versionComparator = new VersionComparator<Integer>() { - @Override - protected Integer parseSegment(int index, String s) { - return Integer.valueOf(s); - } - @Override - protected Integer getZero() { - return Integer.valueOf(0); - } - }; - assertTrue(versionComparator.compare("2.0.2", "2.0.1") > 0); - assertTrue(versionComparator.compare("2.0.2", "2.0.1") > 0); - assertTrue(versionComparator.compare("2.5.0.0.1.0", "2.5.0") > 0); - assertTrue(versionComparator.compare("2.0.0", "2.0.-1") > 0); - assertTrue(versionComparator.compare("2", "2.0.-1") > 0); - } - - public void testBadString() { - boolean exCaught = false; - try { - // note the letter 'O' instead of the numeral '0' - assertTrue(VersionComparator.INTEGER_VERSION_COMPARATOR.compare("2.0.0", "2.O.O") == 0); - } catch (NumberFormatException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testBogusSubclass1() { - Comparator<String> versionComparator = new VersionComparator<Integer>() { - // bogus - must override parseSegment(...) - @Override - protected Integer getZero() { - return Integer.valueOf(0); - } - }; - boolean exCaught = false; - try { - assertTrue(versionComparator.compare("2.0.0", "2.0.0") == 0); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testBogusSubclass2() { - Comparator<String> versionComparator = new VersionComparator<Integer>() { - @Override - protected Integer parseSegment(int index, String s) { - return Integer.valueOf(s); - } - // bogus - must getZero() - }; - boolean exCaught = false; - try { - assertTrue(versionComparator.compare("2.0.0", "2.0.0.0.0") == 0); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - static final class DecimalSegmentParser - implements SegmentParser<BigDecimal>, Serializable - { - public static final SegmentParser<BigDecimal> INSTANCE = new DecimalSegmentParser(); - public static SegmentParser<BigDecimal> instance() { - return INSTANCE; - } - // ensure single instance - private DecimalSegmentParser() { - super(); - } - // simply parse the segment as an integer - public BigDecimal parse(int segmentIndex, String segment) { - return new BigDecimal(segment); - } - public BigDecimal getZero() { - return ZERO; - } - private static final BigDecimal ZERO = new BigDecimal(0); - @Override - public String toString() { - return StringTools.buildSingletonToString(this); - } - private static final long serialVersionUID = 1L; - private Object readResolve() { - // replace this object with the singleton - return INSTANCE; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/XMLStringEncoderTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/XMLStringEncoderTests.java deleted file mode 100644 index 461313cb72..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/XMLStringEncoderTests.java +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.FileTools; -import org.eclipse.jpt.common.utility.internal.XMLStringEncoder; - -@SuppressWarnings("nls") -public class XMLStringEncoderTests extends TestCase { - - public XMLStringEncoderTests(String name) { - super(name); - } - - public void testEncodeNoCharacterSequences() { - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - - String s = "foo"; - assertEquals(s, encoder.encode(s)); - - s = "123foo123"; - assertEquals(s, encoder.encode(s)); - } - - public void testEncodeCharacterSequences() { - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - - String s = "?foo?"; - String expected = "?foo?"; - assertEquals(expected, encoder.encode(s)); - - s = "?foo&123"; - expected = "?foo&123"; - assertEquals(expected, encoder.encode(s)); - } - - public void testDenormalizeValidFileName() { - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - - String s = "foo"; - assertEquals(s, encoder.decode(s)); - - s = "123foo123"; - assertEquals(s, encoder.decode(s)); - } - - public void testDenormalizeInvalidFileName() { - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - - String s = "?foo?"; - String expected = "?foo?"; - assertEquals(expected, encoder.decode(s)); - - s = "?foo&123"; - expected = "?foo&123"; - assertEquals(expected, encoder.decode(s)); - } - - public void testRoundTripNoCharacterSequences() { - this.verifyRoundTrip("foo"); - this.verifyRoundTrip("123foo456"); - } - - public void testRoundTripCharacterSequences() { - this.verifyRoundTrip("?foo?"); - this.verifyRoundTrip("?foo&123&&&&&&>>>>"); - } - - private void verifyRoundTrip(String s) { - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - String actual = encoder.encode(s); - assertEquals(s, encoder.decode(actual)); - } - - public void testInvalidCharacterSequence1() { - this.verifyIllegalStateException("foo&"); - } - - public void testInvalidCharacterSequence2() { - this.verifyIllegalStateException("foo&#"); - } - - public void testInvalidCharacterSequence3() { - this.verifyIllegalStateException("foo&#x"); - } - - public void testInvalidCharacterSequence4() { - this.verifyIllegalStateException("foo"); - } - - public void testInvalidCharacterSequence5() { - this.verifyIllegalStateException("foo&#x;"); - } - - public void testInvalidCharacterSequence6() { - this.verifyIllegalStateException("foo&A"); - } - - public void testInvalidCharacterSequence7() { - this.verifyIllegalStateException("foo&#A"); - } - - private void verifyIllegalStateException(String s) { - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - boolean exCaught = false; - try { - s = encoder.decode(s); - fail(s); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testInvalidCharacterSequence8() { - String s = "foo&#xZZZZ;"; - XMLStringEncoder encoder = new XMLStringEncoder(FileTools.INVALID_FILENAME_CHARACTERS); - boolean exCaught = false; - try { - s = encoder.decode(s); - fail(s); - } catch (NumberFormatException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/AsynchronousCommandExecutorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/AsynchronousCommandExecutorTests.java deleted file mode 100644 index 767882fbd9..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/AsynchronousCommandExecutorTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import org.eclipse.jpt.common.utility.ExceptionHandler; -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.command.StatefulCommandExecutor; -import org.eclipse.jpt.common.utility.internal.command.AsynchronousExtendedCommandExecutor; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; - -public class AsynchronousCommandExecutorTests - extends MultiThreadedTestCase -{ - public AsynchronousCommandExecutorTests(String name) { - super(name); - } - - public void testExecution() throws Exception { - TestCommand command = new TestCommand(); - AsynchronousExtendedCommandExecutor.SimpleConfig config = new AsynchronousExtendedCommandExecutor.SimpleConfig(); - config.setThreadFactory(this.buildThreadFactory()); - config.setExceptionHandler(ExceptionHandler.Runtime.instance()); - StatefulCommandExecutor commandExecutor = new AsynchronousExtendedCommandExecutor(config); - commandExecutor.start(); - commandExecutor.execute(command); - commandExecutor.execute(command); - commandExecutor.execute(command); - Thread.sleep(TWO_TICKS); // wait for the command to execute - commandExecutor.stop(); - assertEquals(3, command.count); - } - - static class TestCommand implements Command { - int count = 0; - public void execute() { - this.count++; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/AsynchronousRepeatingCommandWrapperTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/AsynchronousRepeatingCommandWrapperTests.java deleted file mode 100644 index 975cf6aff4..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/AsynchronousRepeatingCommandWrapperTests.java +++ /dev/null @@ -1,445 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import org.eclipse.jpt.common.utility.ExceptionHandler; -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.command.RepeatingCommand; -import org.eclipse.jpt.common.utility.internal.CollectingExceptionHandler; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ConsumerThreadCoordinator; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.command.AsynchronousRepeatingCommandWrapper; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; - -@SuppressWarnings("nls") -public class AsynchronousRepeatingCommandWrapperTests - extends MultiThreadedTestCase -{ - PrimaryModel1 primaryModel1; - SecondaryModel1 secondaryModel1; - Command command1; - RepeatingCommand repeatingCommand1; - - PrimaryModel2 primaryModel2; - SecondaryModel2 secondaryModel2; - Command command2; - RepeatingCommand repeatingCommand2; - - public AsynchronousRepeatingCommandWrapperTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.primaryModel1 = new PrimaryModel1(); - this.secondaryModel1 = new SecondaryModel1(this.primaryModel1); - this.command1 = new SynchronizeSecondaryModelCommand1(this.secondaryModel1); - this.repeatingCommand1 = new AsynchronousRepeatingCommandWrapper(this.command1, this.buildThreadFactory(), null, ExceptionHandler.Runtime.instance()); - this.primaryModel1.setSynchronizer(this.repeatingCommand1); - - this.primaryModel2 = new PrimaryModel2(); - this.secondaryModel2 = new SecondaryModel2(this.primaryModel2); - this.command2 = new SynchronizeSecondaryModelCommand2(this.primaryModel2, this.secondaryModel2); - this.repeatingCommand2 = new AsynchronousRepeatingCommandWrapper(this.command2, this.buildThreadFactory(), null, ExceptionHandler.Runtime.instance()); - this.primaryModel2.setSynchronizer(this.repeatingCommand2); - } - - @Override - protected void tearDown() throws Exception { - this.repeatingCommand1.stop(); - this.repeatingCommand2.stop(); - super.tearDown(); - } - - public void testInitialization() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - } - - public void testToString() { - assertNotNull(this.repeatingCommand1.toString()); - } - - public void testChange() throws Exception { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.setCount(7); - - this.sleep(TICK); - this.repeatingCommand1.stop(); - this.sleep(TICK); - - assertEquals(14, this.secondaryModel1.getDoubleCount()); - - // re-start so tear-down works - this.repeatingCommand1.start(); - } - - public void testStart() throws Exception { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.setSynchronizer(RepeatingCommand.Null.instance()); - this.primaryModel1.setCount(7); - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.setSynchronizer(this.repeatingCommand1); - // the async synchronizer does not synchronize at start-up - assertEquals(4, this.secondaryModel1.getDoubleCount()); - - this.primaryModel1.setCount(8); - - this.sleep(TICK); - this.repeatingCommand1.stop(); - this.sleep(TICK); - - assertEquals(16, this.secondaryModel1.getDoubleCount()); - - // re-start so tear-down works - this.repeatingCommand1.start(); - } - - public void testStop() throws Exception { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.dispose(); - this.primaryModel1.setCount(7); - assertEquals(4, this.secondaryModel1.getDoubleCount()); - - // re-start so tear-down works - this.repeatingCommand1.start(); - } - - public void testDoubleStart() throws Exception { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - boolean exCaught = false; - try { - this.primaryModel1.startSynchronizer(); - fail(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - this.primaryModel1.setCount(7); - - this.sleep(TICK); - this.repeatingCommand1.stop(); - this.sleep(TICK); - - assertEquals(14, this.secondaryModel1.getDoubleCount()); - - // re-start so tear-down works - this.repeatingCommand1.start(); - } - - public void testDoubleStop() throws Exception { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.dispose(); - boolean exCaught = false; - try { - this.primaryModel1.dispose(); - fail(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - this.primaryModel1.setCount(7); - assertEquals(4, this.secondaryModel1.getDoubleCount()); - - // re-start so tear-down works - this.repeatingCommand1.start(); - } - - public void testRecursiveChange() throws Exception { - assertEquals(4, this.secondaryModel2.getDoubleCount()); - this.primaryModel2.setCount(7); - - this.sleep(TICK); - assertEquals(10, this.primaryModel2.getCountPlus3()); - assertEquals(14, this.secondaryModel2.getDoubleCount()); - - this.sleep(TICK); - assertEquals(20, this.secondaryModel2.getDoubleCountPlus3()); - } - - public void testNullCommand() { - boolean exCaught = false; - try { - RepeatingCommand s = new AsynchronousRepeatingCommandWrapper(null, this.buildThreadFactory(), null, ExceptionHandler.Runtime.instance()); - fail("bogus: " + s); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testThreadName() throws Exception { - RepeatingCommand s = new AsynchronousRepeatingCommandWrapper(this.command1, this.buildThreadFactory(), "sync", ExceptionHandler.Runtime.instance()); - s.start(); - ConsumerThreadCoordinator ctc = (ConsumerThreadCoordinator) ReflectionTools.getFieldValue(s, "consumerThreadCoordinator"); - Thread t = (Thread) ReflectionTools.getFieldValue(ctc, "thread"); - assertEquals("sync", t.getName()); - s.stop(); - } - - public void testExecuteCalledBeforeStart() throws Exception { - SimpleCommand command = new SimpleCommand(); - RepeatingCommand synchronizer = new AsynchronousRepeatingCommandWrapper(command, this.buildThreadFactory(), null, ExceptionHandler.Runtime.instance()); - - synchronizer.execute(); - synchronizer.start(); - this.sleep(TICK); - synchronizer.stop(); - assertEquals(1, command.count); - } - - public class SimpleCommand implements Command { - int count = 0; - public void execute() { - this.count++; - } - } - - public void testException() throws Exception { - BogusCommand command = new BogusCommand(); - CollectingExceptionHandler exHandler = new CollectingExceptionHandler(); - RepeatingCommand synchronizer = new AsynchronousRepeatingCommandWrapper(command, this.buildThreadFactory(), null, exHandler); - synchronizer.start(); - - synchronizer.execute(); - this.sleep(TICK); - - synchronizer.execute(); - this.sleep(TICK); - - synchronizer.stop(); - assertEquals(2, CollectionTools.size(exHandler.getExceptions())); - assertEquals(2, command.count); - } - - public class BogusCommand implements Command { - int count = 0; - public void execute() { - this.count++; - throw new NullPointerException(); - } - } - - - // ********** synchronize commands ********** - - public static class SynchronizeSecondaryModelCommand1 - implements Command - { - private final SecondaryModel1 secondaryModel; - - public SynchronizeSecondaryModelCommand1(SecondaryModel1 secondaryModel) { - super(); - this.secondaryModel = secondaryModel; - } - - public void execute() { - this.secondaryModel.synchronize(); - } - } - - /** - * the primary model (subclass) has to synchronize with itself (superclass) - */ - public static class SynchronizeSecondaryModelCommand2 - extends SynchronizeSecondaryModelCommand1 - { - private final PrimaryModel2 primaryModel; - - public SynchronizeSecondaryModelCommand2(PrimaryModel2 primaryModel, SecondaryModel2 secondaryModel) { - super(secondaryModel); - this.primaryModel = primaryModel; - } - - @Override - public void execute() { - super.execute(); - this.primaryModel.synchronize(); - } - } - - - // ********** primary models ********** - - /** - * this object will call the synchronizer whenever its count changes, - * allowing interested parties to synchronize with the change - */ - public static class PrimaryModel1 { - protected RepeatingCommand synchronizer; - protected int count = 2; - - public PrimaryModel1() { - super(); - this.setSynchronizer_(RepeatingCommand.Null.instance()); - } - - public int getCount() { - return this.count; - } - public void setCount(int count) { - if (count != this.count) { - this.count = count; - this.stateChanged(); - } - } - - protected void stateChanged() { - this.synchronizer.execute(); - } - - public void setSynchronizer(RepeatingCommand synchronizer) throws InterruptedException { - if (synchronizer == null) { - throw new NullPointerException(); - } - this.synchronizer.stop(); - this.setSynchronizer_(synchronizer); - } - - protected void setSynchronizer_(RepeatingCommand synchronizer) { - this.synchronizer = synchronizer; - this.synchronizer.start(); - } - - public void startSynchronizer() { - this.synchronizer.start(); // this should cause an exception - } - public void dispose() throws InterruptedException { - this.synchronizer.stop(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append('('); - this.toString(sb); - sb.append(')'); - return sb.toString(); - } - public void toString(StringBuilder sb) { - sb.append("count="); - sb.append(this.count); - } - } - - /** - * This model synchronizes with itself, triggering a recursive synchronization - * with the change. Whenever the [inherited] 'count' changes, 'countPlus3' - * is updated appropriately and another synchronize is initiated if appropriate. - */ - public static class PrimaryModel2 - extends PrimaryModel1 - { - private int countPlus3 = 0; - - public PrimaryModel2() { - super(); - this.countPlus3 = this.count + 3; - } - - public int getCountPlus3() { - return this.countPlus3; - } - protected void setCountPlus3(int countPlus3) { - if (countPlus3 != this.countPlus3) { - this.countPlus3 = countPlus3; - this.stateChanged(); - } - } - - // synchronize with itself, so to speak - public void synchronize() { - this.setCountPlus3(this.count + 3); - } - - @Override - public void toString(StringBuilder sb) { - super.toString(sb); - sb.append(", countPlus3="); - sb.append(this.countPlus3); - } - } - - - // ********** secondary models ********** - - /** - * This dependent object updates its 'doubleCount' whenever the - * PrimaryModel1's 'count' changes, via the 'synchronizer'. - */ - public static class SecondaryModel1 { - protected final PrimaryModel1 primaryModel; - protected int doubleCount = 0; - - public SecondaryModel1(PrimaryModel1 primaryModel) { - super(); - this.primaryModel = primaryModel; - this.synchronize(); - } - - public void synchronize() { - this.doubleCount = this.primaryModel.getCount() * 2; - } - - public int getDoubleCount() { - return this.doubleCount; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append('('); - this.toString(sb); - sb.append(')'); - return sb.toString(); - } - public void toString(StringBuilder sb) { - sb.append("doubleCount="); - sb.append(this.doubleCount); - } - } - - public static class SecondaryModel2 - extends SecondaryModel1 - { - private int doubleCountPlus3 = 0; - - public SecondaryModel2(PrimaryModel2 extendedPrimaryModel) { - super(extendedPrimaryModel); - } - - protected PrimaryModel2 getExtendedPrimaryModel() { - return (PrimaryModel2) this.primaryModel; - } - - @Override - public void synchronize() { - super.synchronize(); - int temp = this.getExtendedPrimaryModel().getCountPlus3() * 2; - if (this.doubleCountPlus3 != temp) { - this.doubleCountPlus3 = temp; - } - } - - public int getDoubleCountPlus3() { - return this.doubleCountPlus3; - } - - @Override - public void toString(StringBuilder sb) { - super.toString(sb); - sb.append(", doubleCountPlus3="); - sb.append(this.doubleCountPlus3); - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandExecutorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandExecutorTests.java deleted file mode 100644 index cb7d75ea1e..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandExecutorTests.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.command.CommandExecutor; -import org.eclipse.jpt.common.utility.command.ExtendedCommandExecutor; -import org.eclipse.jpt.common.utility.internal.command.ThreadLocalExtendedCommandExecutor; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class CommandExecutorTests - extends MultiThreadedTestCase -{ - - public CommandExecutorTests(String name) { - super(name); - } - - public void testDefaultCommandExecutor_toString() throws Exception { - CommandExecutor commandExecutor = CommandExecutor.Default.instance(); - assertNotNull(commandExecutor.toString()); - } - - public void testDefaultCommandExecutor_serialization() throws Exception { - CommandExecutor commandExecutor1 = CommandExecutor.Default.instance(); - CommandExecutor commandExecutor2 = TestTools.serialize(commandExecutor1); - assertSame(commandExecutor1, commandExecutor2); - } - - public void testDefaultCommandExecutor() { - TestCommand testCommand = new TestCommand(); - assertEquals(0, testCommand.count); - CommandExecutor commandExecutor = CommandExecutor.Default.instance(); - commandExecutor.execute(testCommand); - assertEquals(1, testCommand.count); - } - - static class TestCommand implements Command { - int count = 0; - public void execute() { - this.count++; - } - } - - public void testThreadLocalCommandExecutor_toString() throws Exception { - CommandExecutor commandExecutor = new ThreadLocalExtendedCommandExecutor(); - assertNotNull(commandExecutor.toString()); - } - - public void testThreadLocalCommandExecutor() throws Exception { - ThreadLocalExtendedCommandExecutor threadLocalCommandExecutor = new ThreadLocalExtendedCommandExecutor(); - TestRunnable testRunnable1 = new TestRunnable(threadLocalCommandExecutor, 1); - Thread thread1 = this.buildThread(testRunnable1); - thread1.run(); - - TestRunnable testRunnable2 = new TestRunnable(threadLocalCommandExecutor, 2); - Thread thread2 = this.buildThread(testRunnable2); - thread2.run(); - - TestRunnable testRunnable3 = new TestRunnable(threadLocalCommandExecutor, 3, null); - Thread thread3 = this.buildThread(testRunnable3); - thread3.run(); - - thread1.join(); - thread2.join(); - thread3.join(); - - assertEquals(1, testRunnable1.testCommand.count); - assertEquals(1, testRunnable1.testCommandExecutor.count); - - assertEquals(2, testRunnable2.testCommand.count); - assertEquals(2, testRunnable2.testCommandExecutor.count); - - assertEquals(3, testRunnable3.testCommand.count); - assertNull(testRunnable3.testCommandExecutor); - } - - static class TestCommandExecutor implements ExtendedCommandExecutor { - int count = 0; - public void execute(Command command) { - this.count++; - command.execute(); - } - public void waitToExecute(Command command) { - this.execute(command); - } - public boolean waitToExecute(Command command, long timeout) { - this.execute(command); - return true; - } - } - - static class TestRunnable implements Runnable { - final ThreadLocalExtendedCommandExecutor threadLocalCommandExecutor; - final int executionCount; - final TestCommand testCommand = new TestCommand(); - final TestCommandExecutor testCommandExecutor; - TestRunnable(ThreadLocalExtendedCommandExecutor threadLocalCommandExecutor, int executionCount) { - this(threadLocalCommandExecutor, executionCount, new TestCommandExecutor()); - } - TestRunnable(ThreadLocalExtendedCommandExecutor threadLocalCommandExecutor, int executionCount, TestCommandExecutor testCommandExecutor) { - super(); - this.threadLocalCommandExecutor = threadLocalCommandExecutor; - this.executionCount = executionCount; - this.testCommandExecutor = testCommandExecutor; - } - public void run() { - this.threadLocalCommandExecutor.set(this.testCommandExecutor); - for (int i = 0; i < this.executionCount; i++) { - this.threadLocalCommandExecutor.execute(this.testCommand); - } - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandRunnableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandRunnableTests.java deleted file mode 100644 index d5dce4e56c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandRunnableTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.internal.command.CommandRunnable; - -@SuppressWarnings("nls") -public class CommandRunnableTests extends TestCase { - boolean commandExecuted = false; - - public CommandRunnableTests(String name) { - super(name); - } - - public void testNullCommand() { - boolean exCaught = false; - try { - Runnable runnable = new CommandRunnable(null); - fail("bogus: " + runnable); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRun() { - Runnable runnable = new CommandRunnable(this.buildCommand()); - runnable.run(); - assertTrue(this.commandExecuted); - } - - public void testToString() { - Runnable runnable = new CommandRunnable(this.buildCommand()); - assertNotNull(runnable.toString()); - } - - private Command buildCommand() { - return new Command() { - public void execute() { - CommandRunnableTests.this.commandExecuted = true; - } - }; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandTests.java deleted file mode 100644 index 266a0101e4..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CommandTests.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.command.CommandExecutor; -import org.eclipse.jpt.common.utility.internal.command.CommandRunnable; -import org.eclipse.jpt.common.utility.internal.command.RunnableCommand; -import org.eclipse.jpt.common.utility.internal.command.ThreadLocalCommand; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class CommandTests - extends MultiThreadedTestCase -{ - public CommandTests(String name) { - super(name); - } - - public void testNullCommand() { - Command command = Command.Null.instance(); - command.execute(); // just make sure it doesn't blow up? - } - - public void testNullCommand_toString() { - Command command = Command.Null.instance(); - assertNotNull(command.toString()); - } - - public void testNullCommand_serialization() throws Exception { - Command command1 = Command.Null.instance(); - Command command2 = TestTools.serialize(command1); - assertSame(command1, command2); - } - - public void testDisabledCommand() { - Command command = Command.Disabled.instance(); - boolean exCaught = false; - try { - command.execute(); - fail(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testDisabledCommand_toString() { - Command command = Command.Disabled.instance(); - assertNotNull(command.toString()); - } - - public void testDisabledCommand_serialization() throws Exception { - Command command1 = Command.Disabled.instance(); - Command command2 = TestTools.serialize(command1); - assertSame(command1, command2); - } - - public void testRunnableCommand() { - SimpleTestRunnable testRunnable = new SimpleTestRunnable(); - assertFalse(testRunnable.ran); - Command command = new RunnableCommand(testRunnable); - command.execute(); - assertTrue(testRunnable.ran); - } - - static class SimpleTestRunnable implements Runnable { - boolean ran = false; - public void run() { - this.ran = true; - } - } - - public void testCommandRunnable() { - TestCommand testCommand = new TestCommand(); - assertEquals(0, testCommand.count); - Runnable runnable = new CommandRunnable(testCommand); - runnable.run(); - assertEquals(1, testCommand.count); - } - - static class TestCommand implements Command { - int count = 0; - public void execute() { - this.count++; - } - } - - public void testThreadLocalCommand() throws Exception { - ThreadLocalCommand threadLocalCommand = new ThreadLocalCommand(); - TestRunnable testRunnable1 = new TestRunnable(threadLocalCommand, 1); - Thread thread1 = this.buildThread(testRunnable1); - thread1.run(); - - TestRunnable testRunnable2 = new TestRunnable(threadLocalCommand, 2); - Thread thread2 = this.buildThread(testRunnable2); - thread2.run(); - - thread1.join(); - thread2.join(); - - assertEquals(1, testRunnable1.testCommand.count); - - assertEquals(2, testRunnable2.testCommand.count); - } - - static class TestCommandExecutor implements CommandExecutor { - int count = 0; - public void execute(Command command) { - this.count++; - command.execute(); - } - } - - static class TestRunnable implements Runnable { - final ThreadLocalCommand threadLocalCommand; - final int executionCount; - final TestCommand testCommand = new TestCommand(); - TestRunnable(ThreadLocalCommand threadLocalCommand, int executionCount) { - super(); - this.threadLocalCommand = threadLocalCommand; - this.executionCount = executionCount; - } - public void run() { - this.threadLocalCommand.set(this.testCommand); - for (int i = 0; i < this.executionCount; i++) { - this.threadLocalCommand.execute(); - } - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CompositeCommandTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CompositeCommandTests.java deleted file mode 100644 index 69aa1f8c8d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/CompositeCommandTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.internal.command.CommandRunnable; -import org.eclipse.jpt.common.utility.internal.command.CompositeCommand; - -public class CompositeCommandTests extends TestCase { - boolean command1Executed = false; - boolean command2Executed = false; - - public CompositeCommandTests(String name) { - super(name); - } - - public void testRun() { - Runnable runnable = new CommandRunnable(this.buildCompositeCommand()); - runnable.run(); - assertTrue(this.command1Executed); - assertTrue(this.command2Executed); - } - - public void testToString() { - Runnable runnable = new CommandRunnable(this.buildCompositeCommand()); - assertNotNull(runnable.toString()); - } - - private Command buildCompositeCommand() { - return new CompositeCommand( - this.buildCommand1(), - this.buildCommand2() - ); - } - - private Command buildCommand1() { - return new Command() { - public void execute() { - CompositeCommandTests.this.command1Executed = true; - } - }; - } - - private Command buildCommand2() { - return new Command() { - public void execute() { - CompositeCommandTests.this.command2Executed = true; - } - }; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/JptUtilityCommandTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/JptUtilityCommandTests.java deleted file mode 100644 index 6d40c97327..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/command/JptUtilityCommandTests.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.command; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * decentralize test creation code - */ -public class JptUtilityCommandTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityCommandTests.class.getPackage().getName()); - - suite.addTestSuite(AsynchronousCommandExecutorTests.class); - suite.addTestSuite(AsynchronousRepeatingCommandWrapperTests.class); - suite.addTestSuite(CommandExecutorTests.class); - suite.addTestSuite(CommandRunnableTests.class); - suite.addTestSuite(CommandTests.class); - suite.addTestSuite(CompositeCommandTests.class); - - return suite; - } - - private JptUtilityCommandTests() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/EmptyEnumerationTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/EmptyEnumerationTests.java deleted file mode 100644 index 1efc9c81bb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/EmptyEnumerationTests.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.enumerations; - -import java.util.Enumeration; -import java.util.NoSuchElementException; -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.enumerations.EmptyEnumeration; - -@SuppressWarnings("nls") -public class EmptyEnumerationTests extends TestCase { - - public EmptyEnumerationTests(String name) { - super(name); - } - - public void testHasMoreElements() { - int i = 0; - for (Enumeration<Object> stream = EmptyEnumeration.instance(); stream.hasMoreElements();) { - stream.nextElement(); - i++; - } - assertEquals(0, i); - } - - public void testNextElement() { - for (Enumeration<Object> stream = EmptyEnumeration.instance(); stream.hasMoreElements();) { - fail("bogus element: " + stream.nextElement()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Enumeration<Object> stream = EmptyEnumeration.instance(); - Object element = null; - while (stream.hasMoreElements()) { - element = stream.nextElement(); - } - try { - element = stream.nextElement(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + element, exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/IteratorEnumerationTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/IteratorEnumerationTests.java deleted file mode 100644 index cd6cbaa8af..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/IteratorEnumerationTests.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.enumerations; - -import java.util.Enumeration; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Vector; -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.enumerations.IteratorEnumeration; - -@SuppressWarnings("nls") -public class IteratorEnumerationTests extends TestCase { - - public IteratorEnumerationTests(String name) { - super(name); - } - - public void testHasMoreElements() { - int i = 0; - for (Enumeration<String> stream = this.buildEnumeration(); stream.hasMoreElements();) { - stream.nextElement(); - i++; - } - assertEquals(this.buildVector().size(), i); - } - - public void testHasMoreElementsUpcast() { - int i = 0; - for (Enumeration<Object> stream = this.buildEnumerationUpcast(); stream.hasMoreElements();) { - stream.nextElement(); - i++; - } - assertEquals(this.buildVector().size(), i); - } - - public void testNextElement() { - Iterator<String> iterator = this.buildIterator(); - for (Enumeration<String> stream = this.buildEnumeration(); stream.hasMoreElements();) { - assertEquals("bogus element", iterator.next(), stream.nextElement()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Enumeration<String> stream = this.buildEnumeration(); - String string = null; - while (stream.hasMoreElements()) { - string = stream.nextElement(); - } - try { - string = stream.nextElement(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - private Enumeration<String> buildEnumeration() { - return this.buildEnumeration(this.buildIterator()); - } - - private Enumeration<Object> buildEnumerationUpcast() { - return this.buildEnumerationUpcast(this.buildIterator()); - } - - private Enumeration<String> buildEnumeration(Iterator<String> iterator) { - return new IteratorEnumeration<String>(iterator); - } - - private Enumeration<Object> buildEnumerationUpcast(Iterator<String> iterator) { - return new IteratorEnumeration<Object>(iterator); - } - - private Iterator<String> buildIterator() { - return this.buildVector().iterator(); - } - - private Vector<String> buildVector() { - Vector<String> v = new Vector<String>(); - v.addElement("one"); - v.addElement("two"); - v.addElement("three"); - v.addElement("four"); - v.addElement("five"); - v.addElement("six"); - v.addElement("seven"); - v.addElement("eight"); - return v; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/JptUtilityEnumerationsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/JptUtilityEnumerationsTests.java deleted file mode 100644 index d5dfb0f0a8..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/enumerations/JptUtilityEnumerationsTests.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.enumerations; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * decentralize test creation code - */ -public class JptUtilityEnumerationsTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityEnumerationsTests.class.getPackage().getName()); - - suite.addTestSuite(EmptyEnumerationTests.class); - suite.addTestSuite(IteratorEnumerationTests.class); - - return suite; - } - - private JptUtilityEnumerationsTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ArrayIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ArrayIterableTests.java deleted file mode 100644 index 0c6e2da5a2..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ArrayIterableTests.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ArrayIterable; - -@SuppressWarnings("nls") -public class ArrayIterableTests extends TestCase { - - public ArrayIterableTests(String name) { - super(name); - } - - public void testIterator() { - int i = 1; - for (String string : this.buildIterable()) { - assertEquals(i++, Integer.parseInt(string)); - } - } - - public void testSubIterator() { - int i = 3; - for (String string : this.buildIterable(2)) { - assertEquals(i++, Integer.parseInt(string)); - } - } - - public void testIllegalArgumentException() { - this.triggerIllegalArgumentException(-1, 1); - this.triggerIllegalArgumentException(8, 1); - this.triggerIllegalArgumentException(0, -1); - this.triggerIllegalArgumentException(0, 9); - } - - private void triggerIllegalArgumentException(int start, int length) { - boolean exCaught = false; - try { - Iterable<String> iterable = this.buildIterable(start, length); - fail("bogus iterable: " + iterable); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private Iterable<String> buildIterable() { - return this.buildIterable(0); - } - - private Iterable<String> buildIterable(int start) { - return this.buildIterable(this.buildArray(), start); - } - - private Iterable<String> buildIterable(String[] array, int start) { - return new ArrayIterable<String>(array, start); - } - - private Iterable<String> buildIterable(int start, int length) { - return this.buildIterable(this.buildArray(), start, length); - } - - private Iterable<String> buildIterable(String[] array, int start, int length) { - return new ArrayIterable<String>(array, start, length); - } - - private String[] buildArray() { - return new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ArrayListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ArrayListIterableTests.java deleted file mode 100644 index f7cd40fcb8..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ArrayListIterableTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ListIterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ArrayListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ListIterable; - -@SuppressWarnings("nls") -public class ArrayListIterableTests extends TestCase { - - public ArrayListIterableTests(String name) { - super(name); - } - - public void testIterator() { - int i = 1; - ListIterable<String> iterable = this.buildIterable(); - for (String string : iterable) { - assertEquals(i++, Integer.parseInt(string)); - } - ListIterator<String> stream = iterable.iterator(); - while (stream.hasNext()) { - stream.next(); - } - while (stream.hasPrevious()) { - assertEquals(--i, Integer.parseInt(stream.previous())); - } - } - - public void testSubIterator() { - int i = 3; - for (String string : this.buildIterable(2)) { - assertEquals(i++, Integer.parseInt(string)); - } - } - - public void testIllegalArgumentException() { - this.triggerIllegalArgumentException(-1, 1); - this.triggerIllegalArgumentException(8, 1); - this.triggerIllegalArgumentException(0, -1); - this.triggerIllegalArgumentException(0, 9); - } - - private void triggerIllegalArgumentException(int start, int length) { - boolean exCaught = false; - try { - Iterable<String> iterable = this.buildIterable(start, length); - fail("bogus iterable: " + iterable); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private ListIterable<String> buildIterable() { - return this.buildIterable(0); - } - - private ListIterable<String> buildIterable(int start) { - return this.buildIterable(this.buildArray(), start); - } - - private ListIterable<String> buildIterable(String[] array, int start) { - return (start == 0) ? - new ArrayListIterable<String>(array) : - new ArrayListIterable<String>(array, start); - } - - private ListIterable<String> buildIterable(int start, int length) { - return this.buildIterable(this.buildArray(), start, length); - } - - private ListIterable<String> buildIterable(String[] array, int start, int length) { - return new ArrayListIterable<String>(array, start, length); - } - - private String[] buildArray() { - return new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ChainIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ChainIterableTests.java deleted file mode 100644 index ae8423bfd5..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ChainIterableTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.AbstractCollection; -import java.util.AbstractList; -import java.util.Iterator; -import java.util.Vector; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ChainIterable; -import org.eclipse.jpt.common.utility.internal.iterators.ChainIterator; - -@SuppressWarnings("nls") -public class ChainIterableTests extends TestCase { - private final static Class<?>[] VECTOR_HIERARCHY = { Vector.class, AbstractList.class, AbstractCollection.class, Object.class }; - - public ChainIterableTests(String name) { - super(name); - } - - - public void testNextLink() { - int i = 0; - for (Class<?> clazz : this.buildIterable()) { - assertEquals(VECTOR_HIERARCHY[i++], clazz); - } - } - - public void testLinker() { - int i = 0; - for (Class<?> clazz : new ChainIterable<Class<?>>(Vector.class, this.buildLinker())) { - assertEquals(VECTOR_HIERARCHY[i++], clazz); - } - } - - public void testException() { - Iterable<Class<?>> iterable = new ChainIterable<Class<?>>(Vector.class); - Iterator<Class<?>> iterator = iterable.iterator(); - boolean exCaught = false; - try { - Class<?> clazz = iterator.next(); - fail("bogus class: " + clazz); - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testToString() { - assertNotNull(this.buildIterable().toString()); - } - - private Iterable<Class<?>> buildIterable() { - return this.buildChainIterable(Vector.class); - } - - private Iterable<Class<?>> buildChainIterable(Class<?> startLink) { - // chain up the class's hierarchy - return new ChainIterable<Class<?>>(startLink) { - @Override - protected Class<?> nextLink(Class<?> currentLink) { - return currentLink.getSuperclass(); - } - }; - } - - private ChainIterator.Linker<Class<?>> buildLinker() { - return new ChainIterator.Linker<Class<?>>() { - public Class<?> nextLink(Class<?> currentLink) { - return currentLink.getSuperclass(); - } - }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CloneIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CloneIterableTests.java deleted file mode 100644 index 03292ec25d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CloneIterableTests.java +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.CloneIterator; -import org.eclipse.jpt.common.utility.internal.iterators.CloneListIterator; - -@SuppressWarnings("nls") -public abstract class CloneIterableTests extends TestCase { - Iterable<String> iterable; - - public CloneIterableTests(String name) { - super(name); - } - - public void testIterator() { - List<String> c = new ArrayList<String>(); - c.add("0"); - c.add("1"); - c.add("2"); - c.add("3"); - assertEquals(4, c.size()); - this.iterable = this.buildIterable(c); - int i = 0; - for (String s : this.iterable) { - assertEquals(String.valueOf(i++), s); - c.remove("3"); - } - assertEquals(4, i); - assertEquals(3, c.size()); - } - - public void testRemove() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildRemovingIterable(collection); - - Object removed = "three"; - assertTrue(CollectionTools.contains(this.iterable, removed)); - for (Iterator<String> iterator = this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals(removed)) { - iterator.remove(); - } - } - assertFalse(collection.contains(removed)); - } - - public void testRemover() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterableWithRemover(collection); - - Object removed = "three"; - assertTrue(CollectionTools.contains(this.iterable, removed)); - for (Iterator<String> iterator = this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals(removed)) { - iterator.remove(); - } - } - assertFalse(collection.contains(removed)); - } - - public void testMissingRemover() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterable(collection); - assertNotNull(this.iterable.toString()); - - Object removed = "three"; - assertTrue(CollectionTools.contains(this.iterable, removed)); - boolean exCaught = false; - for (Iterator<String> iterator = this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals(removed)) { - try { - iterator.remove(); - fail(); - } catch (RuntimeException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - public void testToString() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterable(collection); - assertNotNull(iterable.toString()); - } - - abstract Iterable<String> buildIterable(List<String> c); - - abstract Iterable<String> buildRemovingIterable(List<String> c); - - abstract Iterable<String> buildIterableWithRemover(List<String> c); - - CloneIterator.Remover<String> buildRemover(final Collection<String> c) { - return new CloneIterator.Remover<String>() { - public void remove(String current) { - c.remove(current); - } - }; - } - - CloneListIterator.Mutator<String> buildMutator(final List<String> list) { - return new CloneListIterator.Mutator<String>() { - public void add(int index, String string) { - list.add(index, string); - } - public void set(int index, String string) { - list.set(index, string); - } - public void remove(int index) { - list.remove(index); - } - }; - } - - List<String> buildCollection() { - List<String> c = new ArrayList<String>(); - c.add("one"); - c.add("two"); - c.add("three"); - c.add("four"); - c.add("five"); - c.add("six"); - c.add("seven"); - c.add("eight"); - return c; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CompositeIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CompositeIterableTests.java deleted file mode 100644 index bd5516f161..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CompositeIterableTests.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.CompositeIterable; - -@SuppressWarnings("nls") -public class CompositeIterableTests extends TestCase { - - public CompositeIterableTests(String name) { - super(name); - } - - public void testIterator() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Collection<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - - @SuppressWarnings("unchecked") - Iterable<String> composite = new CompositeIterable<String>(c1, c2); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testExtraElement1() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Iterable<String> composite = new CompositeIterable<String>(c1, "4"); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testExtraElement2() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Iterable<String> composite = new CompositeIterable<String>("0", c1); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testCollectionOfIterables() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Collection<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - - Collection<Iterable<String>> collection = new ArrayList<Iterable<String>>(); - collection.add(c1); - collection.add(c2); - Iterable<String> composite = new CompositeIterable<String>(collection); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testToString() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Collection<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - - @SuppressWarnings("unchecked") - Iterable<String> composite = new CompositeIterable<String>(c1, c2); - assertNotNull(composite.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CompositeListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CompositeListIterableTests.java deleted file mode 100644 index baf06cf3fb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/CompositeListIterableTests.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.CompositeListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ListListIterable; - -@SuppressWarnings("nls") -public class CompositeListIterableTests extends TestCase { - - public CompositeListIterableTests(String name) { - super(name); - } - - public void testIterator() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - List<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - - @SuppressWarnings("unchecked") - Iterable<String> composite = new CompositeListIterable<String>(c1, c2); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testExtraElement1() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Iterable<String> composite = new CompositeListIterable<String>(c1, "4"); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testExtraElement2() { - List<String> c1 = new ArrayList<String>(); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - Iterable<String> composite = new CompositeListIterable<String>("0", c1); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testCollectionOfIterables() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - List<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - - List<ListIterable<String>> collection = new ArrayList<ListIterable<String>>(); - collection.add(new ListListIterable<String>(c1)); - collection.add(new ListListIterable<String>(c2)); - Iterable<String> composite = new CompositeListIterable<String>(collection); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testToString() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - - List<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - - @SuppressWarnings("unchecked") - Iterable<String> composite = new CompositeListIterable<String>(c1, c2); - assertNotNull(composite.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/EmptyIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/EmptyIterableTests.java deleted file mode 100644 index 1afe2303eb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/EmptyIterableTests.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.EmptyIterable; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class EmptyIterableTests extends TestCase { - - public EmptyIterableTests(String name) { - super(name); - } - - public void testIterator() { - for (String s : EmptyIterable.<String>instance()) { - fail("bogus element: " + s); - } - } - - public void testToString() { - assertNotNull(EmptyIterable.instance().toString()); - } - - public void testSerialization() throws Exception { - Iterable<String> iterable = EmptyIterable.instance(); - assertSame(iterable, TestTools.serialize(iterable)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/EmptyListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/EmptyListIterableTests.java deleted file mode 100644 index 761555cbbe..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/EmptyListIterableTests.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.EmptyListIterable; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class EmptyListIterableTests extends TestCase { - - public EmptyListIterableTests(String name) { - super(name); - } - - public void testIterator() { - for (String s : EmptyListIterable.<String>instance()) { - fail("bogus element: " + s); - } - } - - public void testToString() { - assertNotNull(EmptyListIterable.instance().toString()); - } - - public void testSerialization() throws Exception { - Iterable<String> iterable = EmptyListIterable.instance(); - assertSame(iterable, TestTools.serialize(iterable)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/FilteringIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/FilteringIterableTests.java deleted file mode 100644 index fa1b5613f3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/FilteringIterableTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.Filter; -import org.eclipse.jpt.common.utility.internal.iterables.FilteringIterable; - -@SuppressWarnings("nls") -public class FilteringIterableTests extends TestCase { - private static final String PREFIX = "prefix"; - - public FilteringIterableTests(String name) { - super(name); - } - - public void testAccept() { - int i = 0; - for (String s : this.buildIterable()) { - assertTrue(s.contains(PREFIX)); - i++; - } - assertEquals(6, i); - } - - public void testFilter() { - Filter<String> filter = this.buildFilter(); - int i = 0; - for (String s : new FilteringIterable<String>(this.buildNestedIterable(), filter)) { - assertTrue(s.contains(PREFIX)); - i++; - } - assertEquals(6, i); - } - - public void testToString() { - assertNotNull(this.buildIterable().toString()); - } - - public void testMissingFilter() { - boolean exCaught = false; - Iterable<String> iterable = new FilteringIterable<String>(this.buildNestedIterable()); - try { - Iterator<String> iterator = iterable.iterator(); - fail("bogus iterator: " + iterator); - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private Iterable<String> buildIterable() { - return this.buildFilteringIterable(this.buildNestedIterable()); - } - - private Iterable<String> buildFilteringIterable(Iterable<String> nestedIterable) { - return new FilteringIterable<String>(nestedIterable) { - @Override - protected boolean accept(String s) { - return s.startsWith(PREFIX); - } - }; - } - - private Filter<String> buildFilter() { - return new Filter<String>() { - public boolean accept(String s) { - return s.startsWith(PREFIX); - } - }; - } - - private Iterable<String> buildNestedIterable() { - Collection<String> c = new ArrayList<String>(); - c.add(PREFIX + "1"); - c.add(PREFIX + "2"); - c.add(PREFIX + "3"); - c.add("4"); - c.add(PREFIX + "5"); - c.add(PREFIX + "6"); - c.add(PREFIX + "7"); - c.add("8"); - return c; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/GraphIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/GraphIterableTests.java deleted file mode 100644 index bb39c41b85..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/GraphIterableTests.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterables.GraphIterable; -import org.eclipse.jpt.common.utility.internal.iterators.GraphIterator; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class GraphIterableTests extends TestCase { - /** this will be populated with all the nodes created for the test */ - Collection<GraphNode> nodes = new ArrayList<GraphNode>(); - - public GraphIterableTests(String name) { - super(name); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testNeighbors1() { - for (GraphNode gn : this.buildGraphIterable1()) { - assertTrue(this.nodes.contains(gn)); - } - } - - private Iterable<GraphNode> buildGraphIterable1() { - return new GraphIterable<GraphNode>(this.buildGraphRoot()) { - @Override - public Iterator<GraphNode> neighbors(GraphNode next) { - return next.neighbors(); - } - }; - } - - public void testNeighbors2() { - for (GraphNode gn : this.buildGraphIterable2()) { - assertTrue(this.nodes.contains(gn)); - } - } - - private Iterable<GraphNode> buildGraphIterable2() { - return new GraphIterable<GraphNode>(this.buildGraphRoot(), this.buildMisterRogers()); - } - - public void testNeighbors3() { - for (GraphNode gn : this.buildGraphIterable3()) { - assertTrue(this.nodes.contains(gn)); - } - } - - private Iterable<GraphNode> buildGraphIterable3() { - return new GraphIterable<GraphNode>(new GraphNode[] { this.buildGraphRoot() }) { - @Override - public Iterator<GraphNode> neighbors(GraphNode next) { - return next.neighbors(); - } - }; - } - - public void testNeighbors4() { - for (GraphNode gn : this.buildGraphIterable4()) { - assertTrue(this.nodes.contains(gn)); - } - } - - private Iterable<GraphNode> buildGraphIterable4() { - return new GraphIterable<GraphNode>(new GraphNode[] { this.buildGraphRoot() }, this.buildMisterRogers()); - } - - public void testToString() { - assertNotNull(this.buildGraphIterable1().toString()); - } - - public void testMissingMisterRogers() { - boolean exCaught = false; - try { - for (GraphNode gn : new GraphIterable<GraphNode>(this.buildGraphRoot())) { - assertTrue(this.nodes.contains(gn)); - } - fail(); - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private GraphIterator.MisterRogers<GraphNode> buildMisterRogers() { - return new GraphIterator.MisterRogers<GraphNode>() { - public Iterator<GraphNode> neighbors(GraphNode next) { - return next.neighbors(); - } - }; - } - - private GraphNode buildGraphRoot() { - GraphNode ncNode = new GraphNode("North Carolina"); - GraphNode vaNode = new GraphNode("Virginia"); - GraphNode scNode = new GraphNode("South Carolina"); - GraphNode gaNode = new GraphNode("Georgia"); - GraphNode flNode = new GraphNode("Florida"); - GraphNode alNode = new GraphNode("Alabama"); - GraphNode msNode = new GraphNode("Mississippi"); - GraphNode tnNode = new GraphNode("Tennessee"); - - ncNode.setNeighbors(new GraphNode[] { vaNode, scNode, gaNode, tnNode }); - vaNode.setNeighbors(new GraphNode[] { ncNode, tnNode }); - scNode.setNeighbors(new GraphNode[] { ncNode, gaNode }); - gaNode.setNeighbors(new GraphNode[] { ncNode, scNode, flNode, alNode, tnNode }); - flNode.setNeighbors(new GraphNode[] { gaNode }); - alNode.setNeighbors(new GraphNode[] { gaNode, msNode, tnNode }); - msNode.setNeighbors(new GraphNode[] { alNode, tnNode }); - tnNode.setNeighbors(new GraphNode[] { vaNode, ncNode, gaNode, alNode, msNode }); - - return ncNode; - } - - public class GraphNode { - private String name; - - private Collection<GraphNode> neighbors = new ArrayList<GraphNode>(); - - public GraphNode(String name) { - super(); - GraphIterableTests.this.nodes.add(this); // log node - this.name = name; - } - - public String getName() { - return this.name; - } - - void setNeighbors(GraphNode[] neighbors) { - this.neighbors = CollectionTools.list(neighbors); - } - - public Iterator<GraphNode> neighbors() { - return this.neighbors.iterator(); - } - - public int neighborsSize() { - return this.neighbors.size(); - } - - @Override - public String toString() { - return "GraphNode(" + this.name + ")"; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/JptUtilityIterablesTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/JptUtilityIterablesTests.java deleted file mode 100644 index 6da560d319..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/JptUtilityIterablesTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * decentralize test creation code - */ -public class JptUtilityIterablesTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityIterablesTests.class.getPackage().getName()); - - suite.addTestSuite(ArrayIterableTests.class); - suite.addTestSuite(ArrayListIterableTests.class); - suite.addTestSuite(ChainIterableTests.class); - suite.addTestSuite(CompositeIterableTests.class); - suite.addTestSuite(CompositeListIterableTests.class); - suite.addTestSuite(EmptyIterableTests.class); - suite.addTestSuite(EmptyListIterableTests.class); - suite.addTestSuite(FilteringIterableTests.class); - suite.addTestSuite(SuperIterableWrapperTests.class); - suite.addTestSuite(GraphIterableTests.class); - suite.addTestSuite(LiveCloneIterableTests.class); - suite.addTestSuite(LiveCloneListIterableTests.class); - suite.addTestSuite(PeekableIterableTests.class); - suite.addTestSuite(QueueIterableTests.class); - suite.addTestSuite(ReadOnlyCompositeListIterableTests.class); - suite.addTestSuite(ReadOnlyIterableTests.class); - suite.addTestSuite(ReadOnlyListIterableTests.class); - suite.addTestSuite(SingleElementIterableTests.class); - suite.addTestSuite(SingleElementListIterableTests.class); - suite.addTestSuite(SnapshotCloneIterableTests.class); - suite.addTestSuite(SnapshotCloneListIterableTests.class); - suite.addTestSuite(StackIterableTests.class); - suite.addTestSuite(TransformationIterableTests.class); - suite.addTestSuite(TransformationListIterableTests.class); - suite.addTestSuite(TreeIterableTests.class); - - return suite; - } - - private JptUtilityIterablesTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/LiveCloneIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/LiveCloneIterableTests.java deleted file mode 100644 index 96fde7ffde..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/LiveCloneIterableTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.List; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterables.LiveCloneIterable; - -@SuppressWarnings("nls") -public class LiveCloneIterableTests extends CloneIterableTests { - - public LiveCloneIterableTests(String name) { - super(name); - } - - @Override - public void testIterator() { - super.testIterator(); - // iterable should now return only 3 strings (since it's "live") - int i = 0; - for (String s : this.iterable) { - assertEquals(String.valueOf(i++), s); - } - assertEquals(3, i); - } - - @Override - public void testRemove() { - super.testRemove(); - // "live" clone iterable will no longer contain the element removed from the - // original collection - assertFalse(CollectionTools.contains(this.iterable, "three")); - } - - @Override - public void testRemover() { - super.testRemover(); - // "live" clone iterable will no longer contain the element removed from the - // original collection - assertFalse(CollectionTools.contains(this.iterable, "three")); - } - - @Override - Iterable<String> buildIterable(List<String> c) { - return new LiveCloneIterable<String>(c); - } - - @Override - Iterable<String> buildRemovingIterable(final List<String> c) { - return new LiveCloneIterable<String>(c) { - @Override - protected void remove(String current) { - c.remove(current); - } - }; - } - - @Override - Iterable<String> buildIterableWithRemover(List<String> c) { - return new LiveCloneIterable<String>(c, this.buildRemover(c)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/LiveCloneListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/LiveCloneListIterableTests.java deleted file mode 100644 index 0d70c000ea..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/LiveCloneListIterableTests.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.List; -import java.util.ListIterator; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterables.LiveCloneListIterable; - -@SuppressWarnings("nls") -public class LiveCloneListIterableTests extends LiveCloneIterableTests { - - public LiveCloneListIterableTests(String name) { - super(name); - } - - public void testAdd() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildRemovingIterable(collection); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("two")) { - iterator.add(added); - } - } - assertTrue(collection.contains(added)); - // "live" clone iterable will contain the element added to the - // original collection - assertTrue(CollectionTools.contains(this.iterable, added)); - } - - public void testMissingMutatorAdd() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterable(collection); - assertNotNull(this.iterable.toString()); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - boolean exCaught = false; - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("three")) { - try { - iterator.add(added); - fail(); - } catch (RuntimeException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - public void testSet() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildRemovingIterable(collection); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("two")) { - iterator.set(added); - } - } - assertTrue(collection.contains(added)); - assertFalse(collection.contains("two")); - // "live" clone iterable will contain the element added to the - // original collection - assertTrue(CollectionTools.contains(this.iterable, added)); - assertFalse(CollectionTools.contains(this.iterable, "two")); - } - - public void testMissingMutatorSet() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterable(collection); - assertNotNull(this.iterable.toString()); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - boolean exCaught = false; - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("three")) { - try { - iterator.set(added); - fail(); - } catch (RuntimeException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - @Override - Iterable<String> buildIterable(List<String> c) { - return new LiveCloneListIterable<String>(c); - } - - @Override - Iterable<String> buildRemovingIterable(final List<String> c) { - return new LiveCloneListIterable<String>(c) { - @Override - protected void add(int index, String element) { - c.add(index, element); - } - @Override - protected void remove(int index) { - c.remove(index); - } - @Override - protected void set(int index, String element) { - c.set(index, element); - } - }; - } - - @Override - Iterable<String> buildIterableWithRemover(List<String> c) { - return new LiveCloneListIterable<String>(c, this.buildMutator(c)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/PeekableIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/PeekableIterableTests.java deleted file mode 100644 index 634992e5db..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/PeekableIterableTests.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ArrayIterable; -import org.eclipse.jpt.common.utility.internal.iterables.PeekableIterable; -import org.eclipse.jpt.common.utility.internal.iterators.PeekableIterator; - -@SuppressWarnings("nls") -public class PeekableIterableTests extends TestCase { - - public PeekableIterableTests(String name) { - super(name); - } - - public void testIterator() { - PeekableIterable<String> iterable = this.buildIterable(); - PeekableIterator<String> iterator = iterable.iterator(); - assertEquals("one", iterator.peek()); - } - - public void testToString() { - assertNotNull(this.buildIterable().toString()); - } - - private PeekableIterable<String> buildIterable() { - return new PeekableIterable<String>(this.buildNestedIterable()); - } - - private Iterable<String> buildNestedIterable() { - return new ArrayIterable<String>(this.buildArray()); - } - - private String[] buildArray() { - return new String[] {"one", "two", "three"}; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/QueueIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/QueueIterableTests.java deleted file mode 100644 index 649f336336..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/QueueIterableTests.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Queue; -import org.eclipse.jpt.common.utility.internal.SimpleQueue; -import org.eclipse.jpt.common.utility.internal.iterables.QueueIterable; - -@SuppressWarnings("nls") -public class QueueIterableTests extends TestCase { - - public QueueIterableTests(String name) { - super(name); - } - - public void testIterator() { - Iterable<String> iterable = this.buildIterable(); - for (String s : iterable) { - assertNotNull(s); - } - } - - public void testToString() { - assertNotNull(this.buildIterable().toString()); - } - - private Iterable<String> buildIterable() { - return new QueueIterable<String>(this.buildQueue()); - } - - private Queue<String> buildQueue() { - Queue<String> q = new SimpleQueue<String>(); - q.enqueue("foo"); - q.enqueue("bar"); - q.enqueue("baz"); - return q; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyCompositeListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyCompositeListIterableTests.java deleted file mode 100644 index f217b39b2d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyCompositeListIterableTests.java +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ListListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ReadOnlyCompositeListIterable; - -@SuppressWarnings("nls") -public class ReadOnlyCompositeListIterableTests extends TestCase { - - public ReadOnlyCompositeListIterableTests(String name) { - super(name); - } - - public void testIterator() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - ListIterable<String> li1 = new ListListIterable<String>(c1); - - List<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - ListIterable<String> li2 = new ListListIterable<String>(c2); - - @SuppressWarnings("unchecked") - Iterable<String> composite = new ReadOnlyCompositeListIterable<String>(li1, li2); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testExtraElement1() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - ListIterable<String> li1 = new ListListIterable<String>(c1); - - Iterable<String> composite = new ReadOnlyCompositeListIterable<String>(li1, "4"); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testExtraElement2() { - List<String> c1 = new ArrayList<String>(); - c1.add("1"); - c1.add("2"); - c1.add("3"); - ListIterable<String> li1 = new ListListIterable<String>(c1); - - Iterable<String> composite = new ReadOnlyCompositeListIterable<String>("0", li1); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testCollectionOfIterables() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - ListIterable<String> li1 = new ListListIterable<String>(c1); - - List<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - ListIterable<String> li2 = new ListListIterable<String>(c2); - - List<ListIterable<String>> collection = new ArrayList<ListIterable<String>>(); - collection.add(li1); - collection.add(li2); - ListIterable<ListIterable<String>> li = new ListListIterable<ListIterable<String>>(collection); - - Iterable<String> composite = new ReadOnlyCompositeListIterable<String>(li); - int i = 0; - for (String s : composite) { - assertEquals(String.valueOf(i++), s); - } - } - - public void testToString() { - List<String> c1 = new ArrayList<String>(); - c1.add("0"); - c1.add("1"); - c1.add("2"); - c1.add("3"); - ListIterable<String> li1 = new ListListIterable<String>(c1); - - List<String> c2 = new ArrayList<String>(); - c2.add("4"); - c2.add("5"); - c2.add("6"); - c2.add("7"); - ListIterable<String> li2 = new ListListIterable<String>(c2); - - @SuppressWarnings("unchecked") - Iterable<String> composite = new ReadOnlyCompositeListIterable<String>(li1, li2); - assertNotNull(composite.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyIterableTests.java deleted file mode 100644 index 4399851f65..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyIterableTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.Iterator; -import java.util.Vector; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ReadOnlyIterable; - -@SuppressWarnings("nls") -public class ReadOnlyIterableTests extends TestCase { - - public ReadOnlyIterableTests(String name) { - super(name); - } - - public void testIterator() { - Iterator<String> nestedIterator = this.buildVector().iterator(); - for (String s : this.buildReadOnlyIterable()) { - assertEquals(nestedIterator.next(), s); - } - } - - public void testRemove() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildReadOnlyIterable().iterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - public void testToString() { - assertNotNull(this.buildReadOnlyIterable().toString()); - } - - private Iterable<String> buildReadOnlyIterable() { - return new ReadOnlyIterable<String>(this.buildVector()); - } - - private Vector<String> buildVector() { - Vector<String> v = new Vector<String>(); - v.addElement("one"); - v.addElement("two"); - v.addElement("three"); - v.addElement("four"); - v.addElement("five"); - v.addElement("six"); - v.addElement("seven"); - v.addElement("eight"); - return v; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyListIterableTests.java deleted file mode 100644 index 8a923ff3e4..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/ReadOnlyListIterableTests.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.Iterator; -import java.util.Vector; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.ListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ListListIterable; -import org.eclipse.jpt.common.utility.internal.iterables.ReadOnlyListIterable; - -@SuppressWarnings("nls") -public class ReadOnlyListIterableTests extends TestCase { - - public ReadOnlyListIterableTests(String name) { - super(name); - } - - public void testIterator() { - Iterator<String> nestedIterator = this.buildVector().iterator(); - for (String s : this.buildReadOnlyListIterable()) { - assertEquals(nestedIterator.next(), s); - } - } - - public void testRemove() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildReadOnlyListIterable().iterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - public void testToString() { - assertNotNull(this.buildReadOnlyListIterable().toString()); - } - - private Iterable<String> buildReadOnlyListIterable() { - return new ReadOnlyListIterable<String>(this.buildNestedListIterable()); - } - - private ListIterable<String> buildNestedListIterable() { - return new ListListIterable<String>(this.buildVector()); - } - - private Vector<String> buildVector() { - Vector<String> v = new Vector<String>(); - v.addElement("one"); - v.addElement("two"); - v.addElement("three"); - v.addElement("four"); - v.addElement("five"); - v.addElement("six"); - v.addElement("seven"); - v.addElement("eight"); - return v; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SingleElementIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SingleElementIterableTests.java deleted file mode 100644 index 49061d3773..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SingleElementIterableTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.SingleElementIterable; - -@SuppressWarnings("nls") -public class SingleElementIterableTests extends TestCase { - - public SingleElementIterableTests(String name) { - super(name); - } - - public void testIterator() { - for (String s : this.buildSingleElementIterable()) { - assertEquals(this.singleElement(), s); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildSingleElementIterable().iterator(); - String string = stream.next(); - try { - string = stream.next(); - fail("bogus element: " + string); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemove() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildSingleElementIterable().iterator(); stream.hasNext(); ) { - if (stream.next().equals(this.singleElement())) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - protected Iterable<String> buildSingleElementIterable() { - return new SingleElementIterable<String>(this.singleElement()); - } - - protected String singleElement() { - return "single element"; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SingleElementListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SingleElementListIterableTests.java deleted file mode 100644 index d11520f7de..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SingleElementListIterableTests.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.SingleElementListIterable; - -@SuppressWarnings("nls") -public class SingleElementListIterableTests extends TestCase { - - public SingleElementListIterableTests(String name) { - super(name); - } - - public void testIterator() { - for (String s : this.buildSingleElementListIterable()) { - assertEquals(this.singleElement(), s); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildSingleElementListIterable().iterator(); - String string = stream.next(); - try { - string = stream.next(); - fail("bogus element: " + string); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemove() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildSingleElementListIterable().iterator(); stream.hasNext(); ) { - if (stream.next().equals(this.singleElement())) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testToString() { - assertNotNull(this.buildSingleElementListIterable().toString()); - } - - protected Iterable<String> buildSingleElementListIterable() { - return new SingleElementListIterable<String>(this.singleElement()); - } - - protected String singleElement() { - return "single element"; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SnapshotCloneIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SnapshotCloneIterableTests.java deleted file mode 100644 index 384006c45e..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SnapshotCloneIterableTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.List; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterables.SnapshotCloneIterable; - -@SuppressWarnings("nls") -public class SnapshotCloneIterableTests extends CloneIterableTests { - - public SnapshotCloneIterableTests(String name) { - super(name); - } - - @Override - public void testIterator() { - super.testIterator(); - // "snapshot" iterable should still return 4 strings (since the original collection was cloned) - int i = 0; - for (String s : this.iterable) { - assertEquals(String.valueOf(i++), s); - } - assertEquals(4, i); - } - - @Override - public void testRemove() { - super.testRemove(); - // "snapshot" clone iterable will still contain the element removed from the - // original collection - assertTrue(CollectionTools.contains(this.iterable, "three")); - } - - @Override - public void testRemover() { - super.testRemover(); - // "snapshot" clone iterable will still contain the element removed from the - // original collection - assertTrue(CollectionTools.contains(this.iterable, "three")); - } - - @Override - Iterable<String> buildIterable(List<String> c) { - return new SnapshotCloneIterable<String>(c); - } - - @Override - Iterable<String> buildRemovingIterable(final List<String> c) { - return new SnapshotCloneIterable<String>(c) { - @Override - protected void remove(String current) { - c.remove(current); - } - }; - } - - @Override - Iterable<String> buildIterableWithRemover(List<String> c) { - return new SnapshotCloneIterable<String>(c, this.buildRemover(c)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SnapshotCloneListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SnapshotCloneListIterableTests.java deleted file mode 100644 index a6c5c1376b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SnapshotCloneListIterableTests.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.List; -import java.util.ListIterator; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterables.SnapshotCloneListIterable; - -@SuppressWarnings("nls") -public class SnapshotCloneListIterableTests extends SnapshotCloneIterableTests { - - public SnapshotCloneListIterableTests(String name) { - super(name); - } - - public void testAdd() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildRemovingIterable(collection); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("two")) { - iterator.add(added); - } - } - assertTrue(collection.contains(added)); - // "snapshot" clone iterable not will contain the element added to the - // original collection - assertFalse(CollectionTools.contains(this.iterable, added)); - } - - public void testMissingMutatorAdd() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterable(collection); - assertNotNull(this.iterable.toString()); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - boolean exCaught = false; - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("three")) { - try { - iterator.add(added); - fail(); - } catch (RuntimeException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - public void testSet() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildRemovingIterable(collection); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - assertTrue(CollectionTools.contains(this.iterable, "two")); - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("two")) { - iterator.set(added); - } - } - assertTrue(collection.contains(added)); - assertFalse(collection.contains("two")); - // "snapshot" clone iterable will not be changed - assertFalse(CollectionTools.contains(this.iterable, added)); - assertTrue(CollectionTools.contains(this.iterable, "two")); - } - - public void testMissingMutatorSet() { - final List<String> collection = this.buildCollection(); - this.iterable = this.buildIterable(collection); - assertNotNull(this.iterable.toString()); - - String added = "xxxx"; - assertFalse(CollectionTools.contains(this.iterable, added)); - boolean exCaught = false; - for (ListIterator<String> iterator = (ListIterator<String>) this.iterable.iterator(); iterator.hasNext(); ) { - if (iterator.next().equals("three")) { - try { - iterator.set(added); - fail(); - } catch (RuntimeException ex) { - exCaught = true; - } - } - } - assertTrue(exCaught); - } - - @Override - Iterable<String> buildIterable(List<String> c) { - return new SnapshotCloneListIterable<String>(c); - } - - @Override - Iterable<String> buildRemovingIterable(final List<String> c) { - return new SnapshotCloneListIterable<String>(c) { - @Override - protected void add(int index, String element) { - c.add(index, element); - } - @Override - protected void remove(int index) { - c.remove(index); - } - @Override - protected void set(int index, String element) { - c.set(index, element); - } - }; - } - - @Override - Iterable<String> buildIterableWithRemover(List<String> c) { - return new SnapshotCloneListIterable<String>(c, this.buildMutator(c)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/StackIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/StackIterableTests.java deleted file mode 100644 index 70a95bcd8a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/StackIterableTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.SimpleStack; -import org.eclipse.jpt.common.utility.internal.Stack; -import org.eclipse.jpt.common.utility.internal.iterables.StackIterable; - -@SuppressWarnings("nls") -public class StackIterableTests extends TestCase { - - public StackIterableTests(String name) { - super(name); - } - - public void testIterator() { - Iterator<String> iterator = this.buildIterable().iterator(); - assertEquals("three", iterator.next()); - assertEquals("two", iterator.next()); - assertEquals("one", iterator.next()); - } - - public void testToString() { - assertNotNull(this.buildIterable().toString()); - } - - private Iterable<String> buildIterable() { - return new StackIterable<String>(this.buildStack()); - } - - private Stack<String> buildStack() { - Stack<String> stack = new SimpleStack<String>(); - stack.push("one"); - stack.push("two"); - stack.push("three"); - return stack; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SuperIterableWrapperTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SuperIterableWrapperTests.java deleted file mode 100644 index c65608ef5d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/SuperIterableWrapperTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collections; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.SuperIterableWrapper; - -@SuppressWarnings("nls") -public class SuperIterableWrapperTests extends TestCase { - - public SuperIterableWrapperTests(String name) { - super(name); - } - - public void testIterator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - String concat = ""; - for (String s : list) { - concat += s; - } - assertEquals("foobarbaz", concat); - - Iterable<Object> iterable = new SuperIterableWrapper<Object>(list); - concat = ""; - for (Object s : iterable) { - concat += s; - } - assertEquals("foobarbaz", concat); - } - - public void testToString() { - Iterable<Object> iterable = new SuperIterableWrapper<Object>(Collections.emptyList()); - assertNotNull(iterable.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TransformationIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TransformationIterableTests.java deleted file mode 100644 index 5a16de67c8..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TransformationIterableTests.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.iterables.TransformationIterable; - -@SuppressWarnings("nls") -public class TransformationIterableTests extends TestCase { - - public TransformationIterableTests(String name) { - super(name); - } - - public void testTransform1() { - int i = 1; - for (Integer integer : this.buildIterable1()) { - assertEquals(i++, integer.intValue()); - } - } - - private Iterable<Integer> buildIterable1() { - return this.buildTransformationIterable1(this.buildNestedIterable()); - } - - private Iterable<Integer> buildTransformationIterable1(Iterable<String> nestedIterable) { - // transform each string into an integer with a value of the string's length - return new TransformationIterable<String, Integer>(nestedIterable) { - @Override - protected Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - public void testTransform2() { - int i = 1; - for (Integer integer : this.buildIterable2()) { - assertEquals(i++, integer.intValue()); - } - } - - private Iterable<Integer> buildIterable2() { - return this.buildTransformationIterable2(this.buildNestedIterable()); - } - - private Iterable<Integer> buildTransformationIterable2(Iterable<String> nestedIterable) { - // transform each string into an integer with a value of the string's length - return new TransformationIterable<String, Integer>(nestedIterable, this.buildTransformer()); - } - - private Transformer<String, Integer> buildTransformer() { - // transform each string into an integer with a value of the string's length - return new Transformer<String, Integer>() { - public Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - private Iterable<String> buildNestedIterable() { - Collection<String> c = new ArrayList<String>(); - c.add("1"); - c.add("22"); - c.add("333"); - c.add("4444"); - c.add("55555"); - c.add("666666"); - c.add("7777777"); - c.add("88888888"); - return c; - } - - public void testToString() { - assertNotNull(this.buildIterable1().toString()); - } - - public void testMissingTransformer() { - Iterable<Integer> iterable = new TransformationIterable<String, Integer>(this.buildNestedIterable()); - boolean exCaught = false; - try { - int i = 1; - for (Integer integer : iterable) { - assertEquals(i++, integer.intValue()); - } - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TransformationListIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TransformationListIterableTests.java deleted file mode 100644 index 6ac6a16d07..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TransformationListIterableTests.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.iterables.TransformationListIterable; - -@SuppressWarnings("nls") -public class TransformationListIterableTests extends TestCase { - - public TransformationListIterableTests(String name) { - super(name); - } - - public void testTransform1() { - int i = 1; - for (Integer integer : this.buildIterable1()) { - assertEquals(i++, integer.intValue()); - } - } - - private Iterable<Integer> buildIterable1() { - return this.buildTransformationListIterable1(this.buildNestedList()); - } - - private Iterable<Integer> buildTransformationListIterable1(List<String> nestedList) { - // transform each string into an integer with a value of the string's length - return new TransformationListIterable<String, Integer>(nestedList) { - @Override - protected Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - public void testTransform2() { - int i = 1; - for (Integer integer : this.buildIterable2()) { - assertEquals(i++, integer.intValue()); - } - } - - private Iterable<Integer> buildIterable2() { - return this.buildTransformationListIterable2(this.buildNestedList()); - } - - private Iterable<Integer> buildTransformationListIterable2(List<String> nestedList) { - // transform each string into an integer with a value of the string's length - return new TransformationListIterable<String, Integer>(nestedList, this.buildTransformer()); - } - - private Transformer<String, Integer> buildTransformer() { - // transform each string into an integer with a value of the string's length - return new Transformer<String, Integer>() { - public Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - private List<String> buildNestedList() { - List<String> c = new ArrayList<String>(); - c.add("1"); - c.add("22"); - c.add("333"); - c.add("4444"); - c.add("55555"); - c.add("666666"); - c.add("7777777"); - c.add("88888888"); - return c; - } - - public void testToString() { - assertNotNull(this.buildIterable1().toString()); - } - - public void testMissingTransformer() { - Iterable<Integer> iterable = new TransformationListIterable<String, Integer>(this.buildNestedList()); - boolean exCaught = false; - try { - int i = 1; - for (Integer integer : iterable) { - assertEquals(i++, integer.intValue()); - } - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TreeIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TreeIterableTests.java deleted file mode 100644 index dda3533e2b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterables/TreeIterableTests.java +++ /dev/null @@ -1,155 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterables; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterables.TreeIterable; -import org.eclipse.jpt.common.utility.internal.iterators.TreeIterator; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class TreeIterableTests extends TestCase { - /** this will be populated with all the nodes created for the test */ - Collection<TreeNode> nodes = new ArrayList<TreeNode>(); - - public TreeIterableTests(String name) { - super(name); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator1() { - for (TreeNode tn : this.buildTreeIterable1()) { - assertTrue(this.nodes.contains(tn)); - } - } - - public void testIterator2() { - for (TreeNode tn : this.buildTreeIterable2()) { - assertTrue(this.nodes.contains(tn)); - } - } - - public void testMidwife1() { - for (TreeNode tn : new TreeIterable<TreeNode>(this.buildTree(), this.buildMidwife())) { - assertTrue(this.nodes.contains(tn)); - } - } - - public void testMidwife2() { - for (TreeNode tn : new TreeIterable<TreeNode>(new TreeNode[] { this.buildTree() }, this.buildMidwife())) { - assertTrue(this.nodes.contains(tn)); - } - } - - public void testToString() { - assertNotNull(this.buildTreeIterable1().toString()); - } - - public void testMissingMidwife() { - boolean exCaught = false; - try { - for (TreeNode tn : new TreeIterable<TreeNode>(this.buildTree())) { - assertTrue(this.nodes.contains(tn)); - } - } catch (RuntimeException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private Iterable<TreeNode> buildTreeIterable1() { - return new TreeIterable<TreeNode>(this.buildTree()) { - @Override - public Iterator<TreeNode> children(TreeNode next) { - return next.children(); - } - }; - } - - private Iterable<TreeNode> buildTreeIterable2() { - return new TreeIterable<TreeNode>(new TreeNode[] { this.buildTree() }) { - @Override - public Iterator<TreeNode> children(TreeNode next) { - return next.children(); - } - }; - } - - private TreeIterator.Midwife<TreeNode> buildMidwife() { - return new TreeIterator.Midwife<TreeNode>() { - public Iterator<TreeNode> children(TreeNode next) { - return next.children(); - } - }; - } - - private TreeNode buildTree() { - TreeNode root = new TreeNode("root"); - TreeNode child1 = new TreeNode(root, "child 1"); - new TreeNode(child1, "grandchild 1A"); - TreeNode child2 = new TreeNode(root, "child 2"); - new TreeNode(child2, "grandchild 2A"); - TreeNode grandchild2B = new TreeNode(child2, "grandchild 2B"); - new TreeNode(grandchild2B, "great-grandchild 2B1"); - new TreeNode(grandchild2B, "great-grandchild 2B2"); - TreeNode grandchild2C = new TreeNode(child2, "grandchild 2C"); - new TreeNode(grandchild2C, "great-grandchild 2C1"); - new TreeNode(root, "child 3"); - return root; - } - - public class TreeNode { - private String name; - private Collection<TreeNode> children = new ArrayList<TreeNode>(); - - public TreeNode(String name) { - super(); - TreeIterableTests.this.nodes.add(this); // log node - this.name = name; - } - - public TreeNode(TreeNode parent, String name) { - this(name); - parent.addChild(this); - } - - public String getName() { - return this.name; - } - - private void addChild(TreeNode child) { - this.children.add(child); - } - - public Iterator<TreeNode> children() { - return this.children.iterator(); - } - - public int childrenSize() { - return this.children.size(); - } - - @Override - public String toString() { - return "TreeNode(" + this.name + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ArrayIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ArrayIteratorTests.java deleted file mode 100644 index 8c8cda0ae7..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ArrayIteratorTests.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.ArrayIterator; - -@SuppressWarnings("nls") -public class ArrayIteratorTests extends TestCase { - - public ArrayIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildIterator(); stream.hasNext(); ) { - stream.next(); - i++; - } - assertEquals(this.buildArray().length, i); - } - - public void testNext() { - int i = 1; - for (Iterator<String> stream = this.buildIterator(); stream.hasNext(); ) { - assertEquals("bogus element", i++, Integer.parseInt(stream.next())); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildIterator(); stream.hasNext(); ) { - if (stream.next().equals("3")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testIllegalArgumentException() { - this.triggerIllegalArgumentException(-1, 1); - this.triggerIllegalArgumentException(8, 1); - this.triggerIllegalArgumentException(0, -1); - this.triggerIllegalArgumentException(0, 9); - } - - public void testGenerics() { - Integer[] integers = new Integer[3]; - integers[0] = new Integer(0); - integers[1] = new Integer(1); - integers[2] = new Integer(2); - int i = 0; - for (Iterator<Number> stream = this.buildGenericIterator(integers); stream.hasNext();) { - assertEquals(i++, stream.next().intValue()); - } - assertEquals(integers.length, i); - } - - Iterator<Number> buildGenericIterator(Integer[] integers) { - return new ArrayIterator<Number>(integers); - } - - public void testVarargs() { - int i = 0; - for (Iterator<Number> stream = this.buildVarArgIterator(); stream.hasNext();) { - assertEquals(i++, stream.next().intValue()); - } - assertEquals(3, i); - } - - Iterator<Number> buildVarArgIterator() { - return new ArrayIterator<Number>(new Integer(0), new Integer(1), new Integer(2)); - } - - void triggerIllegalArgumentException(int start, int length) { - boolean exCaught = false; - Iterator<String> stream = null; - try { - stream = this.buildIterator(start, length); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue("IllegalArgumentException not thrown: " + stream, exCaught); - } - - Iterator<String> buildIterator() { - return this.buildIterator(this.buildArray()); - } - - Iterator<String> buildIterator(String[] array) { - return new ArrayIterator<String>(array); - } - - Iterator<String> buildIterator(int start, int length) { - return this.buildIterator(this.buildArray(), start, length); - } - - Iterator<String> buildIterator(String[] array, int start, int length) { - return new ArrayIterator<String>(array, start, length); - } - - String[] buildArray() { - return new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ArrayListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ArrayListIteratorTests.java deleted file mode 100644 index cae1762c27..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ArrayListIteratorTests.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.iterators.ArrayListIterator; - -@SuppressWarnings("nls") -public class ArrayListIteratorTests extends ArrayIteratorTests { - - public ArrayListIteratorTests(String name) { - super(name); - } - - public void testHasPrevious() { - ListIterator<String> stream = this.buildListIterator(); - while (stream.hasNext()) { - stream.next(); - } - int i = 0; - while (stream.hasPrevious()) { - stream.previous(); - i++; - } - assertEquals(this.buildArray().length, i); - } - - public void testPrevious() { - ListIterator<String> stream = this.buildListIterator(); - while (stream.hasNext()) { - stream.next(); - } - int i = this.buildArray().length; - while (stream.hasPrevious()) { - assertEquals("bogus element", i--, Integer.parseInt(stream.previous())); - } - } - - public void testNextIndex() { - int i = 0; - ListIterator<String> stream = this.buildListIterator(); - while (stream.hasNext()) { - assertEquals(i, stream.nextIndex()); - stream.next(); - i++; - } - assertEquals(i, stream.nextIndex()); - } - - public void testPreviousIndex() { - int i = 0; - ListIterator<String> stream = this.buildListIterator(); - while (stream.hasNext()) { - assertEquals(i - 1, stream.previousIndex()); - stream.next(); - i++; - } - assertEquals(i - 1, stream.previousIndex()); - } - - @Override - public void testNoSuchElementException() { - boolean exCaught = false; - ListIterator<String> stream = this.buildListIterator(); - String string = null; - try { - string = stream.previous(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testUnsupportedOperationExceptionAdd() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildListIterator(); stream.hasNext();) { - if (stream.next().equals("3")) { - try { - stream.add("3.5"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testUnsupportedOperationExceptionSet() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildListIterator(); stream.hasNext();) { - if (stream.next().equals("3")) { - try { - stream.set("three"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - @Override - Iterator<Number> buildGenericIterator(Integer[] integers) { - return new ArrayListIterator<Number>(integers); - } - - @Override - Iterator<Number> buildVarArgIterator() { - return new ArrayListIterator<Number>(new Integer(0), new Integer(1), new Integer(2)); - } - - private ListIterator<String> buildListIterator() { - return this.buildListIterator(this.buildArray()); - } - - private ListIterator<String> buildListIterator(String[] array) { - return new ArrayListIterator<String>(array); - } - - @Override - Iterator<String> buildIterator(String[] array) { - return new ArrayListIterator<String>(array); - } - - @Override - Iterator<String> buildIterator(String[] array, int start, int length) { - return new ArrayListIterator<String>(array, start, length); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ChainIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ChainIteratorTests.java deleted file mode 100644 index b4cdcf1569..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ChainIteratorTests.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.AbstractCollection; -import java.util.AbstractList; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Vector; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.ChainIterator; - -@SuppressWarnings("nls") -public class ChainIteratorTests extends TestCase { - private final static Class<?>[] VECTOR_HIERARCHY = { Vector.class, AbstractList.class, AbstractCollection.class, Object.class }; - - public ChainIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<Class<?>> stream = this.buildIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(VECTOR_HIERARCHY.length, i); - } - - public void testInnerHasNext() { - int i = 0; - for (Iterator<Class<?>> stream = this.buildInnerIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(VECTOR_HIERARCHY.length, i); - } - - public void testNext() { - int i = 0; - for (Iterator<Class<?>> stream = this.buildIterator(); stream.hasNext(); i++) { - assertEquals("bogus link", VECTOR_HIERARCHY[i], stream.next()); - } - } - - public void testInnerNext() { - int i = 0; - for (Iterator<Class<?>> stream = this.buildInnerIterator(); stream.hasNext(); i++) { - assertEquals("bogus link", VECTOR_HIERARCHY[i], stream.next()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<Class<?>> stream = this.buildIterator(); - Class<?> javaClass = null; - while (stream.hasNext()) { - javaClass = stream.next(); - } - try { - javaClass = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + javaClass, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<Class<?>> stream = this.buildIterator(); stream.hasNext();) { - if (stream.next() == AbstractCollection.class) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - private Iterator<Class<?>> buildIterator() { - return this.buildChainIterator(Vector.class, this.buildLinker()); - } - - private Iterator<Class<?>> buildInnerIterator() { - return this.buildInnerChainIterator(Vector.class); - } - - private Iterator<Class<?>> buildChainIterator(Class<?> startLink, ChainIterator.Linker<Class<?>> linker) { - return new ChainIterator<Class<?>>(startLink, linker); - } - - private ChainIterator.Linker<Class<?>> buildLinker() { - // chain up the class's hierarchy - return new ChainIterator.Linker<Class<?>>() { - public Class<?> nextLink(Class<?> currentLink) { - return currentLink.getSuperclass(); - } - }; - } - - private Iterator<Class<?>> buildInnerChainIterator(Class<?> startLink) { - // chain up the class's hierarchy - return new ChainIterator<Class<?>>(startLink) { - @Override - protected Class<?> nextLink(Class<?> currentLink) { - return currentLink.getSuperclass(); - } - }; - } - - public void testInvalidChainIterator() { - // missing method override - Iterator<Class<?>> iterator = new ChainIterator<Class<?>>(Vector.class); - boolean exCaught = false; - try { - Class<?> c = iterator.next(); - fail("invalid class: " + c.getName()); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CloneIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CloneIteratorTests.java deleted file mode 100644 index 19c45dfd35..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CloneIteratorTests.java +++ /dev/null @@ -1,237 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.iterators.CloneIterator; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CloneIteratorTests - extends MultiThreadedTestCase -{ - Collection<String> originalCollection; - - private Collection<String> concurrentCollection; - - public CloneIteratorTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.originalCollection = this.buildCollection(); - } - - public void testHasNext() { - int originalSize = this.originalCollection.size(); - int i = 0; - for (Iterator<String> stream = this.buildCloneIterator(); stream.hasNext();) { - stream.next(); - // should allow concurrent modification - this.originalCollection.add("foo"); - i++; - } - assertTrue(originalSize != this.originalCollection.size()); - assertEquals(originalSize, i); - } - - public void testNext() { - Iterator<String> nestedIterator = this.originalCollection.iterator(); - for (Iterator<String> stream = this.buildCloneIterator(); stream.hasNext();) { - assertEquals("bogus element", nestedIterator.next(), stream.next()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildCloneIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testRemoveDefault() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildCloneIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testRemoveEliminator() { - CloneIterator.Remover<String> eliminator = new CloneIterator.Remover<String>() { - public void remove(String element) { - CloneIteratorTests.this.originalCollection.remove(element); - } - }; - this.verifyRemove(new CloneIterator<String>(this.originalCollection, eliminator)); - } - - public void testRemoveSubclass() { - this.verifyRemove(new CloneIterator<String>(this.originalCollection) { - @Override - protected void remove(String current) { - CloneIteratorTests.this.originalCollection.remove(current); - } - }); - } - - /** - * Test concurrent access: First build a clone iterator in a separate thread - * that hangs momentarily during its construction; then modify the shared - * collection in this thread. This would cause a - * ConcurrentModificationException in the other thread if the clone iterator - * were not synchronized on the original collection. - */ - public void testConcurrentAccess() throws Exception { - SlowCollection<String> slow = new SlowCollection<String>(); - this.populateCollection(slow); - // using the unsynchronized collection will cause the test to fail - // this.originalCollection = slow; - this.originalCollection = Collections.synchronizedCollection(slow); - - this.concurrentCollection = new ArrayList<String>(); - Thread thread = this.buildThread(this.buildRunnable()); - thread.start(); - while ( ! slow.hasStartedClone()) { - // wait for the other thread to start the clone... - Thread.yield(); - } - // ...then sneak in an extra element - this.originalCollection.add("seventeen"); - thread.join(); - Collection<String> expected = new ArrayList<String>(); - this.populateCollection(expected); - assertEquals(expected, this.concurrentCollection); - } - - private Runnable buildRunnable() { - return new TestRunnable() { - @Override - protected void run_() throws Throwable { - CloneIteratorTests.this.loopWithCloneIterator(); - } - }; - } - - /** - * use a clone iterator to loop over the "slow" collection and copy its - * contents to the concurrent collection - */ - void loopWithCloneIterator() { - for (Iterator<String> stream = this.buildCloneIterator(); stream.hasNext();) { - this.concurrentCollection.add(stream.next()); - } - } - - private void verifyRemove(Iterator<String> iterator) { - Object removed = "three"; - assertTrue(this.originalCollection.contains(removed)); - // try to remove before calling #next() - boolean exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - while (iterator.hasNext()) { - if (iterator.next().equals(removed)) { - iterator.remove(); - // try to remove twice - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - } - assertFalse(this.originalCollection.contains(removed)); - } - - private Iterator<String> buildCloneIterator() { - return this.buildCloneIterator(this.originalCollection); - } - - private Iterator<String> buildCloneIterator(Collection<String> c) { - return new CloneIterator<String>(c); - } - - private Collection<String> buildCollection() { - Collection<String> c = this.buildEmptyCollection(); - this.populateCollection(c); - return c; - } - - protected Collection<String> buildEmptyCollection() { - return new ArrayList<String>(); - } - - private void populateCollection(Collection<String> c) { - c.add("one"); - c.add("two"); - c.add("three"); - c.add("four"); - c.add("five"); - c.add("six"); - c.add("seven"); - c.add("eight"); - } - - // ********** custom collection ********** - static class SlowCollection<E> extends ArrayList<E> { - private static final long serialVersionUID = 1L; - private boolean hasStartedClone = false; - - public SlowCollection() { - super(); - } - - @Override - public Object[] toArray() { - this.setHasStartedClone(true); - // take a little snooze before returning the array - TestTools.sleep(100); - return super.toArray(); - } - - synchronized void setHasStartedClone(boolean hasStartedClone) { - this.hasStartedClone = hasStartedClone; - } - - synchronized boolean hasStartedClone() { - return this.hasStartedClone; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CloneListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CloneListIteratorTests.java deleted file mode 100644 index 0f3a841306..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CloneListIteratorTests.java +++ /dev/null @@ -1,397 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.iterators.CloneListIterator; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CloneListIteratorTests - extends MultiThreadedTestCase -{ - List<String> originalList; - - private List<String> concurrentList; - - public CloneListIteratorTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.originalList = this.buildList(); - } - - public void testHasNext() { - int originalSize = this.originalList.size(); - int i = 0; - for (ListIterator<String> stream = this.buildCloneListIterator(); stream.hasNext();) { - stream.next(); - // should allow concurrent modification - this.originalList.add("foo"); - i++; - } - assertTrue(originalSize != this.originalList.size()); - assertEquals(originalSize, i); - } - - public void testNext() { - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - for (ListIterator<String> stream = this.buildCloneListIterator(); stream.hasNext();) { - assertEquals("bogus element", nestedListIterator.next(), stream.next()); - } - } - - public void testIndex() { - ListIterator<String> cloneListIterator = this.buildCloneListIterator(); - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - for (int i = 0; i < 7; i++) { - nestedListIterator.next(); - cloneListIterator.next(); - assertEquals("bogus index", nestedListIterator.nextIndex(), cloneListIterator.nextIndex()); - assertEquals("bogus index", nestedListIterator.previousIndex(), cloneListIterator.previousIndex()); - } - - for (int i = 0; i < 3; i++) { - nestedListIterator.previous(); - cloneListIterator.previous(); - assertEquals("bogus index", nestedListIterator.nextIndex(), cloneListIterator.nextIndex()); - assertEquals("bogus index", nestedListIterator.previousIndex(), cloneListIterator.previousIndex()); - } - - while (nestedListIterator.hasNext()) { - nestedListIterator.next(); - cloneListIterator.next(); - assertEquals("bogus index", nestedListIterator.nextIndex(), cloneListIterator.nextIndex()); - assertEquals("bogus index", nestedListIterator.previousIndex(), cloneListIterator.previousIndex()); - } - } - - public void testHasPrevious() { - int originalSize = this.originalList.size(); - int i = 0; - ListIterator<String> stream = this.buildCloneListIterator(); - while (stream.hasNext()) { - stream.next(); - this.originalList.add("foo"); - i++; - } - assertTrue(originalSize != this.originalList.size()); - originalSize = this.originalList.size(); - while (stream.hasPrevious()) { - stream.previous(); - // should allow concurrent modification - this.originalList.add("bar"); - i--; - } - assertTrue(originalSize != this.originalList.size()); - assertEquals(0, i); - } - - public void testPrevious() { - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - ListIterator<String> stream = this.buildCloneListIterator(); - while (stream.hasNext()) { - nestedListIterator.next(); - stream.next(); - } - while (stream.hasPrevious()) { - assertEquals("bogus element", nestedListIterator.previous(), stream.previous()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - ListIterator<String> stream = this.buildCloneListIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - - exCaught = false; - while (stream.hasPrevious()) { - string = stream.previous(); - } - try { - string = stream.previous(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testModifyDefault() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildCloneListIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - - exCaught = false; - for (ListIterator<String> stream = this.buildCloneListIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.add("three and a half"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - - exCaught = false; - for (ListIterator<String> stream = this.buildCloneListIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.set("another three"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testModifyMutatorNext() { - this.verifyModifyNext(new CloneListIterator<String>(this.originalList, this.buildMutator())); - } - - public void testModifyMutatorPrevious() { - this.verifyModifyPrevious(new CloneListIterator<String>(this.originalList, this.buildMutator())); - } - - private CloneListIterator.Mutator<String> buildMutator() { - return new CloneListIterator.Mutator<String>() { - public void add(int index, String o) { - CloneListIteratorTests.this.originalList.add(index, o); - } - - public void remove(int index) { - CloneListIteratorTests.this.originalList.remove(index); - } - - public void set(int index, String o) { - CloneListIteratorTests.this.originalList.set(index, o); - } - }; - } - - public void testModifySubclassNext() { - this.verifyModifyNext(this.buildSubclass()); - } - - public void testModifySubclassPrevious() { - this.verifyModifyPrevious(this.buildSubclass()); - } - - private ListIterator<String> buildSubclass() { - return new CloneListIterator<String>(this.originalList) { - @Override - protected void add(int currentIndex, String o) { - CloneListIteratorTests.this.originalList.add(currentIndex, o); - } - - @Override - protected void remove(int currentIndex) { - CloneListIteratorTests.this.originalList.remove(currentIndex); - } - - @Override - protected void set(int currentIndex, String o) { - CloneListIteratorTests.this.originalList.set(currentIndex, o); - } - }; - } - - private void verifyModifyNext(ListIterator<String> iterator) { - String removed = "three"; - String addedAfter = "five"; - String added = "five and a half"; - String replaced = "seven"; - String replacement = "another seven"; - assertTrue(this.originalList.contains(removed)); - assertTrue(this.originalList.contains(addedAfter)); - assertTrue(this.originalList.contains(replaced)); - // try to remove before calling #next() - boolean exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - while (iterator.hasNext()) { - String next = iterator.next(); - if (next.equals(addedAfter)) { - iterator.add(added); - } - if (next.equals(removed)) { - iterator.remove(); - // try to remove twice - exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - if (next.equals(replaced)) { - iterator.set(replacement); - } - } - assertTrue(this.originalList.contains(added)); - assertFalse(this.originalList.contains(removed)); - assertFalse(this.originalList.contains(replaced)); - assertTrue(this.originalList.contains(replacement)); - } - - private void verifyModifyPrevious(ListIterator<String> iterator) { - String removed = "three"; - String addedBefore = "five"; - String added = "four and a half"; - String replaced = "seven"; - String replacement = "another seven"; - assertTrue(this.originalList.contains(removed)); - assertTrue(this.originalList.contains(addedBefore)); - assertTrue(this.originalList.contains(replaced)); - while (iterator.hasNext()) { - iterator.next(); - } - while (iterator.hasPrevious()) { - Object previous = iterator.previous(); - if (previous.equals(addedBefore)) { - iterator.add(added); - } - if (previous.equals(removed)) { - iterator.remove(); - // try to remove twice - boolean exCaught = false; - try { - iterator.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - if (previous.equals(replaced)) { - iterator.set(replacement); - } - } - assertTrue(this.originalList.contains(added)); - assertFalse(this.originalList.contains(removed)); - assertFalse(this.originalList.contains(replaced)); - assertTrue(this.originalList.contains(replacement)); - } - - private ListIterator<String> buildCloneListIterator() { - return this.buildCloneListIterator(this.originalList); - } - - private ListIterator<String> buildCloneListIterator(List<String> list) { - return new CloneListIterator<String>(list); - } - - private ListIterator<String> buildNestedListIterator() { - return this.originalList.listIterator(); - } - - private List<String> buildList() { - List<String> list = this.buildEmptyList(); - this.populateList(list); - return list; - } - - private void populateList(List<String> list) { - list.add("zero"); - list.add("one"); - list.add("two"); - list.add("three"); - list.add("four"); - list.add("five"); - list.add("six"); - list.add("seven"); - list.add("eight"); - list.add("nine"); - } - - protected List<String> buildEmptyList() { - return new ArrayList<String>(); - } - - /** - * Test concurrent access: First build a clone iterator in a separate thread - * that hangs momentarily during its construction; then modify the shared - * collection in this thread. This would cause a - * ConcurrentModificationException in the other thread if the clone iterator - * were not synchronized on the original collection. - */ - public void testConcurrentAccess() throws Exception { - CloneIteratorTests.SlowCollection<String> slow = new CloneIteratorTests.SlowCollection<String>(); - this.populateList(slow); - // using the unsynchronized list will cause the test to fail - // this.originalList = slow; - this.originalList = Collections.synchronizedList(slow); - - this.concurrentList = new ArrayList<String>(); - Thread thread = this.buildThread(this.buildRunnable()); - thread.start(); - while ( ! slow.hasStartedClone()) { - // wait for the other thread to start the clone... - Thread.yield(); - } - // ...then sneak in an extra element - this.originalList.add("seventeen"); - thread.join(); - List<String> expected = new ArrayList<String>(); - this.populateList(expected); - assertEquals(expected, this.concurrentList); - } - - private Runnable buildRunnable() { - return new TestRunnable() { - @Override - protected void run_() throws Throwable { - CloneListIteratorTests.this.loopWithCloneListIterator(); - } - }; - } - - /** - * use a clone iterator to loop over the "slow" collection and copy its - * contents to the concurrent collection - */ - void loopWithCloneListIterator() { - for (ListIterator<String> stream = this.buildCloneListIterator(); stream.hasNext();) { - this.concurrentList.add(stream.next()); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CompositeIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CompositeIteratorTests.java deleted file mode 100644 index 2a7dbd7c01..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CompositeIteratorTests.java +++ /dev/null @@ -1,351 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.CompositeIterator; - -@SuppressWarnings("nls") -public class CompositeIteratorTests extends TestCase { - - public CompositeIteratorTests(String name) { - super(name); - } - - public void testHasAnother() { - this.verifyHasAnother(this.buildCompositeIterator()); - } - - public void testHasAnother2() { - this.verifyHasAnother(this.buildCompositeIterator2()); - } - - public void testHasAnother3() { - this.verifyHasAnother(this.buildCompositeIterator3()); - } - - void verifyHasAnother(Iterator<String> stream) { - this.verifyHasAnother(8, stream); - } - - void verifyHasAnother(int expected, Iterator<String> stream) { - int i = 0; - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(expected, i); - } - - public void testAnother() { - this.verifyAnother(this.buildCompositeIterator()); - } - - public void testAnother2() { - this.verifyAnother(this.buildCompositeIterator2()); - } - - public void testAnother3() { - this.verifyAnother(this.buildCompositeIterator3()); - } - - void verifyAnother(Iterator<String> stream) { - this.verifyAnother(1, stream); - } - - void verifyAnother(int start, Iterator<String> stream) { - int index = start; - while (stream.hasNext()) { - assertEquals("bogus element", String.valueOf(index++), stream.next().substring(0, 1)); - } - } - - public void testRemove() { - this.verifyRemove(); - } - - protected void verifyRemove() { - List<String> list1 = this.buildList1(); - Object lastElement1 = list1.get(list1.size() - 1); - List<String> list2 = this.buildList2(); - List<String> list3 = this.buildList3(); - - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(list1.listIterator()); - list.add(list2.listIterator()); - list.add(list3.listIterator()); - - Iterator<String> stream = this.buildCompositeIterator(list.listIterator()); - while (stream.hasNext()) { - Object next = stream.next(); - if (next.equals("333")) { - stream.remove(); - } - // test special case - where we are between iterators - if (next.equals(lastElement1)) { - // this will trigger the next iterator to be loaded - stream.hasNext(); - // now try to remove from the previous iterator - stream.remove(); - } - } - stream.remove(); - - assertEquals("nothing removed from collection 1", this.buildList1().size() - 2, list1.size()); - assertFalse("element still in collection 1", list1.contains("333")); - assertFalse("last element still in collection 1", list1.contains(lastElement1)); - assertTrue("wrong element removed from collection 1", list1.contains("22")); - - assertEquals("nothing removed from collection 3", this.buildList3().size() - 1, list3.size()); - assertFalse("element still in collection 3", list3.contains("88888888")); - assertTrue("wrong element removed from collection 3", list3.contains("666666")); - } - - public void testSingleElement() { - String item = "0"; - this.verifyHasAnother(9, this.buildCompositeIterator(item, this.buildCompositeIterator())); - this.verifyAnother(0, this.buildCompositeIterator(item, this.buildCompositeIterator())); - } - - public void testNoSuchElementException() { - this.verifyNoSuchElementException(this.buildCompositeIterator()); - } - - void verifyNoSuchElementException(Iterator<String> stream) { - boolean exCaught = false; - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testUnsupportedOperationException() { - this.verifyUnsupportedOperationException(this.buildUnmodifiableCompositeIterator()); - } - - void verifyUnsupportedOperationException(Iterator<String> stream) { - boolean exCaught = false; - while (stream.hasNext()) { - Object string = stream.next(); - if (string.equals("333")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testIllegalStateException() { - this.verifyIllegalStateException(); - } - - void verifyIllegalStateException() { - this.verifyIllegalStateException(this.buildCompositeIterator()); - } - - void verifyIllegalStateException(Iterator<String> stream) { - boolean exCaught = false; - try { - stream.remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - - public void testEmptyHasAnother1() { - this.verifyEmptyHasAnother(this.buildEmptyCompositeIterator1()); - } - - void verifyEmptyHasAnother(Iterator<String> stream) { - int i = 0; - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(0, i); - } - - public void testEmptyNoSuchElementException1() { - this.verifyNoSuchElementException(this.buildEmptyCompositeIterator1()); - } - - public void testEmptyIllegalStateException1() { - this.verifyEmptyIllegalStateException1(); - } - - void verifyEmptyIllegalStateException1() { - this.verifyIllegalStateException(this.buildEmptyCompositeIterator1()); - } - - public void testEmptyHasAnother2() { - this.verifyEmptyHasAnother(this.buildEmptyCompositeIterator2()); - } - - public void testEmptyNoSuchElementException2() { - this.verifyNoSuchElementException(this.buildEmptyCompositeIterator2()); - } - - public void testEmptyIllegalStateException2() { - this.verifyEmptyIllegalStateException2(); - } - - void verifyEmptyIllegalStateException2() { - this.verifyIllegalStateException(this.buildEmptyCompositeIterator2()); - } - - Iterator<String> buildCompositeIterator() { - return this.buildCompositeIterator(this.buildIterators()); - } - - Iterator<String> buildEmptyCompositeIterator1() { - return this.buildCompositeIterator(this.buildEmptyIterators1()); - } - - Iterator<String> buildEmptyCompositeIterator2() { - return this.buildCompositeIterator(this.buildEmptyIterators2()); - } - - Iterator<String> buildUnmodifiableCompositeIterator() { - return this.buildCompositeIterator(this.buildUnmodifiableIterators()); - } - - // leave unchecked so we can override in subclass - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator(Iterator iterators) { - return new CompositeIterator<String>(iterators); - } - - // use vararg constructor - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator2() { - return new CompositeIterator<String>(this.buildIterator1(), this.buildIterator2(), this.buildIterator3()); - } - - // use vararg constructor - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator3() { - return new CompositeIterator<String>(new Iterator[] { this.buildIterator1(), this.buildIterator2(), this.buildIterator3() }); - } - - Iterator<String> buildCompositeIterator(String string, Iterator<String> iterator) { - return new CompositeIterator<String>(string, iterator); - } - - ListIterator<Iterator<String>> buildIterators() { - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(this.buildIterator1()); - list.add(this.buildIterator2()); - list.add(this.buildIterator3()); - return list.listIterator(); - } - - ListIterator<Iterator<String>> buildEmptyIterators1() { - return this.buildEmptyIteratorIterator(); - } - - ListIterator<Iterator<String>> buildEmptyIterators2() { - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(this.buildEmptyStringIterator()); - list.add(this.buildEmptyStringIterator()); - list.add(this.buildEmptyStringIterator()); - return list.listIterator(); - } - - ListIterator<Iterator<String>> buildUnmodifiableIterators() { - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(this.buildUnmodifiableIterator1()); - list.add(this.buildUnmodifiableIterator2()); - list.add(this.buildUnmodifiableIterator3()); - return list.listIterator(); - } - - ListIterator<String> buildIterator1() { - return this.buildList1().listIterator(); - } - - ListIterator<String> buildIterator2() { - return this.buildList2().listIterator(); - } - - ListIterator<String> buildIterator3() { - return this.buildList3().listIterator(); - } - - ListIterator<String> buildUnmodifiableIterator1() { - return this.buildUnmodifiableList1().listIterator(); - } - - ListIterator<String> buildUnmodifiableIterator2() { - return this.buildUnmodifiableList2().listIterator(); - } - - ListIterator<String> buildUnmodifiableIterator3() { - return this.buildUnmodifiableList3().listIterator(); - } - - ListIterator<Iterator<String>> buildEmptyIteratorIterator() { - return (new ArrayList<Iterator<String>>()).listIterator(); - } - - ListIterator<String> buildEmptyStringIterator() { - return (new ArrayList<String>()).listIterator(); - } - - List<String> buildList1() { - List<String> list = new ArrayList<String>(); - list.add("1"); - list.add("22"); - list.add("333"); - list.add("4444"); - return list; - } - - List<String> buildList2() { - return new ArrayList<String>(); - } - - List<String> buildList3() { - List<String> list = new ArrayList<String>(); - list.add("55555"); - list.add("666666"); - list.add("7777777"); - list.add("88888888"); - return list; - } - - List<String> buildUnmodifiableList1() { - return Collections.unmodifiableList(this.buildList1()); - } - - List<String> buildUnmodifiableList2() { - return Collections.unmodifiableList(this.buildList2()); - } - - List<String> buildUnmodifiableList3() { - return Collections.unmodifiableList(this.buildList3()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CompositeListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CompositeListIteratorTests.java deleted file mode 100644 index 5544e86355..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/CompositeListIteratorTests.java +++ /dev/null @@ -1,331 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import org.eclipse.jpt.common.utility.internal.iterators.CompositeListIterator; - -@SuppressWarnings("nls") -public class CompositeListIteratorTests extends ReadOnlyCompositeListIteratorTests { - - public CompositeListIteratorTests(String name) { - super(name); - } - - @Override - public void testRemove() { - super.testRemove(); - List<String> list1 = this.buildList1(); - List<String> list2 = this.buildList2(); - List<String> list3 = this.buildList3(); - Object firstElement3 = list3.get(0); - - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(list1.listIterator()); - list.add(list2.listIterator()); - list.add(list3.listIterator()); - - ListIterator<String> stream = (ListIterator<String>) this.buildCompositeIterator(list.listIterator()); - // position to end of stream - while (stream.hasNext()) { - stream.next(); - } - while (stream.hasPrevious()) { - Object previous = stream.previous(); - if (previous.equals("333")) { - stream.remove(); - } - // test special case - where we are between iterators - if (previous.equals(firstElement3)) { - // this will trigger the next iterator to be loaded - stream.hasPrevious(); - // now try to remove from the previous iterator - stream.remove(); - } - } - stream.remove(); - - assertEquals("nothing removed from collection 1", this.buildList1().size() - 2, list1.size()); - assertFalse("element still in collection 1", list1.contains("1")); - assertFalse("element still in collection 1", list1.contains("333")); - - assertEquals("nothing removed from collection 3", this.buildList3().size() - 1, list3.size()); - assertFalse("first element still in collection 3", list3.contains(firstElement3)); - assertTrue("wrong element removed from collection 3", list3.contains("666666")); - } - - public void testAdd() { - List<String> list1 = this.buildList1(); - Object lastElement1 = list1.get(list1.size() - 1); - List<String> list2 = this.buildList2(); - List<String> list3 = this.buildList3(); - Object firstElement3 = list3.get(0); - - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(list1.listIterator()); - list.add(list2.listIterator()); - list.add(list3.listIterator()); - - ListIterator<String> stream = (ListIterator<String>) this.buildCompositeIterator(list.listIterator()); - while (stream.hasNext()) { - Object next = stream.next(); - if (next.equals("333")) { - stream.add("3.5"); - } - // test special case - where we are between iterators - if (next.equals(lastElement1)) { - // this will trigger the next iterator to be loaded - stream.hasNext(); - // now try to add to the iterator - stream.add("something in 3"); - } - } - stream.add("finale"); - boolean checkForFinale = true; - while (stream.hasPrevious()) { - Object previous = stream.previous(); - if (checkForFinale) { - checkForFinale = false; - assertEquals("added element dropped", "finale", previous); - } - if (previous.equals("333")) { - stream.add("2.5"); - } - // test special case - where we are between iterators - if (previous.equals(firstElement3)) { - // this will trigger the next iterator to be loaded - stream.hasPrevious(); - // now try to remove from the previous iterator - stream.add("old start of 3"); - } - } - stream.add("prelude"); - assertEquals("added element dropped", "prelude", stream.previous()); - - assertEquals("elements not added to collection 1", this.buildList1().size() + 3, list1.size()); - assertEquals("element not added to collection 1", "prelude", list1.get(0)); - assertEquals("element not added to collection 1", "2.5", list1.get(3)); - assertEquals("element not added to collection 1", "3.5", list1.get(5)); - - assertEquals("elements not added to collection 3", this.buildList3().size() + 3, list3.size()); - assertEquals("element not added to collection 3", "something in 3", list3.get(0)); - assertEquals("element not added to collection 3", "old start of 3", list3.get(1)); - assertEquals("element not added to collection 3", "finale", list3.get(list3.size() - 1)); - - // add to the front - stream = (ListIterator<String>) this.buildCompositeIterator(); - stream.add("blah"); - assertFalse("added element should be placed BEFORE the \"cursor\"", stream.next().equals("blah")); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - stream.add("blah"); - assertTrue("added element should be placed BEFORE the \"cursor\"", stream.previous().equals("blah")); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - while (stream.hasNext()) { - stream.next(); - } - while (stream.hasPrevious()) { - stream.previous(); - } - stream.add("blah"); - assertFalse("added element should be placed BEFORE the \"cursor\"", stream.next().equals("blah")); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - while (stream.hasNext()) { - stream.next(); - } - while (stream.hasPrevious()) { - stream.previous(); - } - stream.add("blah"); - assertTrue("added element should be placed BEFORE the \"cursor\"", stream.previous().equals("blah")); - - // add to the middle - stream = (ListIterator<String>) this.buildCompositeIterator(); - stream.next(); - stream.add("blah"); - assertFalse("added element should be placed BEFORE the \"cursor\"", stream.next().equals("blah")); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - stream.next(); - stream.add("blah"); - assertTrue("added element should be placed BEFORE the \"cursor\"", stream.previous().equals("blah")); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - while (stream.hasNext()) { - stream.next(); - } - stream.previous(); - stream.add("blah"); - assertFalse("added element should be placed BEFORE the \"cursor\"", stream.next().equals("blah")); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - while (stream.hasNext()) { - stream.next(); - } - stream.previous(); - stream.add("blah"); - assertTrue("added element should be placed BEFORE the \"cursor\"", stream.previous().equals("blah")); - - // add to the end - stream = (ListIterator<String>) this.buildCompositeIterator(); - while (stream.hasNext()) { - stream.next(); - } - stream.add("blah"); - assertFalse("added element should be placed BEFORE the \"cursor\"", stream.hasNext()); - - stream = (ListIterator<String>) this.buildCompositeIterator(); - while (stream.hasNext()) { - stream.next(); - } - stream.add("blah"); - assertTrue("added element should be placed BEFORE the \"cursor\"", stream.previous().equals("blah")); - } - - public void testSet() { - List<String> list1 = this.buildList1(); - Object lastElement1 = list1.get(list1.size() - 1); - List<String> list2 = this.buildList2(); - List<String> list3 = this.buildList3(); - Object firstElement3 = list3.get(0); - - List<Iterator<String>> list = new ArrayList<Iterator<String>>(); - list.add(list1.listIterator()); - list.add(list2.listIterator()); - list.add(list3.listIterator()); - - ListIterator<String> stream = (ListIterator<String>) this.buildCompositeIterator(list.listIterator()); - // position to end of stream - while (stream.hasNext()) { - Object next = stream.next(); - if (next.equals("333")) { - stream.set("333a"); - } - // test special case - where we are between iterators - if (next.equals(lastElement1)) { - // this will trigger the next iterator to be loaded - stream.hasNext(); - // now try to remove from the previous iterator - stream.set("end of 1"); - } - } - while (stream.hasPrevious()) { - Object previous = stream.previous(); - if (previous.equals("22")) { - stream.set("22a"); - } - // test special case - where we are between iterators - if (previous.equals(firstElement3)) { - // this will trigger the next iterator to be loaded - stream.hasPrevious(); - // now try to remove from the previous iterator - stream.set("start of 3"); - } - } - - assertEquals("element(s) added to collection 1", this.buildList1().size(), list1.size()); - assertEquals("element not set in collection 1", "22a", list1.get(1)); - assertFalse("element not set in collection 1", list1.contains("22")); - assertEquals("element not set in collection 1", "333a", list1.get(2)); - assertFalse("element not set in collection 1", list1.contains("333")); - assertEquals("element not set in collection 1", "end of 1", list1.get(list1.size() - 1)); - assertFalse("element not set in collection 1", list1.contains(lastElement1)); - - assertEquals("element(s) added to collection 3", this.buildList3().size(), list3.size()); - assertEquals("element not set in collection 3", "start of 3", list3.get(0)); - assertFalse("element not set in collection 3", list3.contains(firstElement3)); - } - - @Override - public void testNextIndexPreviousIndex() { - int i = 0; - ListIterator<String> stream = (ListIterator<String>) this.buildCompositeIterator(); - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - while (stream.hasNext()) { - Object next = stream.next(); - i++; - if (next.equals("333")) { - stream.remove(); - i--; - } - if (next.equals("7777777")) { - stream.add("7.5"); - i++; - } - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - } - assertEquals("index is corrupt", 8, i); - - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - while (stream.hasPrevious()) { - Object previous = stream.previous(); - i--; - if (previous.equals("666666")) { - stream.remove(); - // removing a previous element, does not change the cursor - } - if (previous.equals("22")) { - stream.add("1.5"); - i++; - } - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - } - assertEquals("index is corrupt", 0, i); - } - - @Override - public void testIllegalStateException() { - this.verifyIllegalStateException(); - } - - @Override - public void testEmptyIllegalStateException1() { - this.verifyEmptyIllegalStateException1(); - } - - @Override - public void testEmptyIllegalStateException2() { - this.verifyEmptyIllegalStateException2(); - } - - // unchecked so we can override the unchecked method in superclass - @Override - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator(Iterator iterators) { - return new CompositeListIterator<String>((ListIterator<ListIterator<String>>) iterators); - } - - @Override - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator2() { - return new CompositeListIterator<String>(this.buildIterator1(), this.buildIterator2(), this.buildIterator3()); - } - - @Override - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator3() { - return new CompositeListIterator<String>(new ListIterator[] { this.buildIterator1(), this.buildIterator2(), this.buildIterator3() }); - } - - @Override - ListIterator<String> buildCompositeListIterator(String string, ListIterator<String> iterator) { - return new CompositeListIterator<String>(string, iterator); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EmptyIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EmptyIteratorTests.java deleted file mode 100644 index 511e484849..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EmptyIteratorTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.EmptyIterator; - -@SuppressWarnings("nls") -public class EmptyIteratorTests extends TestCase { - - public EmptyIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<Object> stream = EmptyIterator.instance(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(0, i); - } - - public void testNext() { - for (Iterator<String> stream = EmptyIterator.instance(); stream.hasNext();) { - fail("bogus element: " + stream.next()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<Number> stream = EmptyIterator.instance(); - Object element = null; - while (stream.hasNext()) { - element = stream.next(); - } - try { - element = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + element, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - try { - EmptyIterator.instance().remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EmptyListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EmptyListIteratorTests.java deleted file mode 100644 index 1892415b13..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EmptyListIteratorTests.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ListIterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.EmptyListIterator; - -@SuppressWarnings("nls") -public class EmptyListIteratorTests extends TestCase { - - public EmptyListIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (ListIterator<Object> stream = EmptyListIterator.instance(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(0, i); - } - - public void testNext() { - for (ListIterator<Object> stream = EmptyListIterator.instance(); stream.hasNext();) { - fail("bogus element: " + stream.next()); - } - } - - public void testNextIndex() { - ListIterator<Object> stream = EmptyListIterator.instance(); - assertEquals(0, stream.nextIndex()); - } - - public void testHasPrevious() { - ListIterator<Object> stream = EmptyListIterator.instance(); - int i = 0; - while (stream.hasPrevious()) { - stream.previous(); - i++; - } - assertEquals(0, i); - - while (stream.hasNext()) { - stream.next(); - } - i = 0; - while (stream.hasPrevious()) { - stream.previous(); - i++; - } - assertEquals(0, i); - } - - public void testPrevious() { - ListIterator<Object> stream = EmptyListIterator.instance(); - while (stream.hasPrevious()) { - fail("bogus element: " + stream.previous()); - } - while (stream.hasNext()) { - stream.next(); - } - while (stream.hasPrevious()) { - fail("bogus element: " + stream.previous()); - } - } - - public void testPreviousIndex() { - ListIterator<Object> stream = EmptyListIterator.instance(); - assertEquals(-1, stream.previousIndex()); - } - - public void testNoSuchElementException() { - boolean exCaught = false; - ListIterator<Object> stream = EmptyListIterator.instance(); - Object element = null; - while (stream.hasNext()) { - element = stream.next(); - } - try { - element = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown (next): " + element, exCaught); - while (stream.hasPrevious()) { - element = stream.previous(); - } - try { - element = stream.previous(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown (previous): " + element, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - try { - EmptyListIterator.instance().remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("UnsupportedOperationException not thrown (remove)", exCaught); - try { - EmptyListIterator.instance().set(new Object()); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("UnsupportedOperationException not thrown (set)", exCaught); - try { - EmptyListIterator.instance().add(new Object()); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("UnsupportedOperationException not thrown (add)", exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EnumerationIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EnumerationIteratorTests.java deleted file mode 100644 index a7c7d289e6..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/EnumerationIteratorTests.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Enumeration; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Vector; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.EnumerationIterator; - -@SuppressWarnings("nls") -public class EnumerationIteratorTests extends TestCase { - - public EnumerationIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(this.buildVector().size(), i); - } - - public void testHasNextUpcast() { - int i = 0; - for (Iterator<Object> stream = this.buildIteratorUpcast(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(this.buildVector().size(), i); - } - - public void testNext() { - Enumeration<String> enumeration = this.buildEnumeration(); - for (Iterator<String> stream = this.buildIterator(); stream.hasNext();) { - assertEquals("bogus element", enumeration.nextElement(), stream.next()); - } - } - - public void testNextUpcast() { - Enumeration<String> enumeration = this.buildEnumeration(); - for (Iterator<Object> stream = this.buildIteratorUpcast(); stream.hasNext();) { - assertEquals("bogus element", enumeration.nextElement(), stream.next()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - private Iterator<String> buildIterator() { - return this.buildIterator(this.buildEnumeration()); - } - - private Iterator<String> buildIterator(Enumeration<String> enumeration) { - return new EnumerationIterator<String>(enumeration); - } - - private Enumeration<String> buildEnumeration() { - return this.buildVector().elements(); - } - - private Vector<String> buildVector() { - Vector<String> v = new Vector<String>(); - v.addElement("one"); - v.addElement("two"); - v.addElement("three"); - v.addElement("four"); - v.addElement("five"); - v.addElement("six"); - v.addElement("seven"); - v.addElement("eight"); - return v; - } - - private Iterator<Object> buildIteratorUpcast() { - return this.buildIteratorUpcast(this.buildEnumeration()); - } - - private Iterator<Object> buildIteratorUpcast(Enumeration<String> enumeration) { - return new EnumerationIterator<Object>(enumeration); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/FilteringIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/FilteringIteratorTests.java deleted file mode 100644 index 6fe920b713..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/FilteringIteratorTests.java +++ /dev/null @@ -1,266 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.Filter; -import org.eclipse.jpt.common.utility.internal.SimpleFilter; -import org.eclipse.jpt.common.utility.internal.iterators.FilteringIterator; - -@SuppressWarnings("nls") -public class FilteringIteratorTests extends TestCase { - - private static final String PREFIX = "prefix"; - - public FilteringIteratorTests(String name) { - super(name); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildAcceptIterator(); stream.hasNext();) { - String string = stream.next(); - if (string.equals(PREFIX + "3")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildAcceptIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testAcceptHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildAcceptIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(6, i); - } - - public void testAcceptNext() { - for (Iterator<String> stream = this.buildAcceptIterator(); stream.hasNext();) { - assertTrue("bogus accept", stream.next().startsWith(PREFIX)); - } - } - - public void testInnerHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildInnerIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(6, i); - } - - public void testInnerNext() { - for (Iterator<String> stream = this.buildInnerIterator(); stream.hasNext();) { - assertTrue("bogus accept", stream.next().startsWith(PREFIX)); - } - } - - public void testRejectHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildRejectIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(2, i); - } - - public void testRejectNext() { - for (Iterator<String> stream = this.buildRejectIterator(); stream.hasNext();) { - assertFalse("bogus reject", stream.next().startsWith(PREFIX)); - } - } - - public void testBothHasNext() { - // if both accept() and reject() are overridden, accept() is used - int i = 0; - for (Iterator<String> stream = this.buildBothIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(6, i); - } - - public void testLoadNext() { - // loadNext() used to cause a NPE when executing during the - // constructor because the "outer" class is not bound until completion - // of the constructor - for (Iterator<String> stream = this.buildInnerIterator2(); stream.hasNext();) { - assertTrue("bogus accept", stream.next().startsWith(PREFIX)); - } - } - - public void testFilterHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildFilterIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(6, i); - } - - public void testFilterNext() { - for (Iterator<String> stream = this.buildFilterIterator(); stream.hasNext();) { - assertTrue("bogus accept", stream.next().startsWith(PREFIX)); - } - } - - private Iterator<String> buildFilteredIterator(Iterator<String> nestedIterator, Filter<String> filter) { - return new FilteringIterator<String>(nestedIterator, filter); - } - - private Iterator<String> buildInnerFilteredIterator(Iterator<String> nestedIterator) { - return new FilteringIterator<String>(nestedIterator) { - @Override - protected boolean accept(String s) { - return s.startsWith(PREFIX); - } - }; - } - - String getPrefix() { - return PREFIX; - } - - // this inner iterator will call the "outer" object - private Iterator<String> buildInnerFilteredIterator2(Iterator<String> nestedIterator) { - return new FilteringIterator<String>(nestedIterator) { - @Override - protected boolean accept(String s) { - return s.startsWith(FilteringIteratorTests.this.getPrefix()); - } - }; - } - - private Iterator<String> buildNestedIterator() { - Collection<String> c = new ArrayList<String>(); - c.add(PREFIX + "1"); - c.add(PREFIX + "2"); - c.add(PREFIX + "3"); - c.add("4"); - c.add(PREFIX + "5"); - c.add(PREFIX + "6"); - c.add(PREFIX + "7"); - c.add("8"); - return c.iterator(); - } - - private Iterator<String> buildAcceptIterator() { - return this.buildFilteredIterator(this.buildNestedIterator(), this.buildAcceptFilter(PREFIX)); - } - - private Iterator<String> buildInnerIterator() { - return this.buildInnerFilteredIterator(this.buildNestedIterator()); - } - - // this inner iterator will call the "outer" object - private Iterator<String> buildInnerIterator2() { - return this.buildInnerFilteredIterator2(this.buildNestedIterator()); - } - - private Iterator<String> buildFilterIterator() { - return this.buildFilteredIterator(this.buildNestedIterator(), this.buildFilterFilter(PREFIX)); - } - - private Filter<String> buildAcceptFilter(String prefix) { - return new SimpleFilter<String, String>(prefix) { - private static final long serialVersionUID = 1L; - - @Override - public boolean accept(String s) { - return s.startsWith(this.criterion); - } - }; - } - - private Iterator<String> buildRejectIterator() { - return this.buildFilteredIterator(this.buildNestedIterator(), this.buildRejectFilter(PREFIX)); - } - - private Filter<String> buildRejectFilter(String prefix) { - return new SimpleFilter<String, String>(prefix) { - private static final long serialVersionUID = 1L; - - @Override - public boolean reject(String s) { - return s.startsWith(this.criterion); - } - }; - } - - // use anonymous inner Filter - private Filter<String> buildFilterFilter(final String prefix) { - return new Filter<String>() { - public boolean accept(String s) { - return s.startsWith(prefix); - } - }; - } - - private Iterator<String> buildBothIterator() { - return this.buildFilteredIterator(this.buildNestedIterator(), this.buildBothFilter(PREFIX)); - } - - private Filter<String> buildBothFilter(String prefix) { - return new SimpleFilter<String, String>(prefix) { - private static final long serialVersionUID = 1L; - - @Override - public boolean reject(String s) { - return s.startsWith(this.criterion); - } - - @Override - public boolean accept(String s) { - return s.startsWith(this.criterion); - } - }; - } - - public void testInvalidFilteringIterator() { - boolean exCaught = false; - try { - // missing method override - Iterator<String> iterator = new FilteringIterator<String>(this.buildNestedIterator()); - String s = iterator.next(); - fail("invalid string: " + s); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/GraphIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/GraphIteratorTests.java deleted file mode 100644 index e320f28988..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/GraphIteratorTests.java +++ /dev/null @@ -1,197 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.GraphIterator; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class GraphIteratorTests extends TestCase { - /** this will be populated with all the nodes created for the test */ - Collection<GraphNode> nodes = new ArrayList<GraphNode>(); - - public GraphIteratorTests(String name) { - super(name); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testHasNext1() { - this.verifyHasNext(this.buildGraphIterator1()); - } - - public void testHasNext2() { - this.verifyHasNext(this.buildGraphIterator2()); - } - - private void verifyHasNext(Iterator<GraphNode> iterator) { - int i = 0; - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(this.nodes.size(), i); - } - - public void testNext1() { - this.verifyNext(this.buildGraphIterator1()); - } - - public void testNext2() { - this.verifyNext(this.buildGraphIterator2()); - } - - private void verifyNext(Iterator<GraphNode> iterator) { - while (iterator.hasNext()) { - assertTrue("bogus element", this.nodes.contains(iterator.next())); - } - } - - public void testNoSuchElementException1() { - this.verifyNoSuchElementException(this.buildGraphIterator1()); - } - - public void testNoSuchElementException2() { - this.verifyNoSuchElementException(this.buildGraphIterator2()); - } - - private void verifyNoSuchElementException(Iterator<GraphNode> iterator) { - boolean exCaught = false; - while (iterator.hasNext()) { - iterator.next(); - } - try { - iterator.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - - public void testSize1() { - this.verifySize(this.buildGraphIterator1()); - } - - public void testSize2() { - this.verifySize(this.buildGraphIterator2()); - } - - private void verifySize(Iterator<GraphNode> iterator) { - int iteratorSize = CollectionTools.size(iterator); - int actualSize = this.nodes.size(); - assertTrue("Too few items in iterator.", iteratorSize >= actualSize); - assertTrue("Too many items in iterator.", iteratorSize <= actualSize); - } - - public void testInvalidGraphIterator() { - boolean exCaught = false; - try { - // missing method override - Iterator<GraphNode> iterator = new GraphIterator<GraphNode>(this.buildGraphRoot()); - GraphNode gn = iterator.next(); - fail("invalid graph node: " + gn); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - - /** - * build a graph iterator with an explicit misterRogers - */ - private Iterator<GraphNode> buildGraphIterator1() { - return new GraphIterator<GraphNode>(this.buildGraphRoot(), this.buildMisterRogers()); - } - - private GraphIterator.MisterRogers<GraphNode> buildMisterRogers() { - return new GraphIterator.MisterRogers<GraphNode>() { - public Iterator<GraphNode> neighbors(GraphNode next) { - return next.neighbors(); - } - }; - } - - /** - * build a graph iterator with an override - */ - private Iterator<GraphNode> buildGraphIterator2() { - return new GraphIterator<GraphNode>(this.buildGraphRoot()) { - @Override - public Iterator<GraphNode> neighbors(GraphNode next) { - return next.neighbors(); - } - }; - } - - private GraphNode buildGraphRoot() { - GraphNode ncNode = new GraphNode("North Carolina"); - GraphNode vaNode = new GraphNode("Virginia"); - GraphNode scNode = new GraphNode("South Carolina"); - GraphNode gaNode = new GraphNode("Georgia"); - GraphNode flNode = new GraphNode("Florida"); - GraphNode alNode = new GraphNode("Alabama"); - GraphNode msNode = new GraphNode("Mississippi"); - GraphNode tnNode = new GraphNode("Tennessee"); - - ncNode.setNeighbors(new GraphNode[] { vaNode, scNode, gaNode, tnNode }); - vaNode.setNeighbors(new GraphNode[] { ncNode, tnNode }); - scNode.setNeighbors(new GraphNode[] { ncNode, gaNode }); - gaNode.setNeighbors(new GraphNode[] { ncNode, scNode, flNode, alNode, tnNode }); - flNode.setNeighbors(new GraphNode[] { gaNode }); - alNode.setNeighbors(new GraphNode[] { gaNode, msNode, tnNode }); - msNode.setNeighbors(new GraphNode[] { alNode, tnNode }); - tnNode.setNeighbors(new GraphNode[] { vaNode, ncNode, gaNode, alNode, msNode }); - - return ncNode; - } - - public class GraphNode { - private String name; - - private Collection<GraphNode> neighbors = new ArrayList<GraphNode>(); - - public GraphNode(String name) { - super(); - GraphIteratorTests.this.nodes.add(this); // log node - this.name = name; - } - - public String getName() { - return this.name; - } - - void setNeighbors(GraphNode[] neighbors) { - this.neighbors = CollectionTools.list(neighbors); - } - - public Iterator<GraphNode> neighbors() { - return this.neighbors.iterator(); - } - - public int neighborsSize() { - return this.neighbors.size(); - } - - @Override - public String toString() { - return "GraphNode(" + this.name + ")"; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/JptUtilityIteratorsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/JptUtilityIteratorsTests.java deleted file mode 100644 index 54fb276ecb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/JptUtilityIteratorsTests.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * decentralize test creation code - */ -public class JptUtilityIteratorsTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityIteratorsTests.class.getPackage().getName()); - - suite.addTestSuite(ArrayIteratorTests.class); - suite.addTestSuite(ArrayListIteratorTests.class); - suite.addTestSuite(ChainIteratorTests.class); - suite.addTestSuite(CloneIteratorTests.class); - suite.addTestSuite(CloneListIteratorTests.class); - suite.addTestSuite(CompositeIteratorTests.class); - suite.addTestSuite(CompositeListIteratorTests.class); - suite.addTestSuite(EmptyIteratorTests.class); - suite.addTestSuite(EmptyListIteratorTests.class); - suite.addTestSuite(EnumerationIteratorTests.class); - suite.addTestSuite(FilteringIteratorTests.class); - suite.addTestSuite(SuperIteratorWrapperTests.class); - suite.addTestSuite(GraphIteratorTests.class); - suite.addTestSuite(PeekableIteratorTests.class); - suite.addTestSuite(ReadOnlyCompositeListIteratorTests.class); - suite.addTestSuite(ReadOnlyIteratorTests.class); - suite.addTestSuite(ReadOnlyListIteratorTests.class); - suite.addTestSuite(SingleElementIteratorTests.class); - suite.addTestSuite(SingleElementListIteratorTests.class); - suite.addTestSuite(SynchronizedIteratorTests.class); - suite.addTestSuite(SynchronizedListIteratorTests.class); - suite.addTestSuite(TransformationIteratorTests.class); - suite.addTestSuite(TransformationListIteratorTests.class); - suite.addTestSuite(TreeIteratorTests.class); - - return suite; - } - - private JptUtilityIteratorsTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/PeekableIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/PeekableIteratorTests.java deleted file mode 100644 index 00a056f9a2..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/PeekableIteratorTests.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.PeekableIterator; - -@SuppressWarnings("nls") -public class PeekableIteratorTests extends TestCase { - - public PeekableIteratorTests(String name) { - super(name); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildPeekableIterator(); stream.hasNext();) { - String string = stream.next(); - if (string.equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildPeekableIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildPeekableIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(6, i); - } - - public void testHasNextUpcast() { - int i = 0; - for (Iterator<Object> stream = this.buildPeekableIteratorUpcast(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(6, i); - } - - public void testNext() { - Iterator<String> stream = this.buildPeekableIterator(); - assertEquals("zero", stream.next()); - assertEquals("one", stream.next()); - assertEquals("two", stream.next()); - assertEquals("three", stream.next()); - assertEquals("four", stream.next()); - assertEquals("five", stream.next()); - } - - public void testNextUpcast() { - Iterator<Object> stream = this.buildPeekableIteratorUpcast(); - assertEquals("zero", stream.next()); - assertEquals("one", stream.next()); - assertEquals("two", stream.next()); - assertEquals("three", stream.next()); - assertEquals("four", stream.next()); - assertEquals("five", stream.next()); - } - - public void testPeek() { - Object next = null; - for (PeekableIterator<String> stream = this.buildPeekableIterator(); stream.hasNext();) { - Object peek = stream.peek(); - assertTrue("peek and next are prematurely identical", peek != next); - next = stream.next(); - assertTrue("peek and next are not identical", peek == next); - } - } - - public void testPeekUpcast() { - Object next = null; - for (PeekableIterator<Object> stream = this.buildPeekableIteratorUpcast(); stream.hasNext();) { - Object peek = stream.peek(); - assertTrue("peek and next are prematurely identical", peek != next); - next = stream.next(); - assertTrue("peek and next are not identical", peek == next); - } - } - - private PeekableIterator<String> buildPeekableIterator() { - return this.buildPeekableIterator(this.buildNestedIterator()); - } - - private PeekableIterator<Object> buildPeekableIteratorUpcast() { - return this.buildPeekableIteratorUpcast(this.buildNestedIterator()); - } - - private PeekableIterator<String> buildPeekableIterator(Iterator<String> nestedIterator) { - return new PeekableIterator<String>(nestedIterator); - } - - private PeekableIterator<Object> buildPeekableIteratorUpcast(Iterator<String> nestedIterator) { - return new PeekableIterator<Object>(nestedIterator); - } - - private Iterator<String> buildNestedIterator() { - Collection<String> c = new ArrayList<String>(); - c.add("zero"); - c.add("one"); - c.add("two"); - c.add("three"); - c.add("four"); - c.add("five"); - return c.iterator(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyCompositeListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyCompositeListIteratorTests.java deleted file mode 100644 index dd1eea6db4..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyCompositeListIteratorTests.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyCompositeListIterator; - -@SuppressWarnings("nls") -public class ReadOnlyCompositeListIteratorTests extends CompositeIteratorTests { - - public ReadOnlyCompositeListIteratorTests(String name) { - super(name); - } - - @Override - void verifyHasAnother(Iterator<String> stream) { - super.verifyHasAnother(stream); - ListIterator<String> stream2 = (ListIterator<String>) stream; - int i = 0; - while (stream2.hasPrevious()) { - stream2.previous(); - i++; - } - assertEquals(8, i); - } - - @Override - void verifyAnother(Iterator<String> stream) { - super.verifyAnother(stream); - int i = 8; - ListIterator<String> stream2 = (ListIterator<String>) stream; - while (stream2.hasPrevious()) { - assertEquals("bogus element", String.valueOf(i--), stream2.previous().substring(0, 1)); - } - } - - public void testNextIndexPreviousIndex() { - int i = 0; - ListIterator<String> stream = (ListIterator<String>) this.buildCompositeIterator(); - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - while (stream.hasNext()) { - stream.next(); - i++; - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - } - assertEquals("index is corrupt", 8, i); - - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - while (stream.hasPrevious()) { - stream.previous(); - i--; - assertEquals(i, stream.nextIndex()); - assertEquals(i - 1, stream.previousIndex()); - } - assertEquals("index is corrupt", 0, i); - } - - public void testPreviousIndex() { - // TODO - } - - @Override - public void testRemove() { - // #remove() is not supported - } - - @Override - public void testIllegalStateException() { - // #remove() is not supported - } - - @Override - public void testEmptyIllegalStateException1() { - // #remove() is not supported - } - - @Override - public void testEmptyIllegalStateException2() { - // #remove() is not supported - } - - @Override - void verifyNoSuchElementException(Iterator<String> stream) { - super.verifyNoSuchElementException(stream); - ListIterator<String> stream2 = (ListIterator<String>) stream; - boolean exCaught = false; - String string = null; - while (stream2.hasPrevious()) { - string = stream2.previous(); - } - try { - string = stream2.previous(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - @Override - void verifyUnsupportedOperationException(Iterator<String> stream) { - super.verifyUnsupportedOperationException(stream); - boolean exCaught = false; - ListIterator<String> stream2 = (ListIterator<String>) stream; - while (stream2.hasPrevious()) { - Object string = stream2.previous(); - if (string.equals("333")) { - try { - stream2.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - @Override - void verifyIllegalStateException(Iterator<String> stream) { - super.verifyIllegalStateException(stream); - ListIterator<String> stream2 = (ListIterator<String>) stream; - boolean exCaught = false; - try { - stream2.set("junk"); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - - @Override - void verifyEmptyHasAnother(Iterator<String> stream) { - super.verifyEmptyHasAnother(stream); - ListIterator<String> stream2 = (ListIterator<String>) stream; - int i = 0; - while (stream2.hasPrevious()) { - stream2.previous(); - i++; - } - assertEquals(0, i); - } - - // unchecked so we can override the unchecked method in superclass - @Override - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator(Iterator iterators) { - return new ReadOnlyCompositeListIterator<String>((ListIterator<ListIterator<String>>) iterators); - } - - @Override - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator2() { - return new ReadOnlyCompositeListIterator<String>(this.buildIterator1(), this.buildIterator2(), this.buildIterator3()); - } - - @Override - @SuppressWarnings("unchecked") - Iterator<String> buildCompositeIterator3() { - return new ReadOnlyCompositeListIterator<String>(new ListIterator[] { this.buildIterator1(), this.buildIterator2(), this.buildIterator3() }); - } - - Iterator<String> buildCompositeIterator(String string, ListIterator<String> iterator) { - return this.buildCompositeListIterator(string, iterator); - } - - ListIterator<String> buildCompositeListIterator(String string, ListIterator<String> iterator) { - return new ReadOnlyCompositeListIterator<String>(string, iterator); - } - - public void testVariedNestedIterators() { - List<Integer> integerList = new ArrayList<Integer>(); - integerList.add(new Integer(42)); - integerList.add(new Integer(42)); - integerList.add(new Integer(111)); - integerList.add(new Integer(77)); - - List<Float> floatList = new ArrayList<Float>(); - floatList.add(new Float(42.42f)); - floatList.add(new Float(22.22f)); - floatList.add(new Float(111.111f)); - floatList.add(new Float(77.77f)); - - List<List<? extends Number>> list = new ArrayList<List<? extends Number>>(); - list.add(integerList); - list.add(floatList); - ListIterator<Number> li = new ReadOnlyCompositeListIterator<Number>(list); - while (li.hasNext()) { - assertTrue(li.next().intValue() > 0); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyIteratorTests.java deleted file mode 100644 index f00417064d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyIteratorTests.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Vector; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyIterator; - -@SuppressWarnings("nls") -public class ReadOnlyIteratorTests extends TestCase { - - public ReadOnlyIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildReadOnlyIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(this.buildVector().size(), i); - } - - public void testHasNextUpcast() { - int i = 0; - for (Iterator<Object> stream = this.buildReadOnlyIteratorUpcast(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(this.buildVector().size(), i); - } - - public void testNext() { - Iterator<String> nestedIterator = this.buildNestedIterator(); - for (Iterator<String> stream = this.buildReadOnlyIterator(); stream.hasNext();) { - assertEquals("bogus element", nestedIterator.next(), stream.next()); - } - } - - public void testNextUpcast() { - Iterator<String> nestedIterator = this.buildNestedIterator(); - for (Iterator<Object> stream = this.buildReadOnlyIteratorUpcast(); stream.hasNext();) { - assertEquals("bogus element", nestedIterator.next(), stream.next()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildReadOnlyIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testRemove() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildReadOnlyIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - private Iterator<String> buildReadOnlyIterator() { - return this.buildReadOnlyIterator(this.buildNestedIterator()); - } - - private Iterator<Object> buildReadOnlyIteratorUpcast() { - return this.buildReadOnlyIteratorUpcast(this.buildNestedIterator()); - } - - private Iterator<String> buildReadOnlyIterator(Iterator<String> nestedIterator) { - return new ReadOnlyIterator<String>(nestedIterator); - } - - private Iterator<Object> buildReadOnlyIteratorUpcast(Iterator<String> nestedIterator) { - return new ReadOnlyIterator<Object>(nestedIterator); - } - - private Iterator<String> buildNestedIterator() { - return this.buildVector().iterator(); - } - - private Vector<String> buildVector() { - Vector<String> v = new Vector<String>(); - v.addElement("one"); - v.addElement("two"); - v.addElement("three"); - v.addElement("four"); - v.addElement("five"); - v.addElement("six"); - v.addElement("seven"); - v.addElement("eight"); - return v; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyListIteratorTests.java deleted file mode 100644 index 9d81a2ad37..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/ReadOnlyListIteratorTests.java +++ /dev/null @@ -1,204 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyListIterator; - -@SuppressWarnings("nls") -public class ReadOnlyListIteratorTests extends TestCase { - - public ReadOnlyListIteratorTests(String name) { - super(name); - } - - public void testHasNextAndHasPrevious() { - int i = 0; - ListIterator<String> stream = this.buildReadOnlyListIterator(); - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(this.buildList().size(), i); - - while (stream.hasPrevious()) { - stream.previous(); - i--; - } - assertEquals(0, i); - } - - public void testHasNextAndHasPreviousUpcast() { - int i = 0; - ListIterator<Object> stream = this.buildReadOnlyListIteratorUpcast(); - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(this.buildList().size(), i); - - while (stream.hasPrevious()) { - stream.previous(); - i--; - } - assertEquals(0, i); - } - - public void testNextAndPrevious() { - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - ListIterator<String> stream = this.buildReadOnlyListIterator(); - while (stream.hasNext()) { - assertEquals("bogus element", nestedListIterator.next(), stream.next()); - } - while (stream.hasPrevious()) { - assertEquals("bogus element", nestedListIterator.previous(), stream.previous()); - } - } - - public void testNextAndPreviousUpcast() { - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - ListIterator<Object> stream = this.buildReadOnlyListIteratorUpcast(); - while (stream.hasNext()) { - assertEquals("bogus element", nestedListIterator.next(), stream.next()); - } - while (stream.hasPrevious()) { - assertEquals("bogus element", nestedListIterator.previous(), stream.previous()); - } - } - - public void testNextIndexAndPreviousIndex() { - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - ListIterator<String> stream = this.buildReadOnlyListIterator(); - while (stream.hasNext()) { - assertEquals("bogus index", nestedListIterator.nextIndex(), stream.nextIndex()); - nestedListIterator.next(); - stream.next(); - } - assertEquals("bogus index", this.buildList().size(), stream.nextIndex()); - while (stream.hasPrevious()) { - assertEquals("bogus element", nestedListIterator.previousIndex(), stream.previousIndex()); - nestedListIterator.previous(); - stream.previous(); - } - assertEquals("bogus index", -1, stream.previousIndex()); - } - - public void testNextIndexAndPreviousIndexUpcast() { - ListIterator<String> nestedListIterator = this.buildNestedListIterator(); - ListIterator<Object> stream = this.buildReadOnlyListIteratorUpcast(); - while (stream.hasNext()) { - assertEquals("bogus index", nestedListIterator.nextIndex(), stream.nextIndex()); - nestedListIterator.next(); - stream.next(); - } - assertEquals("bogus index", this.buildList().size(), stream.nextIndex()); - while (stream.hasPrevious()) { - assertEquals("bogus element", nestedListIterator.previousIndex(), stream.previousIndex()); - nestedListIterator.previous(); - stream.previous(); - } - assertEquals("bogus index", -1, stream.previousIndex()); - } - - public void testNoSuchElementException() { - boolean exCaught = false; - ListIterator<String> stream = this.buildReadOnlyListIterator(); - String string = null; - while (stream.hasNext()) { - string = stream.next(); - } - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testRemove() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildReadOnlyListIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testSet() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildReadOnlyListIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.set("bogus"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testAdd() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildReadOnlyListIterator(); stream.hasNext();) { - if (stream.next().equals("three")) { - try { - stream.add("bogus"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - private ListIterator<String> buildReadOnlyListIterator() { - return this.buildReadOnlyListIterator(this.buildNestedListIterator()); - } - - private ListIterator<Object> buildReadOnlyListIteratorUpcast() { - return this.buildReadOnlyListIteratorUpcast(this.buildNestedListIterator()); - } - - private ListIterator<String> buildReadOnlyListIterator(ListIterator<String> nestedListIterator) { - return new ReadOnlyListIterator<String>(nestedListIterator); - } - - private ListIterator<Object> buildReadOnlyListIteratorUpcast(ListIterator<String> nestedListIterator) { - return new ReadOnlyListIterator<Object>(nestedListIterator); - } - - private ListIterator<String> buildNestedListIterator() { - return this.buildList().listIterator(); - } - - private List<String> buildList() { - List<String> l = new ArrayList<String>(); - l.add("one"); - l.add("two"); - l.add("three"); - l.add("four"); - l.add("five"); - l.add("six"); - l.add("seven"); - l.add("eight"); - return l; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SingleElementIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SingleElementIteratorTests.java deleted file mode 100644 index 4fce5a6826..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SingleElementIteratorTests.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.SingleElementIterator; - -@SuppressWarnings("nls") -public class SingleElementIteratorTests extends TestCase { - - public SingleElementIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<String> stream = this.buildSingleElementIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(1, i); - } - - public void testNext() { - for (Iterator<String> stream = this.buildSingleElementIterator(); stream.hasNext();) { - assertEquals("bogus element", this.singleElement(), stream.next()); - } - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<String> stream = this.buildSingleElementIterator(); - String string = stream.next(); - try { - string = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + string, exCaught); - } - - public void testRemove() { - boolean exCaught = false; - for (Iterator<String> stream = this.buildSingleElementIterator(); stream.hasNext();) { - if (stream.next().equals(this.singleElement())) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - protected Iterator<String> buildSingleElementIterator() { - return new SingleElementIterator<String>(this.singleElement()); - } - - protected String singleElement() { - return "single element"; - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SingleElementListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SingleElementListIteratorTests.java deleted file mode 100644 index d393a65201..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SingleElementListIteratorTests.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.ListIterator; -import org.eclipse.jpt.common.utility.internal.iterators.SingleElementListIterator; - -@SuppressWarnings("nls") -public class SingleElementListIteratorTests extends SingleElementIteratorTests { - - public SingleElementListIteratorTests(String name) { - super(name); - } - - public void testNextIndex() { - ListIterator<String> stream = this.buildSingleElementListIterator(); - while (stream.hasNext()) { - assertEquals("bogus index", 0, stream.nextIndex()); - stream.next(); - } - assertEquals("bogus index", 1, stream.nextIndex()); - } - - public void testHasPrevious() { - int i = 0; - ListIterator<String> stream = this.buildSingleElementListIterator(); - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(1, i); - - while (stream.hasPrevious()) { - stream.previous(); - i++; - } - assertEquals(2, i); - } - - public void testPrevious() { - ListIterator<String> stream = this.buildSingleElementListIterator(); - - while (stream.hasNext()) { - assertEquals("bogus element", this.singleElement(), stream.next()); - } - - while (stream.hasPrevious()) { - assertEquals("bogus element", this.singleElement(), stream.previous()); - } - } - - public void testPreviousIndex() { - ListIterator<String> stream = this.buildSingleElementListIterator(); - - while (stream.hasNext()) { - assertEquals("bogus index", 0, stream.nextIndex()); - stream.next(); - } - - while (stream.hasPrevious()) { - assertEquals("bogus index", 0, stream.previousIndex()); - stream.previous(); - } - - assertEquals("bogus index", -1, stream.previousIndex()); - } - - public void testAdd() { - boolean exCaught = false; - ListIterator<String> stream = this.buildSingleElementListIterator(); - - try { - stream.add("foo"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testSet() { - boolean exCaught = false; - for (ListIterator<String> stream = this.buildSingleElementListIterator(); stream.hasNext();) { - if (stream.next().equals(this.singleElement())) { - try { - stream.set("foo"); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - @Override - protected Iterator<String> buildSingleElementIterator() { - return new SingleElementListIterator<String>(this.singleElement()); - } - - protected ListIterator<String> buildSingleElementListIterator() { - return (ListIterator<String>) this.buildSingleElementIterator(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SuperIteratorWrapperTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SuperIteratorWrapperTests.java deleted file mode 100644 index 4bb6dc626d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SuperIteratorWrapperTests.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.iterators.SuperIteratorWrapper; - -@SuppressWarnings("nls") -public class SuperIteratorWrapperTests extends TestCase { - - public SuperIteratorWrapperTests(String name) { - super(name); - } - - public void testIterator() { - ArrayList<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - String concat = ""; - for (Iterator<String> stream = list.iterator(); stream.hasNext(); ) { - concat += stream.next(); - } - assertEquals("foobarbaz", concat); - - Iterator<Object> iterator = new SuperIteratorWrapper<Object>(list); - concat = ""; - while (iterator.hasNext()) { - Object next = iterator.next(); - if (next.equals("bar")) { - iterator.remove(); - } else { - concat += next; - } - } - assertEquals("foobaz", concat); - assertEquals(2, list.size()); - assertFalse(list.contains("bar")); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SynchronizedIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SynchronizedIteratorTests.java deleted file mode 100644 index e30238fe74..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SynchronizedIteratorTests.java +++ /dev/null @@ -1,310 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.SynchronizedIterator; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SynchronizedIteratorTests - extends MultiThreadedTestCase -{ - public SynchronizedIteratorTests(String name) { - super(name); - } - - /** - * test that an unsynchronized iterator will produce corrupt output; - * thread 1 will read the first element from the iterator - * and then sleep for a bit, allowing thread 2 to sneak in and - * read the same element from the iterator - */ - public void testUnsynchronizedNext() throws Exception { - TestIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - NextTestRunnable<String> runnable2 = new NextTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // both threads should have read the same element from the iterator :-( - assertEquals("foo", runnable1.next); - assertEquals("foo", runnable2.next); - } - - /** - * test that a synchronized iterator will produce valid output; - * thread 1 will read the first element from the iterator - * and then sleep for a bit, but thread 2 will be locked out and - * wait to read the second element from the iterator - */ - public void testSynchronizedNext() throws Exception { - TestIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - Iterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - NextTestRunnable<String> runnable2 = new NextTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the threads should have read the correct elements from the iterator :-) - assertEquals("foo", runnable1.next); - assertEquals("bar", runnable2.next); - } - - public void testUnsynchronizedHasNext() throws Exception { - TestIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - HasNextTestRunnable<String> runnable2 = new HasNextTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the last element, - // but thread 2 will think there are more elements on the iterator :-( - assertEquals("baz", runnable1.next); - assertEquals(true, runnable2.hasNext); - } - - public void testSynchronizedHasNext() throws Exception { - TestIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - Iterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - HasNextTestRunnable<String> runnable2 = new HasNextTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the last element, - // and thread 2 will think there are no more elements on the iterator :-) - assertEquals("baz", runnable1.next); - assertEquals(false, runnable2.hasNext); - } - - public void testUnsynchronizedRemove() throws Exception { - TestIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - RemoveTestRunnable<String> runnable2 = new RemoveTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the wrong element was removed :-( - assertEquals("bar", runnable1.next); - assertFalse(iterator.list.contains("foo")); - assertTrue(iterator.list.contains("bar")); - assertTrue(iterator.list.contains("baz")); - } - - public void testSynchronizedRemove() throws Exception { - TestIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - Iterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - RemoveTestRunnable<String> runnable2 = new RemoveTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the correct element was removed :-) - assertEquals("bar", runnable1.next); - assertTrue(nestedIterator.list.contains("foo")); - assertFalse(nestedIterator.list.contains("bar")); - assertTrue(nestedIterator.list.contains("baz")); - } - - TestIterator<String> buildTestIterator(long delay) { - return new TestIterator<String>(delay, this.buildArray()); - } - - String[] buildArray() { - return new String[] {"foo", "bar", "baz"}; - } - - Iterator<String> buildSynchronizedIterator(Iterator<String> nestedIterator) { - return new SynchronizedIterator<String>(nestedIterator); - } - - - /** - * next runnable - */ - class NextTestRunnable<E> implements Runnable { - final Iterator<E> iterator; - E next; - - NextTestRunnable(Iterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.next = this.iterator.next(); - } - - } - - /** - * has next runnable - */ - class HasNextTestRunnable<E> implements Runnable { - final Iterator<E> iterator; - boolean hasNext; - - HasNextTestRunnable(Iterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.hasNext = this.iterator.hasNext(); - } - - } - - /** - * remove runnable - */ - class RemoveTestRunnable<E> implements Runnable { - final Iterator<E> iterator; - - RemoveTestRunnable(Iterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.iterator.remove(); - } - - } - - /** - * Test iterator: If {@link #next()} is called while executing on the - * {@link slowThread}, the iterator will delay for the configured time. - */ - static class TestIterator<E> implements Iterator<E> { - final long delay; - final ArrayList<E> list = new ArrayList<E>(); - int nextIndex = 0; - int lastIndex = -1; - Thread slowThread; - - TestIterator(long delay, E... array) { - super(); - this.delay = delay; - CollectionTools.addAll(this.list, array); - } - - public boolean hasNext() { - return this.nextIndex != this.list.size(); - } - - public E next() { - if (this.hasNext()) { - E next = this.list.get(this.nextIndex); - if (Thread.currentThread() == this.slowThread) { - TestTools.sleep(this.delay); - } - this.lastIndex = this.nextIndex++; - return next; - } - throw new NoSuchElementException(); - } - - public void remove() { - if (this.lastIndex == -1) { - throw new IllegalStateException(); - } - this.list.remove(this.lastIndex); - if (this.lastIndex < this.nextIndex) { // check necessary for ListIterator - this.nextIndex--; - } - this.lastIndex = -1; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SynchronizedListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SynchronizedListIteratorTests.java deleted file mode 100644 index dbf0ac5b57..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/SynchronizedListIteratorTests.java +++ /dev/null @@ -1,524 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.Iterator; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.internal.iterators.SynchronizedListIterator; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SynchronizedListIteratorTests - extends SynchronizedIteratorTests -{ - public SynchronizedListIteratorTests(String name) { - super(name); - } - - public void testUnsynchronizedPrevious() throws Exception { - TestListIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - iterator.next(); - - PreviousTestRunnable<String> runnable1 = new PreviousTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - PreviousTestRunnable<String> runnable2 = new PreviousTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // both threads should have read the same element from the iterator :-( - assertEquals("bar", runnable1.previous); - assertEquals("bar", runnable2.previous); - } - - public void testSynchronizedPrevious() throws Exception { - TestListIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - ListIterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - iterator.next(); - - PreviousTestRunnable<String> runnable1 = new PreviousTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - PreviousTestRunnable<String> runnable2 = new PreviousTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the threads should have read the correct elements from the iterator :-) - assertEquals("bar", runnable1.previous); - assertEquals("foo", runnable2.previous); - } - - public void testUnsynchronizedHasPrevious() throws Exception { - TestListIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - - PreviousTestRunnable<String> runnable1 = new PreviousTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - HasPreviousTestRunnable<String> runnable2 = new HasPreviousTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the first element, - // but thread 2 will think there are more "previous" elements on the iterator :-( - assertEquals("foo", runnable1.previous); - assertEquals(true, runnable2.hasPrevious); - } - - public void testSynchronizedHasPrevious() throws Exception { - TestListIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - ListIterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - - PreviousTestRunnable<String> runnable1 = new PreviousTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - HasPreviousTestRunnable<String> runnable2 = new HasPreviousTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the first element, - // and thread 2 will think there are no more "previous" elements on the iterator :-) - assertEquals("foo", runnable1.previous); - assertEquals(false, runnable2.hasPrevious); - } - - public void testUnsynchronizedNextIndex() throws Exception { - TestListIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - NextIndexTestRunnable<String> runnable2 = new NextIndexTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the first element, - // but thread 2 will think the next index is still 0 :-( - assertEquals("foo", runnable1.next); - assertEquals(0, runnable2.nextIndex); - } - - public void testSynchronizedNextIndex() throws Exception { - TestListIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - ListIterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - NextIndexTestRunnable<String> runnable2 = new NextIndexTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the first element, - // and thread 2 will think the next index is 1 :-) - assertEquals("foo", runnable1.next); - assertEquals(1, runnable2.nextIndex); - } - - public void testUnsynchronizedPreviousIndex() throws Exception { - TestListIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - - PreviousTestRunnable<String> runnable1 = new PreviousTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - PreviousIndexTestRunnable<String> runnable2 = new PreviousIndexTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the first element, - // but thread 2 will think the next index is still 0 :-( - assertEquals("foo", runnable1.previous); - assertEquals(0, runnable2.previousIndex); - } - - public void testSynchronizedPreviousIndex() throws Exception { - TestListIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - ListIterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - - PreviousTestRunnable<String> runnable1 = new PreviousTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - PreviousIndexTestRunnable<String> runnable2 = new PreviousIndexTestRunnable<String>(iterator); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // thread 1 will have the first element, - // and thread 2 will think the next index is -1 :-) - assertEquals("foo", runnable1.previous); - assertEquals(-1, runnable2.previousIndex); - } - - public void testUnsynchronizedSet() throws Exception { - TestListIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - SetTestRunnable<String> runnable2 = new SetTestRunnable<String>(iterator, "xxx"); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the wrong element was set :-( - assertEquals("bar", runnable1.next); - assertFalse(iterator.list.contains("foo")); - assertTrue(iterator.list.contains("xxx")); - assertTrue(iterator.list.contains("bar")); - assertTrue(iterator.list.contains("baz")); - } - - public void testSynchronizedSet() throws Exception { - TestListIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - ListIterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - SetTestRunnable<String> runnable2 = new SetTestRunnable<String>(iterator, "xxx"); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the right element was set :-) - assertEquals("bar", runnable1.next); - assertTrue(nestedIterator.list.contains("foo")); - assertFalse(nestedIterator.list.contains("bar")); - assertTrue(nestedIterator.list.contains("xxx")); - assertTrue(nestedIterator.list.contains("baz")); - } - - public void testUnsynchronizedAdd() throws Exception { - TestListIterator<String> iterator = this.buildTestIterator(TWO_TICKS); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - AddTestRunnable<String> runnable2 = new AddTestRunnable<String>(iterator, "xxx"); - Thread thread2 = this.buildThread(runnable2); - iterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the element was added at the wrong index :-( - assertEquals("bar", runnable1.next); - assertTrue(iterator.list.contains("foo")); - assertEquals(0, iterator.list.indexOf("xxx")); - assertTrue(iterator.list.contains("xxx")); - assertTrue(iterator.list.contains("bar")); - assertTrue(iterator.list.contains("baz")); - } - - public void testSynchronizedAdd() throws Exception { - TestListIterator<String> nestedIterator = this.buildTestIterator(TWO_TICKS); - ListIterator<String> iterator = this.buildSynchronizedIterator(nestedIterator); - iterator.next(); - - NextTestRunnable<String> runnable1 = new NextTestRunnable<String>(iterator); - Thread thread1 = this.buildThread(runnable1); - AddTestRunnable<String> runnable2 = new AddTestRunnable<String>(iterator, "xxx"); - Thread thread2 = this.buildThread(runnable2); - nestedIterator.slowThread = thread1; - - thread1.start(); - - // allow thread 1 to read the first element and get bogged down - this.sleep(TICK); - thread2.start(); - - // wait for the threads to finish - thread1.join(); - thread2.join(); - - // the element was added at the correct index :-) - assertEquals("bar", runnable1.next); - assertTrue(nestedIterator.list.contains("foo")); - assertEquals(1, nestedIterator.list.indexOf("xxx")); - assertTrue(nestedIterator.list.contains("xxx")); - assertTrue(nestedIterator.list.contains("bar")); - assertTrue(nestedIterator.list.contains("baz")); - } - - @Override - ListIterator<String> buildSynchronizedIterator(Iterator<String> nestedIterator) { - return new SynchronizedListIterator<String>((ListIterator<String>) nestedIterator); - } - - @Override - TestListIterator<String> buildTestIterator(long delay) { - return new TestListIterator<String>(delay, this.buildArray()); - } - - /** - * previous runnable - */ - class PreviousTestRunnable<E> implements Runnable { - final ListIterator<E> iterator; - E previous; - - PreviousTestRunnable(ListIterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.previous = this.iterator.previous(); - } - - } - - /** - * has previous runnable - */ - class HasPreviousTestRunnable<E> implements Runnable { - final ListIterator<E> iterator; - boolean hasPrevious; - - HasPreviousTestRunnable(ListIterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.hasPrevious = this.iterator.hasPrevious(); - } - - } - - /** - * next index runnable - */ - class NextIndexTestRunnable<E> implements Runnable { - final ListIterator<E> iterator; - int nextIndex; - - NextIndexTestRunnable(ListIterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.nextIndex = this.iterator.nextIndex(); - } - - } - - /** - * previous index runnable - */ - class PreviousIndexTestRunnable<E> implements Runnable { - final ListIterator<E> iterator; - int previousIndex; - - PreviousIndexTestRunnable(ListIterator<E> iterator) { - super(); - this.iterator = iterator; - } - - public void run() { - this.previousIndex = this.iterator.previousIndex(); - } - - } - - /** - * set runnable - */ - class SetTestRunnable<E> implements Runnable { - final ListIterator<E> iterator; - final E element; - - SetTestRunnable(ListIterator<E> iterator, E element) { - super(); - this.iterator = iterator; - this.element = element; - } - - public void run() { - this.iterator.set(this.element); - } - - } - - /** - * add runnable - */ - class AddTestRunnable<E> implements Runnable { - final ListIterator<E> iterator; - final E element; - - AddTestRunnable(ListIterator<E> iterator, E element) { - super(); - this.iterator = iterator; - this.element = element; - } - - public void run() { - this.iterator.add(this.element); - } - - } - - /** - * Test iterator: If {@link #next()} or {@link #previous()} is called - * while executing on the {@link slowThread}, the iterator will delay - * for the configured time. - */ - static class TestListIterator<E> extends TestIterator<E> implements ListIterator<E> { - - TestListIterator(long delay, E... array) { - super(delay, array); - } - - public int nextIndex() { - return this.nextIndex; - } - - public boolean hasPrevious() { - return this.nextIndex != 0; - } - - public E previous() { - if (this.hasPrevious()) { - E previous = this.list.get(this.previousIndex()); - if (Thread.currentThread() == this.slowThread) { - TestTools.sleep(this.delay); - } - this.nextIndex--; - this.lastIndex = this.nextIndex; - return previous; - } - throw new NoSuchElementException(); - } - - public int previousIndex() { - return this.nextIndex - 1; - } - - public void set(E e) { - if (this.lastIndex == -1) { - throw new IllegalStateException(); - } - this.list.set(this.lastIndex, e); - } - - public void add(E e) { - this.list.add(this.lastIndex, e); - this.lastIndex++; - this.lastIndex = -1; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TransformationIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TransformationIteratorTests.java deleted file mode 100644 index af7185a792..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TransformationIteratorTests.java +++ /dev/null @@ -1,230 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.iterators.TransformationIterator; - -@SuppressWarnings("nls") -public class TransformationIteratorTests extends TestCase { - - public TransformationIteratorTests(String name) { - super(name); - } - - public void testHasNext() { - int i = 0; - for (Iterator<Integer> stream = this.buildIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(8, i); - } - - public void testHasNextUpcast() { - int i = 0; - for (Iterator<Object> stream = this.buildIteratorUpcast(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(8, i); - } - - public void testInnerHasNext() { - int i = 0; - for (Iterator<Integer> stream = this.buildInnerIterator(); stream.hasNext();) { - stream.next(); - i++; - } - assertEquals(8, i); - } - - public void testNext() { - int i = 0; - for (Iterator<Integer> stream = this.buildIterator(); stream.hasNext();) { - assertEquals("bogus transformation", ++i, stream.next().intValue()); - } - } - - public void testNextUpcast() { - int i = 0; - for (Iterator<Object> stream = this.buildIteratorUpcast(); stream.hasNext();) { - assertEquals("bogus transformation", ++i, ((Integer) stream.next()).intValue()); - } - } - - public void testInnerNext() { - int i = 0; - for (Iterator<Integer> stream = this.buildInnerIterator(); stream.hasNext();) { - assertEquals("bogus transformation", ++i, stream.next().intValue()); - } - } - - public void testRemove() { - Collection<String> c = this.buildCollection(); - for (Iterator<Integer> stream = this.buildInnerTransformationIterator(c.iterator()); stream.hasNext();) { - if (stream.next().intValue() == 3) { - stream.remove(); - } - } - assertEquals("nothing removed", this.buildCollection().size() - 1, c.size()); - assertFalse("element still in collection", c.contains("333")); - assertTrue("wrong element removed", c.contains("22")); - } - - public void testInnerRemove() { - Collection<String> c = this.buildCollection(); - for (Iterator<Integer> stream = this.buildTransformationIterator(c.iterator(), this.buildTransformer()); stream.hasNext();) { - if (stream.next().intValue() == 3) { - stream.remove(); - } - } - assertEquals("nothing removed", this.buildCollection().size() - 1, c.size()); - assertFalse("element still in collection", c.contains("333")); - assertTrue("wrong element removed", c.contains("22")); - } - - public void testNoSuchElementException() { - boolean exCaught = false; - Iterator<Integer> stream = this.buildIterator(); - Integer integer = null; - while (stream.hasNext()) { - integer = stream.next(); - } - try { - integer = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + integer, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<Integer> stream = this.buildUnmodifiableIterator(); stream.hasNext();) { - int i = stream.next().intValue(); - if (i == 3) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testIllegalStateException() { - boolean exCaught = false; - try { - this.buildIterator().remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - - private Iterator<Integer> buildIterator() { - return this.buildTransformationIterator(this.buildNestedIterator(), this.buildTransformer()); - } - - private Iterator<Object> buildIteratorUpcast() { - return this.buildTransformationIteratorUpcast(this.buildNestedIterator(), this.buildTransformerUpcast()); - } - - private Iterator<Integer> buildInnerIterator() { - return this.buildInnerTransformationIterator(this.buildNestedIterator()); - } - - private Iterator<Integer> buildUnmodifiableIterator() { - return this.buildTransformationIterator(this.buildUnmodifiableNestedIterator(), this.buildTransformer()); - } - - private Iterator<Integer> buildTransformationIterator(Iterator<String> nestedIterator, Transformer<String, Integer> transformer) { - return new TransformationIterator<String, Integer>(nestedIterator, transformer); - } - - private Iterator<Object> buildTransformationIteratorUpcast(Iterator<String> nestedIterator, Transformer<Object, Integer> transformer) { - return new TransformationIterator<Object, Object>(nestedIterator, transformer); - } - - private Transformer<String, Integer> buildTransformer() { - // transform each string into an integer with a value of the string's length - return new Transformer<String, Integer>() { - public Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - private Transformer<Object, Integer> buildTransformerUpcast() { - // transform each string into an integer with a value of the string's length - return new Transformer<Object, Integer>() { - public Integer transform(Object next) { - return new Integer(((String) next).length()); - } - }; - } - - private Iterator<Integer> buildInnerTransformationIterator(Iterator<String> nestedIterator) { - // transform each string into an integer with a value of the string's length - return new TransformationIterator<String, Integer>(nestedIterator) { - @Override - protected Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - private Iterator<String> buildNestedIterator() { - return this.buildCollection().iterator(); - } - - private Iterator<String> buildUnmodifiableNestedIterator() { - return this.buildUnmodifiableCollection().iterator(); - } - - private Collection<String> buildCollection() { - Collection<String> c = new ArrayList<String>(); - c.add("1"); - c.add("22"); - c.add("333"); - c.add("4444"); - c.add("55555"); - c.add("666666"); - c.add("7777777"); - c.add("88888888"); - return c; - } - - private Collection<String> buildUnmodifiableCollection() { - return Collections.unmodifiableCollection(this.buildCollection()); - } - - public void testInvalidTransformationIterator() { - // missing method override - Iterator<Integer> iterator = new TransformationIterator<String, Integer>(this.buildCollection().iterator()); - boolean exCaught = false; - try { - Integer integer = iterator.next(); - fail("invalid integer: " + integer); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TransformationListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TransformationListIteratorTests.java deleted file mode 100644 index 9a438096ba..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TransformationListIteratorTests.java +++ /dev/null @@ -1,322 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.iterators.TransformationListIterator; - -@SuppressWarnings("nls") -public class TransformationListIteratorTests extends TestCase { - - public TransformationListIteratorTests(String name) { - super(name); - } - - public void testHasNextAndHasPrevious() { - int i = 0; - ListIterator<Integer> stream = this.buildIterator(); - - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(8, i); - - while (stream.hasPrevious()) { - stream.previous(); - i--; - } - assertEquals(0, i); - } - - public void testHasNextAndHasPreviousUpcast() { - int i = 0; - ListIterator<Object> stream = this.buildIteratorUpcast(); - - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(8, i); - - while (stream.hasPrevious()) { - stream.previous(); - i--; - } - assertEquals(0, i); - } - - public void testInnerHasNextAndHasPrevious() { - int i = 0; - ListIterator<Integer> stream = this.buildInnerIterator(); - - while (stream.hasNext()) { - stream.next(); - i++; - } - assertEquals(8, i); - - while (stream.hasPrevious()) { - stream.previous(); - i--; - } - assertEquals(0, i); - } - - public void testNextAndPrevious() { - int i = 0; - ListIterator<Integer> stream = this.buildIterator(); - - while (stream.hasNext()) { - assertEquals(++i, stream.next().intValue()); - } - - ++i; - - while (stream.hasPrevious()) { - assertEquals(--i, stream.previous().intValue()); - } - } - - public void testInnerNextAndPrevious() { - int i = 0; - ListIterator<Integer> stream = this.buildInnerIterator(); - - while (stream.hasNext()) { - assertEquals(++i, stream.next().intValue()); - } - - ++i; - - while (stream.hasPrevious()) { - assertEquals(--i, stream.previous().intValue()); - } - } - - public void testNextIndexAndPreviousIndex() { - int i = -1; - ListIterator<Integer> stream = this.buildIterator(); - - while (stream.hasNext()) { - assertEquals(++i, stream.nextIndex()); - stream.next(); - } - - ++i; - - while (stream.hasPrevious()) { - assertEquals(--i, stream.previousIndex()); - stream.previous(); - } - } - - public void testInnerNextIndexAndPreviousIndex() { - int i = -1; - ListIterator<Integer> stream = this.buildInnerIterator(); - - while (stream.hasNext()) { - assertEquals(++i, stream.nextIndex()); - stream.next(); - } - - ++i; - - while (stream.hasPrevious()) { - assertEquals(--i, stream.previousIndex()); - stream.previous(); - } - } - - public void testRemove() { - List<String> l = this.buildList(); - for (ListIterator<Integer> stream = this.buildInnerTransformationListIterator(l.listIterator()); stream.hasNext();) { - if (stream.next().intValue() == 3) { - stream.remove(); - } - } - assertEquals("nothing removed", this.buildList().size() - 1, l.size()); - assertFalse("element still in list", l.contains("333")); - assertTrue("wrong element removed", l.contains("22")); - } - - public void testInnerRemove() { - List<String> l = this.buildList(); - for (ListIterator<Integer> stream = this.buildTransformationListIterator(l.listIterator(), this.buildTransformer()); stream.hasNext();) { - if (stream.next().intValue() == 3) { - stream.remove(); - } - } - assertEquals("nothing removed", this.buildList().size() - 1, l.size()); - assertFalse("element still in list", l.contains("333")); - assertTrue("wrong element removed", l.contains("22")); - } - - public void testUnsupportedOperationExceptionOnAdd() { - ListIterator<Integer> stream = this.buildIterator(); - boolean exCaught = false; - try { - stream.add(new Integer(0)); - fail("exception not thrown"); - } catch (UnsupportedOperationException e) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testUnsupportedOperationExceptionOnSet() { - ListIterator<Integer> stream = this.buildIterator(); - boolean exCaught = false; - try { - stream.set(new Integer(0)); - fail("exception not thrown"); - } catch (UnsupportedOperationException e) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testNoSuchElementException() { - boolean exCaught = false; - ListIterator<Integer> stream = this.buildIterator(); - Integer integer = null; - while (stream.hasNext()) { - integer = stream.next(); - } - try { - integer = stream.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown: " + integer, exCaught); - } - - public void testUnsupportedOperationException() { - boolean exCaught = false; - for (Iterator<Integer> stream = this.buildUnmodifiableIterator(); stream.hasNext();) { - int i = stream.next().intValue(); - if (i == 3) { - try { - stream.remove(); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - } - } - assertTrue("UnsupportedOperationException not thrown", exCaught); - } - - public void testIllegalStateException() { - boolean exCaught = false; - try { - this.buildIterator().remove(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue("IllegalStateException not thrown", exCaught); - } - - private ListIterator<Integer> buildIterator() { - return this.buildTransformationListIterator(this.buildNestedIterator(), this.buildTransformer()); - } - - private ListIterator<Object> buildIteratorUpcast() { - return this.buildTransformationListIteratorUpcast(this.buildNestedIterator(), this.buildTransformerUpcast()); - } - - private ListIterator<Integer> buildInnerIterator() { - return this.buildInnerTransformationListIterator(this.buildNestedIterator()); - } - - private ListIterator<Integer> buildUnmodifiableIterator() { - return this.buildTransformationListIterator(this.buildUnmodifiableNestedIterator(), this.buildTransformer()); - } - - private ListIterator<Integer> buildTransformationListIterator(ListIterator<String> nestedIterator, Transformer<String, Integer> transformer) { - return new TransformationListIterator<String, Integer>(nestedIterator, transformer); - } - - private ListIterator<Object> buildTransformationListIteratorUpcast(ListIterator<String> nestedIterator, Transformer<Object, Integer> transformer) { - return new TransformationListIterator<Object, Object>(nestedIterator, transformer); - } - - private Transformer<String, Integer> buildTransformer() { - // transform each string into an integer with a value of the string's length - return new Transformer<String, Integer>() { - public Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - private Transformer<Object, Integer> buildTransformerUpcast() { - // transform each string into an integer with a value of the string's length - return new Transformer<Object, Integer>() { - public Integer transform(Object next) { - return new Integer(((String) next).length()); - } - }; - } - - private ListIterator<Integer> buildInnerTransformationListIterator(ListIterator<String> nestedIterator) { - // transform each string into an integer with a value of the string's length - return new TransformationListIterator<String, Integer>(nestedIterator) { - @Override - protected Integer transform(String next) { - return new Integer(next.length()); - } - }; - } - - private ListIterator<String> buildNestedIterator() { - return this.buildList().listIterator(); - } - - private ListIterator<String> buildUnmodifiableNestedIterator() { - return this.buildUnmodifiableList().listIterator(); - } - - private List<String> buildList() { - List<String> l = new ArrayList<String>(); - l.add("1"); - l.add("22"); - l.add("333"); - l.add("4444"); - l.add("55555"); - l.add("666666"); - l.add("7777777"); - l.add("88888888"); - return l; - } - - private List<String> buildUnmodifiableList() { - return Collections.unmodifiableList(this.buildList()); - } - - public void testInvalidTransformationListIterator() { - // missing method override - Iterator<Integer> iterator = new TransformationListIterator<String, Integer>(this.buildList().listIterator()); - boolean exCaught = false; - try { - Integer integer = iterator.next(); - fail("invalid integer: " + integer); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TreeIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TreeIteratorTests.java deleted file mode 100644 index f800e12bde..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterators/TreeIteratorTests.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.iterators; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.TreeIterator; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class TreeIteratorTests extends TestCase { - /** this will be populated with all the nodes created for the test */ - Collection<TreeNode> nodes = new ArrayList<TreeNode>(); - - public TreeIteratorTests(String name) { - super(name); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testHasNext1() { - this.verifyHasNext(this.buildTreeIterator1()); - } - - public void testHasNext2() { - this.verifyHasNext(this.buildTreeIterator2()); - } - - private void verifyHasNext(Iterator<TreeNode> iterator) { - int i = 0; - while (iterator.hasNext()) { - iterator.next(); - i++; - } - assertEquals(this.nodes.size(), i); - } - - public void testNext1() { - this.verifyNext(this.buildTreeIterator1()); - } - - public void testNext2() { - this.verifyNext(this.buildTreeIterator2()); - } - - private void verifyNext(Iterator<TreeNode> iterator) { - while (iterator.hasNext()) { - assertTrue("bogus element", this.nodes.contains(iterator.next())); - } - } - - public void testNoSuchElementException1() { - this.verifyNoSuchElementException(this.buildTreeIterator1()); - } - - public void testNoSuchElementException2() { - this.verifyNoSuchElementException(this.buildTreeIterator2()); - } - - private void verifyNoSuchElementException(Iterator<TreeNode> iterator) { - boolean exCaught = false; - while (iterator.hasNext()) { - iterator.next(); - } - try { - iterator.next(); - } catch (NoSuchElementException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - - public void testRemove1() { - this.verifyRemove(this.buildTreeIterator1()); - } - - public void testRemove2() { - this.verifyRemove(this.buildTreeIterator2()); - } - - private void verifyRemove(Iterator<TreeNode> iterator) { - String parentName = "child 2"; - String childName = "grandchild 2A"; - int startSize = this.childrenSize(parentName); - while (iterator.hasNext()) { - TreeNode node = iterator.next(); - if (node.getName().equals(childName)) { - iterator.remove(); - } - } - int endSize = this.childrenSize(parentName); - assertEquals(startSize - 1, endSize); - } - - private int childrenSize(String nodeName) { - for (Iterator<TreeNode> stream = this.nodes.iterator(); stream.hasNext();) { - TreeNode node = stream.next(); - if (node.getName().equals(nodeName)) { - return node.childrenSize(); - } - } - throw new IllegalArgumentException(nodeName); - } - - /** - * build a tree iterator with an explicit midwife - */ - private Iterator<TreeNode> buildTreeIterator1() { - return new TreeIterator<TreeNode>(this.buildTree(), this.buildMidwife()); - } - - private TreeIterator.Midwife<TreeNode> buildMidwife() { - return new TreeIterator.Midwife<TreeNode>() { - public Iterator<TreeNode> children(TreeNode next) { - return next.children(); - } - }; - } - - /** - * build a tree iterator with an override - */ - private Iterator<TreeNode> buildTreeIterator2() { - return new TreeIterator<TreeNode>(this.buildTree()) { - @Override - public Iterator<TreeNode> children(TreeNode next) { - return next.children(); - } - }; - } - - public void testInvalidTreeIterator() { - // missing method override - Iterator<TreeNode> iterator = new TreeIterator<TreeNode>(this.buildTree()); - boolean exCaught = false; - try { - TreeNode tn = iterator.next(); - fail("invalid tree node: " + tn); - } catch (UnsupportedOperationException ex) { - exCaught = true; - } - assertTrue("NoSuchElementException not thrown", exCaught); - } - - private TreeNode buildTree() { - TreeNode root = new TreeNode("root"); - TreeNode child1 = new TreeNode(root, "child 1"); - new TreeNode(child1, "grandchild 1A"); - TreeNode child2 = new TreeNode(root, "child 2"); - new TreeNode(child2, "grandchild 2A"); - TreeNode grandchild2B = new TreeNode(child2, "grandchild 2B"); - new TreeNode(grandchild2B, "great-grandchild 2B1"); - new TreeNode(grandchild2B, "great-grandchild 2B2"); - TreeNode grandchild2C = new TreeNode(child2, "grandchild 2C"); - new TreeNode(grandchild2C, "great-grandchild 2C1"); - new TreeNode(root, "child 3"); - return root; - } - - private class TreeNode { - private String name; - private Collection<TreeNode> children = new ArrayList<TreeNode>(); - - public TreeNode(String name) { - super(); - TreeIteratorTests.this.nodes.add(this); // log node - this.name = name; - } - - public TreeNode(TreeNode parent, String name) { - this(name); - parent.addChild(this); - } - - public String getName() { - return this.name; - } - - private void addChild(TreeNode child) { - this.children.add(child); - } - - public Iterator<TreeNode> children() { - return this.children.iterator(); - } - - public int childrenSize() { - return this.children.size(); - } - - @Override - public String toString() { - return "TreeNode(" + this.name + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/ChangeSupportTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/ChangeSupportTests.java deleted file mode 100644 index 2166827530..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/ChangeSupportTests.java +++ /dev/null @@ -1,4575 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EventListener; -import java.util.HashSet; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ListenerList; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.Tools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.ChangeSupport; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; -import org.eclipse.jpt.common.utility.model.event.TreeAddEvent; -import org.eclipse.jpt.common.utility.model.event.TreeChangeEvent; -import org.eclipse.jpt.common.utility.model.event.TreeClearEvent; -import org.eclipse.jpt.common.utility.model.event.TreeEvent; -import org.eclipse.jpt.common.utility.model.event.TreeRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ListChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.StateChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.StateChangeListener; -import org.eclipse.jpt.common.utility.model.listener.TreeChangeAdapter; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ChangeSupportTests - extends TestCase -{ - TestModel testModel; - static final String TEST_TO_STRING = "this is a test"; - - ChangeListener changeListener = new Adapter(); - - StateChangeEvent stateChangeEvent; - boolean stateChangedCalled = false; - - PropertyChangeEvent propertyChangeEvent; - boolean propertyChangeCalled = false; - static final String PROPERTY_NAME = "propertyName"; - static final Object OLD_OBJECT_VALUE = new Object(); - static final Object NEW_OBJECT_VALUE = new Object(); - static final Integer OLD_INT_VALUE = new Integer(27); - static final Boolean OLD_BOOLEAN_VALUE = Boolean.TRUE; - static final Integer NEW_INT_VALUE = new Integer(42); - static final Boolean NEW_BOOLEAN_VALUE = Boolean.FALSE; - - CollectionEvent collectionEvent; - boolean itemsAddedCollectionCalled = false; - boolean itemsRemovedCollectionCalled = false; - boolean collectionChangedCalled = false; - boolean collectionClearedCalled = false; - static final String COLLECTION_NAME = "collectionName"; - static final Object ADDED_OBJECT_VALUE = new Object(); - static final Object ADDED_OBJECT_VALUE_2 = new Object(); - static final Object REMOVED_OBJECT_VALUE = new Object(); - static final int TARGET_INDEX = 7; - static final int SOURCE_INDEX = 22; - - ListEvent listEvent; - boolean itemsAddedListCalled = false; - boolean itemsRemovedListCalled = false; - boolean itemsReplacedListCalled = false; - boolean itemsMovedListCalled = false; - boolean listChangedCalled = false; - boolean listClearedCalled = false; - static final String LIST_NAME = "listName"; - static final int ADD_INDEX = 3; - static final int REMOVE_INDEX = 5; - static final int REPLACE_INDEX = 2; - - TreeEvent treeEvent; - boolean nodeAddedCalled = false; - boolean nodeRemovedCalled = false; - boolean treeChangedCalled = false; - boolean treeClearedCalled = false; - static final String TREE_NAME = "treeName"; - static final List<Object> OBJECT_PATH = Arrays.asList(new Object[] {new Object(), new Object(), new String()}); - - - public ChangeSupportTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.testModel = new TestModel(); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - - // ********** general tests ********** - - public void testNullSource() { - boolean exCaught = false; - try { - ChangeSupport cs = new ChangeSupport(null); - fail("bogus change support: " + cs); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - // ********** state change tests ********** - - public void testFireStateChange() { - this.stateChangeEvent = null; - this.stateChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireStateChange(); - assertNotNull(this.stateChangeEvent); - assertEquals(this.testModel, this.stateChangeEvent.getSource()); - assertTrue(this.stateChangedCalled); - } - - public void testHasAnyStateChangeListeners() { - assertTrue(this.testModel.hasNoStateChangeListeners()); - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.hasAnyStateChangeListeners()); - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.hasNoStateChangeListeners()); - } - - public void testHasAnyStateChangeListenersDuplicate() { - assertTrue(this.testModel.hasNoStateChangeListeners()); - this.testModel.addChangeListener(this.changeListener); - boolean exCaught = false; - try { - this.testModel.addChangeListener(this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - assertTrue(this.testModel.hasAnyStateChangeListeners()); - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.hasNoStateChangeListeners()); - - exCaught = false; - try { - this.testModel.removeChangeListener(this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(this.testModel.hasNoStateChangeListeners()); - } - - public void testAddNullStateListener() { - boolean exCaught = false; - try { - this.testModel.addStateChangeListener(null); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemoveBogusStateListener() { - boolean exCaught = false; - try { - this.testModel.removeChangeListener(this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addPropertyChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeChangeListener(this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addChangeListener(this.changeListener); - exCaught = false; - try { - this.testModel.removeStateChangeListener(new Adapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.testModel.removeStateChangeListener(new StateChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - // ********** property change tests ********** - - public void testFirePropertyChangedEvent() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedEvent(); - this.verifyPropertyChangeEvent(OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedEvent(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedEvent(); - this.verifyPropertyChangeEvent(OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedEvent(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedEventNoChange() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedEventNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedEventNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedEventNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedEventNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedObjectObject() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObjectObject(); - this.verifyPropertyChangeEvent(OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObjectObject(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObjectObject(); - this.verifyPropertyChangeEvent(OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObjectObject(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedObjectObjectNoChange() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObjectObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObjectObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObjectObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObjectObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedObject() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObject(); - this.verifyPropertyChangeEvent(null, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObject(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObject(); - this.verifyPropertyChangeEvent(null, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObject(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedObjectNoChange() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedObjectNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedIntInt() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedIntInt(); - this.verifyPropertyChangeEvent(OLD_INT_VALUE, NEW_INT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedIntInt(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedIntInt(); - this.verifyPropertyChangeEvent(OLD_INT_VALUE, NEW_INT_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedIntInt(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedIntIntNoChange() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedIntIntNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedIntIntNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedIntIntNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedIntIntNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedBooleanBoolean() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedBooleanBoolean(); - this.verifyPropertyChangeEvent(OLD_BOOLEAN_VALUE, NEW_BOOLEAN_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedBooleanBoolean(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedBooleanBoolean(); - this.verifyPropertyChangeEvent(OLD_BOOLEAN_VALUE, NEW_BOOLEAN_VALUE); - assertTrue(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedBooleanBoolean(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testFirePropertyChangedBooleanBooleanNoChange() { - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedBooleanBooleanNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFirePropertyChangedBooleanBooleanNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedBooleanBooleanNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - this.testModel.testFirePropertyChangedBooleanBooleanNoChange(); - assertNull(this.propertyChangeEvent); - assertFalse(this.propertyChangeCalled); - } - - public void testHasAnyPropertyChangeListeners() { - assertTrue(this.testModel.hasNoPropertyChangeListeners(PROPERTY_NAME)); - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.hasNoPropertyChangeListeners(PROPERTY_NAME)); - - assertTrue(this.testModel.hasNoPropertyChangeListeners(PROPERTY_NAME)); - this.testModel.addPropertyChangeListener(PROPERTY_NAME, this.changeListener); - assertTrue(this.testModel.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - this.testModel.removePropertyChangeListener(PROPERTY_NAME, this.changeListener); - assertTrue(this.testModel.hasNoPropertyChangeListeners(PROPERTY_NAME)); - } - - public void testAddNullPropertyListener() { - boolean exCaught = false; - try { - this.testModel.addChangeListener(null); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddNullPropertyListenerName() { - boolean exCaught = false; - try { - this.testModel.addPropertyChangeListener("foo", null); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemoveBogusPropertyListener() { - boolean exCaught = false; - try { - this.testModel.removePropertyChangeListener("foo", new PropertyChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addCollectionChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removePropertyChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addPropertyChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removePropertyChangeListener("foo", new PropertyChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.testModel.removePropertyChangeListener("foo", new PropertyChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private void verifyPropertyChangeEvent(Object oldValue, Object newValue) { - this.verifyPropertyChangeEvent(this.testModel, oldValue, newValue); - } - - private void verifyPropertyChangeEvent(Object source, Object oldValue, Object newValue) { - assertNotNull(this.propertyChangeEvent); - assertEquals(source, this.propertyChangeEvent.getSource()); - assertEquals(PROPERTY_NAME, this.propertyChangeEvent.getPropertyName()); - assertEquals(oldValue, this.propertyChangeEvent.getOldValue()); - assertEquals(newValue, this.propertyChangeEvent.getNewValue()); - } - - - // ********** collection change tests ********** - - public void testFireItemsAddedCollectionEvent() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollectionEvent(); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollectionEvent(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollectionEvent(); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollectionEvent(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testFireItemsAddedCollectionEventNoChange() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testFireItemsAddedCollection() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollection(); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollection(); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testFireItemsAddedCollectionNoChange() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsAddedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testFireItemAddedCollection() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemAddedCollection(); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemAddedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemAddedCollection(); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemAddedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testFireItemsRemovedCollectionEvent() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollectionEvent(); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollectionEvent(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollectionEvent(); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollectionEvent(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testFireItemsRemovedCollectionEventNoChange() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollectionEventNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testFireItemsRemovedCollection() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollection(); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollection(); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testFireItemsRemovedCollectionNoChange() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemsRemovedCollectionNoChange(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testFireItemRemovedCollection() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemRemovedCollection(); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemRemovedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemRemovedCollection(); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireItemRemovedCollection(); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testFireCollectionCleared() { - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireCollectionCleared(); - this.verifyCollectionEvent(null); - assertTrue(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireCollectionCleared(); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireCollectionCleared(); - this.verifyCollectionEvent(null); - assertTrue(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireCollectionCleared(); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - } - - public void testFireCollectionChangedEvent() { - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireCollectionChangedEvent(); - this.verifyCollectionEvent(null); - assertTrue(this.collectionChangedCalled); - - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireCollectionChangedEvent(); - assertNull(this.collectionEvent); - assertFalse(this.collectionChangedCalled); - - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireCollectionChangedEvent(); - this.verifyCollectionEvent(null); - assertTrue(this.collectionChangedCalled); - - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireCollectionChangedEvent(); - assertNull(this.collectionEvent); - assertFalse(this.collectionChangedCalled); - } - - public void testFireCollectionChanged() { - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireCollectionChanged(); - this.verifyCollectionEvent(null); - assertTrue(this.collectionChangedCalled); - - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireCollectionChanged(); - assertNull(this.collectionEvent); - assertFalse(this.collectionChangedCalled); - - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireCollectionChanged(); - this.verifyCollectionEvent(null); - assertTrue(this.collectionChangedCalled); - - this.collectionEvent = null; - this.collectionChangedCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - this.testModel.testFireCollectionChanged(); - assertNull(this.collectionEvent); - assertFalse(this.collectionChangedCalled); - } - - public void testAddItemToCollection() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testAddItemToCollection()); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testAddItemToCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testAddItemToCollection()); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testAddItemToCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testAddItemToCollectionNoChange() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testAddItemToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testAddItemToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testAddItemToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testAddItemToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testAddItemsToCollection() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testAddItemsToCollection()); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testAddItemsToCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testAddItemsToCollection()); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testAddItemsToCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testAddItemsToCollectionNoChange() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testAddItemsToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testAddItemsToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testAddItemsToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testAddItemsToCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testAddItemsToCollectionMixed() { - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testAddItemsToCollectionMixed()); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE_2); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testAddItemsToCollectionMixed()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testAddItemsToCollectionMixed()); - this.verifyCollectionEvent(ADDED_OBJECT_VALUE_2); - assertTrue(this.itemsAddedCollectionCalled); - - this.collectionEvent = null; - this.itemsAddedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testAddItemsToCollectionMixed()); - assertNull(this.collectionEvent); - assertFalse(this.itemsAddedCollectionCalled); - } - - public void testRemoveItemFromCollection() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testRemoveItemFromCollection()); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testRemoveItemFromCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRemoveItemFromCollection()); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRemoveItemFromCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRemoveItemFromCollectionNoChange() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemFromCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemFromCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemFromCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemFromCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRemoveItemsFromCollection() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testRemoveItemsFromCollection()); - this.verifyCollectionChangeEvent2(REMOVED_OBJECT_VALUE, "foo", "bar"); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testRemoveItemsFromCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRemoveItemsFromCollection()); - this.verifyCollectionChangeEvent2(REMOVED_OBJECT_VALUE, "foo", "bar"); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRemoveItemsFromCollection()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRemoveItemsFromCollectionNoChange1() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRemoveItemsFromCollectionNoChange2() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRemoveItemsFromCollectionNoChange3() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange3()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange3()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange3()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRemoveItemsFromCollectionNoChange3()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRetainItemsInCollection1() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection1()); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection1()); - this.verifyCollectionEvent(REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - // collection cleared... - public void testRetainItemsInCollection2() { - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection2()); - this.verifyCollectionEvent(null); - assertTrue(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection2()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection2()); - this.verifyCollectionEvent(null); - assertTrue(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testRetainItemsInCollection2()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - } - - public void testRetainItemsInCollectionNoChange1() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange1()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testRetainItemsInCollectionNoChange2() { - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - - this.collectionEvent = null; - this.itemsRemovedCollectionCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testRetainItemsInCollectionNoChange2()); - assertNull(this.collectionEvent); - assertFalse(this.itemsRemovedCollectionCalled); - } - - public void testClearCollection() { - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.testClearCollection()); - this.verifyCollectionEvent(null); - assertTrue(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.testClearCollection()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testClearCollection()); - this.verifyCollectionEvent(null); - assertTrue(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.testClearCollection()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - } - - public void testClearCollectionNoChange() { - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - assertFalse(this.testModel.testClearCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - assertFalse(this.testModel.testClearCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testClearCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - - this.collectionEvent = null; - this.collectionClearedCalled = false; - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertFalse(this.testModel.testClearCollectionNoChange()); - assertNull(this.collectionEvent); - assertFalse(this.collectionClearedCalled); - } - - public void testSynchronizeCollection1() { - CollectionSynchListener csl = new CollectionSynchListener(); - this.testModel.addChangeListener(csl); - assertTrue(this.testModel.testSynchronizeCollection1()); - assertTrue(csl.itemsAdded); - assertTrue(csl.itemsRemoved); - assertFalse(csl.collectionChanged); - assertFalse(csl.collectionCleared); - assertEquals(2, csl.addedItems.size()); - assertTrue(CollectionTools.containsAll(csl.addedItems, new Object[] {"joo", "jar"})); - assertEquals(2, csl.removedItems.size()); - assertTrue(CollectionTools.containsAll(csl.removedItems, new Object[] {"foo", "bar"})); - } - - public void testSynchronizeCollection2() { - CollectionSynchListener csl = new CollectionSynchListener(); - this.testModel.addChangeListener(csl); - assertTrue(this.testModel.testSynchronizeCollection2()); - assertFalse(csl.itemsAdded); - assertFalse(csl.itemsRemoved); - assertFalse(csl.collectionChanged); - assertTrue(csl.collectionCleared); - assertTrue(csl.addedItems.isEmpty()); - assertTrue(csl.removedItems.isEmpty()); - } - - public void testSynchronizeCollection3() { - CollectionSynchListener csl = new CollectionSynchListener(); - this.testModel.addChangeListener(csl); - assertTrue(this.testModel.testSynchronizeCollection3()); - assertTrue(csl.itemsAdded); - assertFalse(csl.itemsRemoved); - assertFalse(csl.collectionChanged); - assertFalse(csl.collectionCleared); - assertEquals(3, csl.addedItems.size()); - assertTrue(CollectionTools.containsAll(csl.addedItems, new Object[] {"joo", "jar", "baz"})); - assertTrue(csl.removedItems.isEmpty()); - } - - class CollectionSynchListener extends ChangeAdapter { - boolean itemsAdded = false; - boolean itemsRemoved = false; - boolean collectionChanged = false; - boolean collectionCleared = false; - Collection<Object> addedItems = new ArrayList<Object>(); - Collection<Object> removedItems = new ArrayList<Object>(); - @Override - public void collectionChanged(CollectionChangeEvent event) { - this.collectionChanged = true; - } - @Override - public void collectionCleared(CollectionClearEvent event) { - this.collectionCleared = true; - } - @Override - public void itemsAdded(CollectionAddEvent event) { - this.itemsAdded = true; - CollectionTools.addAll(this.addedItems, event.getItems()); - } - @Override - public void itemsRemoved(CollectionRemoveEvent event) { - this.itemsRemoved = true; - CollectionTools.addAll(this.removedItems, event.getItems()); - } - } - - public void testHasAnyCollectionChangeListeners() { - assertTrue(this.testModel.hasNoCollectionChangeListeners(COLLECTION_NAME)); - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.hasAnyCollectionChangeListeners(COLLECTION_NAME)); - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.hasNoCollectionChangeListeners(COLLECTION_NAME)); - - assertTrue(this.testModel.hasNoCollectionChangeListeners(COLLECTION_NAME)); - this.testModel.addCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.hasAnyCollectionChangeListeners(COLLECTION_NAME)); - this.testModel.removeCollectionChangeListener(COLLECTION_NAME, this.changeListener); - assertTrue(this.testModel.hasNoCollectionChangeListeners(COLLECTION_NAME)); - } - - public void testAddNullCollectionListener() { - boolean exCaught = false; - try { - this.testModel.addCollectionChangeListener("foo", null); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemoveBogusCollectionListener() { - boolean exCaught = false; - try { - this.testModel.removeCollectionChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addPropertyChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeCollectionChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addCollectionChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeCollectionChangeListener("foo", new CollectionChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.testModel.removeCollectionChangeListener("foo", new CollectionChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private void verifyCollectionEvent(Object item) { - assertNotNull(this.collectionEvent); - assertEquals(this.testModel, this.collectionEvent.getSource()); - assertEquals(COLLECTION_NAME, this.collectionEvent.getCollectionName()); - if (item != null) { - assertEquals(item, this.getCollectionEventItems().iterator().next()); - } - } - - private Iterable<?> getCollectionEventItems() { - if (this.collectionEvent instanceof CollectionAddEvent) { - return ((CollectionAddEvent) this.collectionEvent).getItems(); - } else if (this.collectionEvent instanceof CollectionRemoveEvent) { - return ((CollectionRemoveEvent) this.collectionEvent).getItems(); - } - throw new IllegalStateException(); - } - - private void verifyCollectionChangeEvent2(Object... items) { - assertNotNull(this.collectionEvent); - assertEquals(this.testModel, this.collectionEvent.getSource()); - assertEquals(COLLECTION_NAME, this.collectionEvent.getCollectionName()); - assertEquals(items.length, this.getCollectionEventItemsSize()); - for (Object item : items) { - assertTrue(CollectionTools.contains(this.getCollectionEventItems(), item)); - } - } - - private int getCollectionEventItemsSize() { - if (this.collectionEvent instanceof CollectionAddEvent) { - return ((CollectionAddEvent) this.collectionEvent).getItemsSize(); - } else if (this.collectionEvent instanceof CollectionRemoveEvent) { - return ((CollectionRemoveEvent) this.collectionEvent).getItemsSize(); - } - throw new IllegalStateException(); - } - - - // ********** list change tests ********** - - public void testFireItemsAddedListEvent() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedListEvent(); - this.verifyListAddEvent(ADD_INDEX, ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedListEvent(); - this.verifyListAddEvent(ADD_INDEX, ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testFireItemsAddedListEventNoChange() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testFireItemsAddedList() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedList(); - this.verifyListAddEvent(ADD_INDEX, ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedList(); - this.verifyListAddEvent(ADD_INDEX, ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testFireItemsAddedListNoChange() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsAddedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsAddedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsAddedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testFireItemAddedList() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemAddedList(); - this.verifyListAddEvent(ADD_INDEX, ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemAddedList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemAddedList(); - this.verifyListAddEvent(ADD_INDEX, ADDED_OBJECT_VALUE); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemAddedList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testFireItemsRemovedListEvent() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedListEvent(); - this.verifyListRemoveEvent(REMOVE_INDEX, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedListEvent(); - this.verifyListRemoveEvent(REMOVE_INDEX, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testFireItemsRemovedListEventNoChange() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testFireItemsRemovedList() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedList(); - this.verifyListRemoveEvent(REMOVE_INDEX, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedList(); - this.verifyListRemoveEvent(REMOVE_INDEX, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testFireItemsRemovedListNoChange() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsRemovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsRemovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testFireItemRemovedList() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemRemovedList(); - this.verifyListRemoveEvent(REMOVE_INDEX, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemRemovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemRemovedList(); - this.verifyListRemoveEvent(REMOVE_INDEX, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemRemovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testFireItemsReplacedListEvent() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedListEvent(); - this.verifyListReplaceEvent(REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedListEvent(); - this.verifyListReplaceEvent(REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testFireItemsReplacedListEventNoChange() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testFireItemsReplacedList() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedList(); - this.verifyListReplaceEvent(REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedList(); - this.verifyListReplaceEvent(REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testFireItemsReplacedListNoChange() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsReplacedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsReplacedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testFireItemReplacedList() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemReplacedList(); - this.verifyListReplaceEvent(REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemReplacedList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemReplacedList(); - this.verifyListReplaceEvent(REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemReplacedList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testFireItemsMovedListEvent() { - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsMovedListEvent(); - this.verifyListMoveEvent(TARGET_INDEX, SOURCE_INDEX); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsMovedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedListEvent(); - this.verifyListMoveEvent(TARGET_INDEX, SOURCE_INDEX); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedListEvent(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - } - - public void testFireItemsMovedListEventNoChange() { - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsMovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsMovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedListEventNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - } - - public void testFireItemsMovedList() { - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsMovedList(); - this.verifyListMoveEvent(TARGET_INDEX, SOURCE_INDEX); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsMovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedList(); - this.verifyListMoveEvent(TARGET_INDEX, SOURCE_INDEX); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - } - - public void testFireItemsMovedListNoChange() { - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemsMovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemsMovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemsMovedListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - } - - public void testFireItemMovedList() { - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireItemMovedList(); - this.verifyListMoveEvent(TARGET_INDEX, SOURCE_INDEX); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireItemMovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemMovedList(); - this.verifyListMoveEvent(TARGET_INDEX, SOURCE_INDEX); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireItemMovedList(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - } - - public void testFireListClearedEvent() { - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireListClearedEvent(); - this.verifyListClearEvent(); - assertTrue(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireListClearedEvent(); - assertNull(this.listEvent); - assertFalse(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListClearedEvent(); - this.verifyListClearEvent(); - assertTrue(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListClearedEvent(); - assertNull(this.listEvent); - assertFalse(this.listClearedCalled); - } - - public void testFireListCleared() { - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireListCleared(); - this.verifyListClearEvent(); - assertTrue(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireListCleared(); - assertNull(this.listEvent); - assertFalse(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListCleared(); - this.verifyListClearEvent(); - assertTrue(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListCleared(); - assertNull(this.listEvent); - assertFalse(this.listClearedCalled); - } - - public void testFireListChangedEvent() { - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireListChangedEvent(); - this.verifyListChangeEvent(); - assertTrue(this.listChangedCalled); - - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireListChangedEvent(); - assertNull(this.listEvent); - assertFalse(this.listChangedCalled); - - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListChangedEvent(); - this.verifyListChangeEvent(); - assertTrue(this.listChangedCalled); - - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListChangedEvent(); - assertNull(this.listEvent); - assertFalse(this.listChangedCalled); - } - - public void testFireListChanged() { - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireListChanged(); - this.verifyListChangeEvent(); - assertTrue(this.listChangedCalled); - - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireListChanged(); - assertNull(this.listEvent); - assertFalse(this.listChangedCalled); - - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListChanged(); - this.verifyListChangeEvent(); - assertTrue(this.listChangedCalled); - - this.listEvent = null; - this.listChangedCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testFireListChanged(); - assertNull(this.listEvent); - assertFalse(this.listChangedCalled); - } - - public void testAddItemToListIndex() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testAddItemToListIndex(); - this.verifyListAddEvent(2, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testAddItemToListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemToListIndex(); - this.verifyListAddEvent(2, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemToListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testAddItemToList() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testAddItemToList(); - this.verifyListAddEvent(3, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testAddItemToList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemToList(); - this.verifyListAddEvent(3, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemToList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testAddItemsToListIndex() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testAddItemsToListIndex(); - this.verifyListAddEvent(2, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testAddItemsToListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToListIndex(); - this.verifyListAddEvent(2, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testAddItemsToListIndexNoChange() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testAddItemsToListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testAddItemsToListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testAddItemsToList() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testAddItemsToList(); - this.verifyListAddEvent(3, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testAddItemsToList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToList(); - this.verifyListAddEvent(3, "joo"); - assertTrue(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToList(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testAddItemsToListNoChange() { - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testAddItemsToListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testAddItemsToListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - - this.listEvent = null; - this.itemsAddedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testAddItemsToListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsAddedListCalled); - } - - public void testRemoveItemFromListIndex() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRemoveItemFromListIndex(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRemoveItemFromListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemFromListIndex(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemFromListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testRemoveItemFromList() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRemoveItemFromList(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRemoveItemFromList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemFromList(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemFromList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testRemoveItemsFromListIndex() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromListIndex(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromListIndex(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromListIndex(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testRemoveItemsFromListIndexNoChange() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromListIndexNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testRemoveItemsFromList() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromList(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromList(); - this.verifyListRemoveEvent(1, "bar"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testRemoveItemsFromListNoChange() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRemoveItemsFromListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRemoveItemsFromListNoChange(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testRetainItemsInList() { - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testRetainItemsInList(); - this.verifyListRemoveEvent(0, "foo"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testRetainItemsInList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRetainItemsInList(); - this.verifyListRemoveEvent(0, "foo"); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testRetainItemsInList(); - assertNull(this.listEvent); - assertFalse(this.itemsRemovedListCalled); - } - - public void testReplaceItemInList() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testReplaceItemInList(); - this.verifyListReplaceEvent(1, "xxx", "bar"); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testReplaceItemInList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testReplaceItemInList(); - this.verifyListReplaceEvent(1, "xxx", "bar"); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testReplaceItemInList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testSetItemsInList() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testSetItemsInList(); - this.verifyListReplaceEvent(1, "xxx", "bar"); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testSetItemsInList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testSetItemsInList(); - this.verifyListReplaceEvent(1, "xxx", "bar"); - assertTrue(this.itemsReplacedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testSetItemsInList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - } - - public void testMoveItemsInList() { - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testMoveItemsInList(); - this.verifyListMoveEvent(2, 4, 2); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testMoveItemsInList(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testMoveItemsInList(); - this.verifyListMoveEvent(2, 4, 2); - assertTrue(this.itemsMovedListCalled); - - this.listEvent = null; - this.itemsMovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testMoveItemsInList(); - assertNull(this.listEvent); - assertFalse(this.itemsMovedListCalled); - } - - public void testClearList() { - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testClearList(); - this.verifyListClearEvent(); - assertTrue(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testClearList(); - assertNull(this.listEvent); - assertFalse(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testClearList(); - this.verifyListClearEvent(); - assertTrue(this.listClearedCalled); - - this.listEvent = null; - this.listClearedCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testClearList(); - assertNull(this.listEvent); - assertFalse(this.listClearedCalled); - } - - public void testSynchronizeList() { - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.itemsRemovedListCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testSynchronizeList(); - assertNotNull(this.listEvent); - assertTrue(this.itemsReplacedListCalled); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.itemsRemovedListCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testSynchronizeList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - assertFalse(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.itemsRemovedListCalled = false; - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testSynchronizeList(); - assertNotNull(this.listEvent); - assertTrue(this.itemsReplacedListCalled); - assertTrue(this.itemsRemovedListCalled); - - this.listEvent = null; - this.itemsReplacedListCalled = false; - this.itemsRemovedListCalled = false; - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - this.testModel.testSynchronizeList(); - assertNull(this.listEvent); - assertFalse(this.itemsReplacedListCalled); - assertFalse(this.itemsRemovedListCalled); - } - - public void testHasAnyListChangeListeners() { - assertTrue(this.testModel.hasNoListChangeListeners(LIST_NAME)); - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.hasAnyListChangeListeners(LIST_NAME)); - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.hasNoListChangeListeners(LIST_NAME)); - - assertTrue(this.testModel.hasNoListChangeListeners(LIST_NAME)); - this.testModel.addListChangeListener(LIST_NAME, this.changeListener); - assertTrue(this.testModel.hasAnyListChangeListeners(LIST_NAME)); - this.testModel.removeListChangeListener(LIST_NAME, this.changeListener); - assertTrue(this.testModel.hasNoListChangeListeners(LIST_NAME)); - } - - public void testAddNullListListener() { - boolean exCaught = false; - try { - this.testModel.addListChangeListener("foo", null); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemoveBogusListListener() { - boolean exCaught = false; - try { - this.testModel.removeListChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addPropertyChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeListChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addListChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeListChangeListener("foo", new ListChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.testModel.removeListChangeListener("foo", new ListChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private void verifyListAddEvent(int index, Object item) { - assertNotNull(this.listEvent); - assertEquals(this.testModel, this.listEvent.getSource()); - assertEquals(LIST_NAME, this.listEvent.getListName()); - assertEquals(index, ((ListAddEvent) this.listEvent).getIndex()); - assertEquals(item, ((ListAddEvent) this.listEvent).getItems().iterator().next()); - } - - private void verifyListRemoveEvent(int index, Object item) { - assertNotNull(this.listEvent); - assertEquals(this.testModel, this.listEvent.getSource()); - assertEquals(LIST_NAME, this.listEvent.getListName()); - assertEquals(index, ((ListRemoveEvent) this.listEvent).getIndex()); - assertEquals(item, ((ListRemoveEvent) this.listEvent).getItems().iterator().next()); - } - - private void verifyListReplaceEvent(int index, Object newItem, Object oldItem) { - assertNotNull(this.listEvent); - assertEquals(this.testModel, this.listEvent.getSource()); - assertEquals(LIST_NAME, this.listEvent.getListName()); - assertEquals(index, ((ListReplaceEvent) this.listEvent).getIndex()); - assertEquals(newItem, ((ListReplaceEvent) this.listEvent).getNewItems().iterator().next()); - assertEquals(oldItem, ((ListReplaceEvent) this.listEvent).getOldItems().iterator().next()); - } - - private void verifyListMoveEvent(int targetIndex, int sourceIndex) { - this.verifyListMoveEvent(targetIndex, sourceIndex, 1); - } - - private void verifyListMoveEvent(int targetIndex, int sourceIndex, int length) { - assertNotNull(this.listEvent); - assertEquals(this.testModel, this.listEvent.getSource()); - assertEquals(LIST_NAME, this.listEvent.getListName()); - assertEquals(targetIndex, ((ListMoveEvent) this.listEvent).getTargetIndex()); - assertEquals(sourceIndex, ((ListMoveEvent) this.listEvent).getSourceIndex()); - assertEquals(length, ((ListMoveEvent) this.listEvent).getLength()); - } - - private void verifyListClearEvent() { - assertNotNull(this.listEvent); - assertEquals(this.testModel, this.listEvent.getSource()); - assertEquals(LIST_NAME, this.listEvent.getListName()); - assertEquals(ListClearEvent.class, this.listEvent.getClass()); - } - - private void verifyListChangeEvent() { - assertNotNull(this.listEvent); - assertEquals(this.testModel, this.listEvent.getSource()); - assertEquals(LIST_NAME, this.listEvent.getListName()); - assertEquals(ListChangeEvent.class, this.listEvent.getClass()); - } - - - // ********** tree change tests ********** - - public void testFireNodeAddedTree() { - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireNodeAddedTree(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeAddedCalled); - - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireNodeAddedTree(); - assertNull(this.treeEvent); - assertFalse(this.nodeAddedCalled); - - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeAddedTree(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeAddedCalled); - - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeAddedTree(); - assertNull(this.treeEvent); - assertFalse(this.nodeAddedCalled); - } - - public void testFireNodeAddedTreeEvent() { - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireNodeAddedTreeEvent(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeAddedCalled); - - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireNodeAddedTreeEvent(); - assertNull(this.treeEvent); - assertFalse(this.nodeAddedCalled); - - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeAddedTreeEvent(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeAddedCalled); - - this.treeEvent = null; - this.nodeAddedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeAddedTreeEvent(); - assertNull(this.treeEvent); - assertFalse(this.nodeAddedCalled); - } - - public void testFireNodeRemovedTreeEvent() { - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireNodeRemovedTreeEvent(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeRemovedCalled); - - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireNodeRemovedTreeEvent(); - assertNull(this.treeEvent); - assertFalse(this.nodeRemovedCalled); - - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeRemovedTreeEvent(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeRemovedCalled); - - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeRemovedTreeEvent(); - assertNull(this.treeEvent); - assertFalse(this.nodeRemovedCalled); - } - - public void testFireNodeRemovedTree() { - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireNodeRemovedTree(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeRemovedCalled); - - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireNodeRemovedTree(); - assertNull(this.treeEvent); - assertFalse(this.nodeRemovedCalled); - - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeRemovedTree(); - this.verifyTreeEvent(OBJECT_PATH); - assertTrue(this.nodeRemovedCalled); - - this.treeEvent = null; - this.nodeRemovedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireNodeRemovedTree(); - assertNull(this.treeEvent); - assertFalse(this.nodeRemovedCalled); - } - - public void testFireTreeClearedEvent() { - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireTreeClearedEvent(); - this.verifyTreeEvent(null); - assertTrue(this.treeClearedCalled); - - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireTreeClearedEvent(); - assertNull(this.treeEvent); - assertFalse(this.treeClearedCalled); - - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeClearedEvent(); - this.verifyTreeEvent(null); - assertTrue(this.treeClearedCalled); - - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeClearedEvent(); - assertNull(this.treeEvent); - assertFalse(this.treeClearedCalled); - } - - public void testFireTreeCleared() { - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireTreeCleared(); - this.verifyTreeEvent(null); - assertTrue(this.treeClearedCalled); - - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireTreeCleared(); - assertNull(this.treeEvent); - assertFalse(this.treeClearedCalled); - - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeCleared(); - this.verifyTreeEvent(null); - assertTrue(this.treeClearedCalled); - - this.treeEvent = null; - this.treeClearedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeCleared(); - assertNull(this.treeEvent); - assertFalse(this.treeClearedCalled); - } - - public void testFireTreeChangedEvent() { - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireTreeChangedEvent(); - this.verifyTreeEvent(null); - assertTrue(this.treeChangedCalled); - - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireTreeChangedEvent(); - assertNull(this.treeEvent); - assertFalse(this.treeChangedCalled); - - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeChangedEvent(); - this.verifyTreeEvent(null); - assertTrue(this.treeChangedCalled); - - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeChangedEvent(); - assertNull(this.treeEvent); - assertFalse(this.treeChangedCalled); - } - - public void testFireTreeChanged() { - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.addChangeListener(this.changeListener); - this.testModel.testFireTreeChanged(); - this.verifyTreeEvent(null); - assertTrue(this.treeChangedCalled); - - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.removeChangeListener(this.changeListener); - this.testModel.testFireTreeChanged(); - assertNull(this.treeEvent); - assertFalse(this.treeChangedCalled); - - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeChanged(); - this.verifyTreeEvent(null); - assertTrue(this.treeChangedCalled); - - this.treeEvent = null; - this.treeChangedCalled = false; - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - this.testModel.testFireTreeChanged(); - assertNull(this.treeEvent); - assertFalse(this.treeChangedCalled); - } - - public void testHasAnyTreeChangeListeners() { - assertTrue(this.testModel.hasNoTreeChangeListeners(TREE_NAME)); - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.hasAnyTreeChangeListeners(TREE_NAME)); - this.testModel.removeChangeListener(this.changeListener); - assertTrue(this.testModel.hasNoTreeChangeListeners(TREE_NAME)); - - assertTrue(this.testModel.hasNoTreeChangeListeners(TREE_NAME)); - this.testModel.addTreeChangeListener(TREE_NAME, this.changeListener); - assertTrue(this.testModel.hasAnyTreeChangeListeners(TREE_NAME)); - this.testModel.removeTreeChangeListener(TREE_NAME, this.changeListener); - assertTrue(this.testModel.hasNoTreeChangeListeners(TREE_NAME)); - } - - public void testAddNullTreeListener() { - boolean exCaught = false; - try { - this.testModel.addTreeChangeListener("foo", null); - } catch (NullPointerException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testRemoveBogusTreeListener() { - boolean exCaught = false; - try { - this.testModel.removeTreeChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addPropertyChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeTreeChangeListener("foo", this.changeListener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - this.testModel.addTreeChangeListener("foo", this.changeListener); - exCaught = false; - try { - this.testModel.removeTreeChangeListener("foo", new TreeChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.testModel.removeTreeChangeListener("foo", new TreeChangeAdapter()); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - private void verifyTreeEvent(List<?> path) { - assertNotNull(this.treeEvent); - assertEquals(this.testModel, this.treeEvent.getSource()); - assertEquals(TREE_NAME, this.treeEvent.getTreeName()); - assertEquals(path, this.getListPath()); - } - - private List<?> getListPath() { - Iterable<?> iterable = this.getPath(); - return (iterable == null) ? null : CollectionTools.list(iterable); - } - - private Iterable<?> getPath() { - if (this.treeEvent instanceof TreeAddEvent) { - return ((TreeAddEvent) this.treeEvent).getPath(); - } - if (this.treeEvent instanceof TreeRemoveEvent) { - return ((TreeRemoveEvent) this.treeEvent).getPath(); - } - return null; - } - - - - // ********** convenience method tests ********** - - public void testElementsAreEqual() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("foo"); - c1.add("bar"); - c1.add("baz"); - Collection<String> c2 = new ArrayList<String>(); - c2.add("foo"); - c2.add("bar"); - c2.add("baz"); - assertTrue(this.testModel.testElementsAreEqual(c1, c2)); - } - - public void testElementsAreDifferent() { - Collection<String> c1 = new ArrayList<String>(); - c1.add("foo"); - c1.add("bar"); - c1.add("baz"); - Collection<String> c2 = new ArrayList<String>(); - c2.add("baz"); - c2.add("bar"); - c2.add("foo"); - assertTrue(this.testModel.testElementsAreDifferent(c1, c2)); - } - - - // ********** AbstractModel tests ********** - - public void testAbstractModelValuesAreEqual1() { - assertTrue(this.testModel.testValuesAreEqual(null, null)); - } - - public void testAbstractModelValuesAreEqual2() { - assertTrue(this.testModel.testValuesAreEqual("foo", "foo")); - } - - public void testAbstractModelValuesAreEqual3() { - assertFalse(this.testModel.testValuesAreEqual("foo", null)); - } - - public void testAbstractModelValuesAreEqual4() { - assertFalse(this.testModel.testValuesAreEqual(null, "foo")); - } - - public void testAbstractModelValuesAreEqual5() { - assertFalse(this.testModel.testValuesAreEqual("bar", "foo")); - } - - public void testAbstractModelValuesAreDifferent1() { - assertFalse(this.testModel.testValuesAreDifferent(null, null)); - } - - public void testAbstractModelValuesAreDifferent2() { - assertFalse(this.testModel.testValuesAreDifferent("foo", "foo")); - } - - public void testAbstractModelValuesAreDifferent3() { - assertTrue(this.testModel.testValuesAreDifferent("foo", null)); - } - - public void testAbstractModelValuesAreDifferent4() { - assertTrue(this.testModel.testValuesAreDifferent(null, "foo")); - } - - public void testAbstractModelValuesAreDifferent5() { - assertTrue(this.testModel.testValuesAreDifferent("bar", "foo")); - } - - public void testAbstractModelAttributeValueHasChanged1() { - assertFalse(this.testModel.testAttributeValueHasChanged(null, null)); - } - - public void testAbstractModelAttributeValueHasChanged2() { - assertFalse(this.testModel.testAttributeValueHasChanged("foo", "foo")); - } - - public void testAbstractModelAttributeValueHasChanged3() { - assertTrue(this.testModel.testAttributeValueHasChanged("foo", null)); - } - - public void testAbstractModelAttributeValueHasChanged4() { - assertTrue(this.testModel.testAttributeValueHasChanged(null, "foo")); - } - - public void testAbstractModelAttributeValueHasChanged5() { - assertTrue(this.testModel.testAttributeValueHasChanged("bar", "foo")); - } - - public void testAbstractModelAttributeValueHasNotChanged1() { - assertTrue(this.testModel.testAttributeValueHasNotChanged(null, null)); - } - - public void testAbstractModelAttributeValueHasNotChanged2() { - assertTrue(this.testModel.testAttributeValueHasNotChanged("foo", "foo")); - } - - public void testAbstractModelAttributeValueHasNotChanged3() { - assertFalse(this.testModel.testAttributeValueHasNotChanged("foo", null)); - } - - public void testAbstractModelAttributeValueHasNotChanged4() { - assertFalse(this.testModel.testAttributeValueHasNotChanged(null, "foo")); - } - - public void testAbstractModelAttributeValueHasNotChanged5() { - assertFalse(this.testModel.testAttributeValueHasNotChanged("bar", "foo")); - } - - public void testAbstractModelClone() { - assertFalse(this.testModel.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - this.testModel.addChangeListener(this.changeListener); - assertTrue(this.testModel.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - - // verify that the clone does not have any listeners - TestModel clone = this.testModel.clone(); - assertFalse(clone.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - clone.addChangeListener(this.changeListener); - assertTrue(clone.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - // check original - assertTrue(this.testModel.hasAnyPropertyChangeListeners(PROPERTY_NAME)); - - // now test events fired by original - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - this.testModel.testFirePropertyChangedObjectObject(); - this.verifyPropertyChangeEvent(OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - - // now test events fired by clone - this.propertyChangeEvent = null; - this.propertyChangeCalled = false; - clone.testFirePropertyChangedObjectObject(); - this.verifyPropertyChangeEvent(clone, OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - assertTrue(this.propertyChangeCalled); - } - - public void testAbstractModelToString() { - assertTrue(this.testModel.toString().contains('(' + TEST_TO_STRING + ')')); - } - - - // ********** listener implementations ********** - - class Adapter implements ChangeListener { - public void stateChanged(StateChangeEvent e) { - ChangeSupportTests.this.stateChangedCalled = true; - ChangeSupportTests.this.stateChangeEvent = e; - } - - public void propertyChanged(PropertyChangeEvent e) { - ChangeSupportTests.this.propertyChangeCalled = true; - ChangeSupportTests.this.propertyChangeEvent = e; - } - - - public void itemsAdded(CollectionAddEvent e) { - ChangeSupportTests.this.itemsAddedCollectionCalled = true; - ChangeSupportTests.this.collectionEvent = e; - } - public void itemsRemoved(CollectionRemoveEvent e) { - ChangeSupportTests.this.itemsRemovedCollectionCalled = true; - ChangeSupportTests.this.collectionEvent = e; - } - public void collectionCleared(CollectionClearEvent e) { - ChangeSupportTests.this.collectionClearedCalled = true; - ChangeSupportTests.this.collectionEvent = e; - } - public void collectionChanged(CollectionChangeEvent e) { - ChangeSupportTests.this.collectionChangedCalled = true; - ChangeSupportTests.this.collectionEvent = e; - } - - public void itemsAdded(ListAddEvent e) { - ChangeSupportTests.this.itemsAddedListCalled = true; - ChangeSupportTests.this.listEvent = e; - } - public void itemsRemoved(ListRemoveEvent e) { - ChangeSupportTests.this.itemsRemovedListCalled = true; - ChangeSupportTests.this.listEvent = e; - } - public void itemsReplaced(ListReplaceEvent e) { - ChangeSupportTests.this.itemsReplacedListCalled = true; - ChangeSupportTests.this.listEvent = e; - } - public void itemsMoved(ListMoveEvent e) { - ChangeSupportTests.this.itemsMovedListCalled = true; - ChangeSupportTests.this.listEvent = e; - } - public void listCleared(ListClearEvent e) { - ChangeSupportTests.this.listClearedCalled = true; - ChangeSupportTests.this.listEvent = e; - } - public void listChanged(ListChangeEvent e) { - ChangeSupportTests.this.listChangedCalled = true; - ChangeSupportTests.this.listEvent = e; - } - - public void nodeAdded(TreeAddEvent e) { - ChangeSupportTests.this.nodeAddedCalled = true; - ChangeSupportTests.this.treeEvent = e; - } - public void nodeRemoved(TreeRemoveEvent e) { - ChangeSupportTests.this.nodeRemovedCalled = true; - ChangeSupportTests.this.treeEvent = e; - } - public void treeCleared(TreeClearEvent e) { - ChangeSupportTests.this.treeClearedCalled = true; - ChangeSupportTests.this.treeEvent = e; - } - public void treeChanged(TreeChangeEvent e) { - ChangeSupportTests.this.treeChangedCalled = true; - ChangeSupportTests.this.treeEvent = e; - } - } - - - // ********** inner class ********** - - private static class TestModel extends AbstractModel implements Cloneable { - TestModel() { - super(); - } - - // ***** state - public void testFireStateChange() { - this.fireStateChanged(); - } - - // ***** property - public void testFirePropertyChangedEvent() { - this.firePropertyChanged(new PropertyChangeEvent(this, PROPERTY_NAME, OLD_OBJECT_VALUE, NEW_OBJECT_VALUE)); - } - - public void testFirePropertyChangedEventNoChange() { - this.firePropertyChanged(new PropertyChangeEvent(this, PROPERTY_NAME, OLD_OBJECT_VALUE, OLD_OBJECT_VALUE)); - } - - public void testFirePropertyChangedObjectObject() { - this.firePropertyChanged(PROPERTY_NAME, OLD_OBJECT_VALUE, NEW_OBJECT_VALUE); - } - - public void testFirePropertyChangedObjectObjectNoChange() { - this.firePropertyChanged(PROPERTY_NAME, OLD_OBJECT_VALUE, OLD_OBJECT_VALUE); - } - - public void testFirePropertyChangedObject() { - this.firePropertyChanged(PROPERTY_NAME, NEW_OBJECT_VALUE); - } - - public void testFirePropertyChangedObjectNoChange() { - this.firePropertyChanged(PROPERTY_NAME, null); - } - - public void testFirePropertyChangedIntInt() { - this.firePropertyChanged(PROPERTY_NAME, OLD_INT_VALUE.intValue(), NEW_INT_VALUE.intValue()); - } - - public void testFirePropertyChangedIntIntNoChange() { - this.firePropertyChanged(PROPERTY_NAME, OLD_INT_VALUE.intValue(), OLD_INT_VALUE.intValue()); - } - - public void testFirePropertyChangedBooleanBoolean() { - this.firePropertyChanged(PROPERTY_NAME, OLD_BOOLEAN_VALUE.booleanValue(), NEW_BOOLEAN_VALUE.booleanValue()); - } - - public void testFirePropertyChangedBooleanBooleanNoChange() { - this.firePropertyChanged(PROPERTY_NAME, OLD_BOOLEAN_VALUE.booleanValue(), OLD_BOOLEAN_VALUE.booleanValue()); - } - - // ***** collection - public void testFireItemsAddedCollectionEvent() { - this.fireItemsAdded(new CollectionAddEvent(this, COLLECTION_NAME, ADDED_OBJECT_VALUE)); - } - - public void testFireItemsAddedCollectionEventNoChange() { - this.fireItemsAdded(new CollectionAddEvent(this, COLLECTION_NAME, Collections.emptySet())); - } - - public void testFireItemsAddedCollection() { - this.fireItemsAdded(COLLECTION_NAME, Collections.singleton(ADDED_OBJECT_VALUE)); - } - - public void testFireItemsAddedCollectionNoChange() { - this.fireItemsAdded(COLLECTION_NAME, Collections.emptySet()); - } - - public void testFireItemAddedCollection() { - this.fireItemAdded(COLLECTION_NAME, ADDED_OBJECT_VALUE); - } - - public void testFireItemsRemovedCollectionEvent() { - this.fireItemsRemoved(new CollectionRemoveEvent(this, COLLECTION_NAME, REMOVED_OBJECT_VALUE)); - } - - public void testFireItemsRemovedCollectionEventNoChange() { - this.fireItemsRemoved(new CollectionRemoveEvent(this, COLLECTION_NAME, Collections.emptySet())); - } - - public void testFireItemsRemovedCollection() { - this.fireItemsRemoved(COLLECTION_NAME, Collections.singleton(REMOVED_OBJECT_VALUE)); - } - - public void testFireItemsRemovedCollectionNoChange() { - this.fireItemsRemoved(COLLECTION_NAME, Collections.emptySet()); - } - - public void testFireItemRemovedCollection() { - this.fireItemRemoved(COLLECTION_NAME, REMOVED_OBJECT_VALUE); - } - - public void testFireCollectionCleared() { - this.fireCollectionCleared(COLLECTION_NAME); - } - - public void testFireCollectionChangedEvent() { - this.fireCollectionChanged(new CollectionChangeEvent(this, COLLECTION_NAME, Collections.emptySet())); - } - - public void testFireCollectionChanged() { - this.fireCollectionChanged(COLLECTION_NAME, Collections.emptySet()); - } - - public boolean testAddItemToCollection() { - return this.addItemToCollection(ADDED_OBJECT_VALUE, new ArrayList<Object>(), COLLECTION_NAME); - } - - public boolean testAddItemToCollectionNoChange() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(ADDED_OBJECT_VALUE); - return this.addItemToCollection(ADDED_OBJECT_VALUE, collection, COLLECTION_NAME); - } - - public boolean testAddItemsToCollection() { - return this.addItemsToCollection(Collections.singleton(ADDED_OBJECT_VALUE), new ArrayList<Object>(), COLLECTION_NAME); - } - - public boolean testAddItemsToCollectionNoChange() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(ADDED_OBJECT_VALUE); - return this.addItemsToCollection(Collections.singleton(ADDED_OBJECT_VALUE), collection, COLLECTION_NAME); - } - - public boolean testAddItemsToCollectionMixed() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(ADDED_OBJECT_VALUE); - return this.addItemsToCollection(new Object[] {ADDED_OBJECT_VALUE, ADDED_OBJECT_VALUE_2}, collection, COLLECTION_NAME); - } - - public boolean testRemoveItemFromCollection() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - return this.removeItemFromCollection(REMOVED_OBJECT_VALUE, collection, COLLECTION_NAME); - } - - public boolean testRemoveItemFromCollectionNoChange() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - return this.removeItemFromCollection("foo", collection, COLLECTION_NAME); - } - - public boolean testRemoveItemsFromCollection() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - collection.add("foo"); - collection.add("bar"); - return this.removeItemsFromCollection(new Object[] {"foo", "bar", REMOVED_OBJECT_VALUE}, collection, COLLECTION_NAME); - } - - public boolean testRemoveItemsFromCollectionNoChange1() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - return this.removeItemsFromCollection(Collections.emptySet(), collection, COLLECTION_NAME); - } - - public boolean testRemoveItemsFromCollectionNoChange2() { - Collection<Object> collection = new HashSet<Object>(); - return this.removeItemsFromCollection(Collections.singleton("foo"), collection, COLLECTION_NAME); - } - - public boolean testRemoveItemsFromCollectionNoChange3() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - return this.removeItemsFromCollection(Collections.singleton("foo"), collection, COLLECTION_NAME); - } - - public boolean testRetainItemsInCollection1() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - collection.add("foo"); - collection.add("bar"); - return this.retainItemsInCollection(new Object[] {"foo", "bar"}, collection, COLLECTION_NAME); - } - - public boolean testRetainItemsInCollection2() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - collection.add("foo"); - collection.add("bar"); - return this.retainItemsInCollection(Collections.emptySet(), collection, COLLECTION_NAME); - } - - public boolean testRetainItemsInCollectionNoChange1() { - Collection<Object> collection = new HashSet<Object>(); - return this.retainItemsInCollection(new Object[] {"foo", "bar"}, collection, COLLECTION_NAME); - } - - public boolean testRetainItemsInCollectionNoChange2() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - collection.add("foo"); - collection.add("bar"); - return this.retainItemsInCollection(new Object[] {"foo", "bar", REMOVED_OBJECT_VALUE}, collection, COLLECTION_NAME); - } - - public boolean testClearCollection() { - Collection<Object> collection = new HashSet<Object>(); - collection.add(REMOVED_OBJECT_VALUE); - collection.add("foo"); - collection.add("bar"); - return this.clearCollection(collection, COLLECTION_NAME); - } - - public boolean testClearCollectionNoChange() { - Collection<Object> collection = new HashSet<Object>(); - return this.clearCollection(collection, COLLECTION_NAME); - } - - public boolean testSynchronizeCollection1() { - Collection<Object> collection = new HashSet<Object>(); - collection.add("foo"); - collection.add("bar"); - collection.add("baz"); - Collection<Object> newCollection = new HashSet<Object>(); - newCollection.add("joo"); - newCollection.add("jar"); - newCollection.add("baz"); - boolean result = this.synchronizeCollection(newCollection, collection, COLLECTION_NAME); - assertEquals(newCollection, collection); - return result; - } - - public boolean testSynchronizeCollection2() { - Collection<Object> collection = new HashSet<Object>(); - collection.add("foo"); - collection.add("bar"); - collection.add("baz"); - Collection<Object> newCollection = new HashSet<Object>(); - boolean result = this.synchronizeCollection(newCollection, collection, COLLECTION_NAME); - assertEquals(newCollection, collection); - return result; - } - - public boolean testSynchronizeCollection3() { - Collection<Object> collection = new HashSet<Object>(); - Collection<Object> newCollection = new HashSet<Object>(); - newCollection.add("joo"); - newCollection.add("jar"); - newCollection.add("baz"); - boolean result = this.synchronizeCollection(newCollection, collection, COLLECTION_NAME); - assertEquals(newCollection, collection); - return result; - } - - // ***** list - public void testFireItemsAddedListEvent() { - this.fireItemsAdded(new ListAddEvent(this, LIST_NAME, ADD_INDEX, ADDED_OBJECT_VALUE)); - } - - public void testFireItemsAddedListEventNoChange() { - this.fireItemsAdded(new ListAddEvent(this, LIST_NAME, ADD_INDEX, Collections.emptyList())); - } - - public void testFireItemsAddedList() { - this.fireItemsAdded(LIST_NAME, ADD_INDEX, Collections.singletonList(ADDED_OBJECT_VALUE)); - } - - public void testFireItemsAddedListNoChange() { - this.fireItemsAdded(LIST_NAME, ADD_INDEX, Collections.emptyList()); - } - - public void testFireItemAddedList() { - this.fireItemAdded(LIST_NAME, ADD_INDEX, ADDED_OBJECT_VALUE); - } - - public void testFireItemsRemovedListEvent() { - this.fireItemsRemoved(new ListRemoveEvent(this, LIST_NAME, REMOVE_INDEX, REMOVED_OBJECT_VALUE)); - } - - public void testFireItemsRemovedListEventNoChange() { - this.fireItemsRemoved(new ListRemoveEvent(this, LIST_NAME, REMOVE_INDEX, Collections.emptyList())); - } - - public void testFireItemsRemovedList() { - this.fireItemsRemoved(LIST_NAME, REMOVE_INDEX, Collections.singletonList(REMOVED_OBJECT_VALUE)); - } - - public void testFireItemsRemovedListNoChange() { - this.fireItemsRemoved(LIST_NAME, REMOVE_INDEX, Collections.emptyList()); - } - - public void testFireItemRemovedList() { - this.fireItemRemoved(LIST_NAME, REMOVE_INDEX, REMOVED_OBJECT_VALUE); - } - - public void testFireItemsReplacedListEvent() { - this.fireItemsReplaced(new ListReplaceEvent(this, LIST_NAME, REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE)); - } - - public void testFireItemsReplacedListEventNoChange() { - this.fireItemsReplaced(new ListReplaceEvent(this, LIST_NAME, REPLACE_INDEX, Collections.emptyList(), Collections.emptyList())); - } - - public void testFireItemsReplacedList() { - this.fireItemsReplaced(LIST_NAME, REPLACE_INDEX, Collections.singletonList(ADDED_OBJECT_VALUE), Collections.singletonList(REMOVED_OBJECT_VALUE)); - } - - public void testFireItemsReplacedListNoChange() { - this.fireItemsReplaced(LIST_NAME, REPLACE_INDEX, Collections.emptyList(), Collections.emptyList()); - } - - public void testFireItemReplacedList() { - this.fireItemReplaced(LIST_NAME, REPLACE_INDEX, ADDED_OBJECT_VALUE, REMOVED_OBJECT_VALUE); - } - - public void testFireItemsMovedListEvent() { - this.fireItemsMoved(new ListMoveEvent(this, LIST_NAME, TARGET_INDEX, SOURCE_INDEX, 1)); - } - - public void testFireItemsMovedListEventNoChange() { - this.fireItemsMoved(new ListMoveEvent(this, LIST_NAME, SOURCE_INDEX, SOURCE_INDEX, 1)); - } - - public void testFireItemsMovedList() { - this.fireItemsMoved(LIST_NAME, TARGET_INDEX, SOURCE_INDEX, 1); - } - - public void testFireItemsMovedListNoChange() { - this.fireItemsMoved(LIST_NAME, SOURCE_INDEX, SOURCE_INDEX, 1); - } - - public void testFireItemMovedList() { - this.fireItemMoved(LIST_NAME, TARGET_INDEX, SOURCE_INDEX); - } - - public void testFireListClearedEvent() { - this.fireListCleared(new ListClearEvent(this, LIST_NAME)); - } - - public void testFireListCleared() { - this.fireListCleared(LIST_NAME); - } - - public void testFireListChangedEvent() { - this.fireListChanged(new ListChangeEvent(this, LIST_NAME, Collections.emptyList())); - } - - public void testFireListChanged() { - this.fireListChanged(LIST_NAME, Collections.emptyList()); - } - - public void testAddItemToListIndex() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemToList(2, "joo", list, LIST_NAME); - } - - public void testAddItemToList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemToList("joo", list, LIST_NAME); - } - - public void testAddItemsToListIndex() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemsToList(2, Collections.singletonList("joo"), list, LIST_NAME); - } - - public void testAddItemsToListIndexNoChange() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemsToList(2, Collections.<String>emptyList(), list, LIST_NAME); - } - - public void testAddItemsToList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemsToList(Collections.singletonList("joo"), list, LIST_NAME); - } - - public void testAddItemsToListNoChange() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemsToList(Collections.<String>emptyList(), list, LIST_NAME); - } - - public void testRemoveItemFromListIndex() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.removeItemFromList(1, list, LIST_NAME); - } - - public void testRemoveItemFromList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.removeItemFromList("bar", list, LIST_NAME); - } - - public void testRemoveItemsFromListIndex() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.removeItemsFromList(1, 1, list, LIST_NAME); - } - - public void testRemoveItemsFromListIndexNoChange() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.removeItemsFromList(2, 0, list, LIST_NAME); - } - - public void testRemoveItemsFromList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.removeItemsFromList(Collections.singletonList("bar"), list, LIST_NAME); - } - - public void testRemoveItemsFromListNoChange() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.addItemsToList(Collections.<String>emptyList(), list, LIST_NAME); - } - - public void testRetainItemsInList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.retainItemsInList(new String[] {"bar", "baz"}, list, LIST_NAME); - } - - public void testReplaceItemInList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.replaceItemInList("bar", "xxx", list, LIST_NAME); - } - - public void testSetItemsInList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.setItemsInList(1, new String[] {"xxx"}, list, LIST_NAME); - } - - public void testMoveItemsInList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - list.add("xxx"); - list.add("yyy"); - list.add("zzz"); - this.moveItemsInList(2, 4, 2, list, LIST_NAME); - } - - public void testClearList() { - List<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - list.add("baz"); - this.clearList(list, LIST_NAME); - } - - public void testSynchronizeList() { - List<String> oldList = new ArrayList<String>(); - oldList.add("foo"); - oldList.add("bar"); - oldList.add("baz"); - oldList.add("xxx"); - oldList.add("yyy"); - oldList.add("zzz"); - List<String> newList = new ArrayList<String>(); - newList.add("foo"); - newList.add("ppp"); - newList.add("baz"); - newList.add("xxx"); - newList.add("qqq"); - this.synchronizeList(newList, oldList, LIST_NAME); - assertEquals(newList, oldList); - } - - // ***** tree - public void testFireNodeAddedTreeEvent() { - this.fireNodeAdded(new TreeAddEvent(this, TREE_NAME, OBJECT_PATH)); - } - - public void testFireNodeAddedTree() { - this.fireNodeAdded(TREE_NAME, OBJECT_PATH); - } - - public void testFireNodeRemovedTreeEvent() { - this.fireNodeRemoved(new TreeRemoveEvent(this, TREE_NAME, OBJECT_PATH)); - } - - public void testFireNodeRemovedTree() { - this.fireNodeRemoved(TREE_NAME, OBJECT_PATH); - } - - public void testFireTreeClearedEvent() { - this.fireTreeCleared(new TreeClearEvent(this, TREE_NAME)); - } - - public void testFireTreeCleared() { - this.fireTreeCleared(TREE_NAME); - } - - public void testFireTreeChangedEvent() { - this.fireTreeChanged(new TreeChangeEvent(this, TREE_NAME, OBJECT_PATH)); - } - - public void testFireTreeChanged() { - this.fireTreeChanged(TREE_NAME, OBJECT_PATH); - } - - public boolean testAttributeValueHasChanged(Object value1, Object value2) { - return this.attributeValueHasChanged(value1, value2); - } - - public boolean testAttributeValueHasNotChanged(Object value1, Object value2) { - return this.attributeValueHasNotChanged(value1, value2); - } - - // ***** misc - @Override - public TestModel clone() { - try { - return (TestModel) super.clone(); - } catch (CloneNotSupportedException ex) { - throw new InternalError(); - } - } - - public boolean testValuesAreDifferent(Object value1, Object value2) { - return this.valuesAreDifferent(value1, value2); - } - - public boolean testValuesAreEqual(Object value1, Object value2) { - return this.valuesAreEqual(value1, value2); - } - - public boolean testElementsAreDifferent(Iterable<?> iterable1, Iterable<?> iterable2) { - return this.getChangeSupport().elementsAreDifferent(iterable1, iterable2); - } - - public boolean testElementsAreEqual(Iterable<?> iterable1, Iterable<?> iterable2) { - return this.getChangeSupport().elementsAreEqual(iterable1, iterable2); - } - - @Override - public void toString(StringBuilder sb) { - sb.append(TEST_TO_STRING); - } - - } - - - // ********** serialization test ********** - public void testSerialization() throws java.io.IOException, ClassNotFoundException { - if (Tools.jvmIsSun()) { - // This test doesn't pass in the Eclipse build environment (Linux/IBM JVM) for some reason - this.verifySerialization(); - } - } - - private void verifySerialization() throws java.io.IOException, ClassNotFoundException { - LocalModel model1 = new LocalModel(); - Foo foo1 = new Foo(); - Bar bar1 = new Bar(); - Joo joo1 = new Joo(); - Jar jar1 = new Jar(); - model1.addStateChangeListener(foo1); - model1.addStateChangeListener(bar1); - model1.addListChangeListener("foo", joo1); - model1.addListChangeListener("foo", jar1); - - Iterable<EventListener> listeners1 = this.getListeners(model1, StateChangeListener.class, null); - Object[] listenersArray1 = ArrayTools.array(listeners1); - assertEquals(2, listenersArray1.length); - // the order of these could change... - assertEquals(Foo.class, listenersArray1[0].getClass()); - assertEquals(Bar.class, listenersArray1[1].getClass()); - - listeners1 = this.getListeners(model1, ListChangeListener.class, "foo"); - listenersArray1 = ArrayTools.array(listeners1); - assertEquals(2, listenersArray1.length); - // the order of these could change... - assertEquals(Joo.class, listenersArray1[0].getClass()); - assertEquals(Jar.class, listenersArray1[1].getClass()); - - LocalModel model2 = TestTools.serialize(model1); - - Iterable<EventListener> listeners2 = this.getListeners(model2, StateChangeListener.class, null); - Object[] listenersArray2 = ArrayTools.array(listeners2); - assertEquals(1, listenersArray2.length); - assertEquals(Foo.class, listenersArray2[0].getClass()); - - listeners2 = this.getListeners(model2, ListChangeListener.class, "foo"); - listenersArray2 = ArrayTools.array(listeners2); - assertEquals(1, listenersArray2.length); - assertEquals(Joo.class, listenersArray2[0].getClass()); - } - - private Iterable<EventListener> getListeners(LocalModel model, Class<? extends EventListener> listenerClass, String aspectName) { - return this.getListenerList(model, listenerClass, aspectName).getListeners(); - } - - @SuppressWarnings("unchecked") - private ListenerList<EventListener> getListenerList(LocalModel model, Class<? extends EventListener> listenerClass, String aspectName) { - ChangeSupport changeSupport = (ChangeSupport) ReflectionTools.getFieldValue(model, "changeSupport"); - return (ListenerList<EventListener>) ReflectionTools.executeMethod(changeSupport, "getListenerList_", new Class<?>[] {Class.class, String.class}, new Object[] {listenerClass, aspectName}); - } - - // we have to manually handle 'changeSupport' since AbstractModel is not Serializable - private static class LocalModel extends AbstractModel implements Serializable { - LocalModel() { - super(); - } - private synchronized void writeObject(ObjectOutputStream s) throws IOException { - s.defaultWriteObject(); - s.writeObject(this.changeSupport); - } - private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { - s.defaultReadObject(); - this.changeSupport = (ChangeSupport) s.readObject(); - } - } - - private static class Foo implements Serializable, StateChangeListener { - Foo() { - super(); - } - public void stateChanged(StateChangeEvent event) { - // do nothing - } - } - - private static class Bar implements StateChangeListener { - Bar() { - super(); - } - public void stateChanged(StateChangeEvent event) { - // do nothing - } - } - - private static class Joo extends ListChangeAdapter implements Serializable { - Joo() { - super(); - } - } - - private static class Jar extends ListChangeAdapter { - Jar() { - super(); - } - } - - - // ********** bug(?) test ********** - - private static final String ISE_MESSAGE = "this object is no longer listening to localA"; - - /** - * Test the following situation: - * - both B and C are listening to A - * - C is also listening to B - * - when B receives an event from A, it will fire an event to C - * - when C receives an event from B, it will STOP listening to A - * - the event from B to C may be preceded or followed (depending on - * the hash positions of listeners) by an event from A to C: - * - if the A to C event comes first, no problem - * - but if the A to B event comes first, the A to C event should NOT happen - */ - public void testIndirectRemoveStateListener() { - this.verifyIndirectRemoveListener( - new NotifyCommand() { - public void notifyListeners(LocalA localA) { - localA.notifyStateListeners(); - } - } - ); - } - - public void testIndirectRemovePropertyListener() { - this.verifyIndirectRemoveListener( - new NotifyCommand() { - public void notifyListeners(LocalA localA) { - localA.notifyPropertyListeners(); - } - } - ); - } - - public void testIndirectRemoveCollectionListener() { - this.verifyIndirectRemoveListener( - new NotifyCommand() { - public void notifyListeners(LocalA localA) { - localA.notifyCollectionListeners(); - } - } - ); - } - - public void testIndirectRemoveListListener() { - this.verifyIndirectRemoveListener( - new NotifyCommand() { - public void notifyListeners(LocalA localA) { - localA.notifyListListeners(); - } - } - ); - } - - public void testIndirectRemoveTreeListener() { - this.verifyIndirectRemoveListener( - new NotifyCommand() { - public void notifyListeners(LocalA localA) { - localA.notifyTreeListeners(); - } - } - ); - } - - public void verifyIndirectRemoveListener(NotifyCommand command) { - LocalA localA = new LocalA(); - LocalB localB = new LocalB(localA); - - // build a bunch of LocalCs so at least one of them is notified AFTER the LocalB; - // using 1000 seemed to fail very consistently before ChangeSupport was fixed - LocalC[] localCs = new LocalC[1000]; - for (int i = localCs.length; i-- > 0; ) { - localCs[i] = new LocalC(localA, localB); - } - - boolean exCaught = false; - try { - command.notifyListeners(localA); - } catch (IllegalStateException ex) { - if (ex.getMessage() == ISE_MESSAGE) { - exCaught = true; - } else { - throw ex; - } - } - assertFalse(exCaught); - - for (int i = localCs.length; i-- > 0; ) { - assertFalse(localCs[i].isListeningToLocalA()); - } - } - - private interface NotifyCommand { - void notifyListeners(LocalA localA); - } - - /** - * This object simply fires a state change event. Both LocalB and LocalC - * will be listeners. - */ - private static class LocalA extends AbstractModel { - LocalA() { - super(); - } - void notifyStateListeners() { - this.fireStateChanged(); - } - void notifyPropertyListeners() { - this.firePropertyChanged("foo", 1, 2); - } - void notifyCollectionListeners() { - this.fireCollectionChanged("foo", Collections.emptySet()); - } - void notifyListListeners() { - this.fireListChanged("foo", Collections.emptyList()); - } - void notifyTreeListeners() { - this.fireTreeChanged("foo", Collections.emptySet()); - } - } - - /** - * This object will fire state change events whenever it receives - * a state change event from localA. - */ - private static class LocalB - extends AbstractModel - implements ChangeListener - { - LocalB(LocalA localA) { - super(); - localA.addChangeListener(this); - } - - public void stateChanged(StateChangeEvent e) { - this.fireStateChanged(); - } - - public void propertyChanged(PropertyChangeEvent evt) { - this.firePropertyChanged("bar", 1, 2); - } - - public void collectionChanged(CollectionChangeEvent e) { - this.fireCollectionChanged("bar", Collections.emptySet()); - } - public void collectionCleared(CollectionClearEvent e) {/*ignore*/} - public void itemsAdded(CollectionAddEvent e) {/*ignore*/} - public void itemsRemoved(CollectionRemoveEvent e) {/*ignore*/} - - public void listChanged(ListChangeEvent e) { - this.fireListChanged("bar", Collections.emptyList()); - } - public void listCleared(ListClearEvent e) {/*ignore*/} - public void itemsAdded(ListAddEvent e) {/*ignore*/} - public void itemsRemoved(ListRemoveEvent e) {/*ignore*/} - public void itemsReplaced(ListReplaceEvent e) {/*ignore*/} - public void itemsMoved(ListMoveEvent e) {/*ignore*/} - - public void treeChanged(TreeChangeEvent e) { - this.fireTreeChanged("bar", Collections.emptySet()); - } - public void treeCleared(TreeClearEvent e) {/*ignore*/} - public void nodeAdded(TreeAddEvent e) {/*ignore*/} - public void nodeRemoved(TreeRemoveEvent e) {/*ignore*/} - - } - - /** - * This object will listen to two other objects, localA and localB. - * If this object receives notification from localB, it will stop listening to - * localA. If this object receives notification from localA, it will check to - * see whether it still listening to localA. If this object is no longer - * listening to localA, it will complain about receiving the event and - * throw an exception. - */ - private static class LocalC - extends AbstractModel - implements ChangeListener - { - private LocalA localA; - private LocalB localB; - private boolean listeningToLocalA; - - LocalC(LocalA localA, LocalB localB) { - super(); - this.localA = localA; - this.localB = localB; - - localA.addChangeListener(this); - this.listeningToLocalA = true; - - localB.addChangeListener(this); - } - boolean isListeningToLocalA() { - return this.listeningToLocalA; - } - - public void stateChanged(StateChangeEvent e) { - Object source = e.getSource(); - if (source == this.localA) { - if ( ! this.listeningToLocalA) { - throw new IllegalStateException(ISE_MESSAGE); - } - } else if (source == this.localB) { - this.localA.removeChangeListener(this); - this.listeningToLocalA = false; - } else { - throw new IllegalStateException("bogus event source: " + source); - } - } - - public void propertyChanged(PropertyChangeEvent e) { - Object source = e.getSource(); - if (source == this.localA) { - if ( ! this.listeningToLocalA) { - throw new IllegalStateException(ISE_MESSAGE); - } - } else if (source == this.localB) { - this.localA.removeChangeListener(this); - this.listeningToLocalA = false; - } else { - throw new IllegalStateException("bogus event source: " + source); - } - } - - public void collectionChanged(CollectionChangeEvent e) { - Object source = e.getSource(); - if (source == this.localA) { - if ( ! this.listeningToLocalA) { - throw new IllegalStateException(ISE_MESSAGE); - } - } else if (source == this.localB) { - this.localA.removeChangeListener(this); - this.listeningToLocalA = false; - } else { - throw new IllegalStateException("bogus event source: " + source); - } - } - public void collectionCleared(CollectionClearEvent e) {/*ignore*/} - public void itemsAdded(CollectionAddEvent e) {/*ignore*/} - public void itemsRemoved(CollectionRemoveEvent e) {/*ignore*/} - - public void listChanged(ListChangeEvent e) { - Object source = e.getSource(); - if (source == this.localA) { - if ( ! this.listeningToLocalA) { - throw new IllegalStateException(ISE_MESSAGE); - } - } else if (source == this.localB) { - this.localA.removeChangeListener(this); - this.listeningToLocalA = false; - } else { - throw new IllegalStateException("bogus event source: " + source); - } - } - public void listCleared(ListClearEvent e) {/*ignore*/} - public void itemsAdded(ListAddEvent e) {/*ignore*/} - public void itemsRemoved(ListRemoveEvent e) {/*ignore*/} - public void itemsReplaced(ListReplaceEvent e) {/*ignore*/} - public void itemsMoved(ListMoveEvent e) {/*ignore*/} - - public void treeChanged(TreeChangeEvent e) { - Object source = e.getSource(); - if (source == this.localA) { - if ( ! this.listeningToLocalA) { - throw new IllegalStateException(ISE_MESSAGE); - } - } else if (source == this.localB) { - this.localA.removeChangeListener(this); - this.listeningToLocalA = false; - } else { - throw new IllegalStateException("bogus event source: " + source); - } - } - public void treeCleared(TreeClearEvent e) {/*ignore*/} - public void nodeAdded(TreeAddEvent e) {/*ignore*/} - public void nodeRemoved(TreeRemoveEvent e) {/*ignore*/} - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/JptUtilityModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/JptUtilityModelTests.java deleted file mode 100644 index f4f64ef801..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/JptUtilityModelTests.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.eclipse.jpt.common.utility.tests.internal.model.listener.JptUtilityModelListenerTests; -import org.eclipse.jpt.common.utility.tests.internal.model.value.JptUtilityModelValueTests; - -public class JptUtilityModelTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityModelTests.class.getPackage().getName()); - - suite.addTest(JptUtilityModelListenerTests.suite()); - suite.addTest(JptUtilityModelValueTests.suite()); - - suite.addTestSuite(ChangeSupportTests.class); - suite.addTestSuite(NewEventTests.class); - suite.addTestSuite(SingleAspectChangeSupportTests.class); - - return suite; - } - - private JptUtilityModelTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/NewEventTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/NewEventTests.java deleted file mode 100644 index 2ce4ac0c49..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/NewEventTests.java +++ /dev/null @@ -1,181 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model; - -import java.util.EventListener; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ListenerList; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.ChangeSupport; -import org.eclipse.jpt.common.utility.model.Model; -import org.eclipse.jpt.common.utility.model.event.ChangeEvent; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -/** - * test what it takes to add a new type of event to - * model and change support - */ -public class NewEventTests extends TestCase { - private Foo foo; - - public NewEventTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.foo = new Foo(); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testHasNoFooChangeListeners() { - assertTrue(this.foo.hasNoFooChangeListeners()); - LocalListener listener = new LocalListener(); - this.foo.addFooChangeListener(listener); - assertFalse(this.foo.hasNoFooChangeListeners()); - this.foo.removeFooChangeListener(listener); - assertTrue(this.foo.hasNoFooChangeListeners()); - } - - public void testHasAnyFooChangeListeners() { - assertFalse(this.foo.hasAnyFooChangeListeners()); - LocalListener listener = new LocalListener(); - this.foo.addFooChangeListener(listener); - assertTrue(this.foo.hasAnyFooChangeListeners()); - this.foo.removeFooChangeListener(listener); - assertFalse(this.foo.hasAnyFooChangeListeners()); - } - - public void testFireFooChangeEvent() { - LocalListener listener = new LocalListener(); - assertFalse(listener.receivedFooEvent); - this.foo.addFooChangeListener(listener); - this.foo.foo(); - assertTrue(listener.receivedFooEvent); - } - - - // ********** harness classes ********** - - class Foo extends AbstractFooModel { - Foo() { - super(); - } - void foo() { - this.fireFooChangeEvent(); - } - } - - class LocalListener implements FooChangeListener { - boolean receivedFooEvent = false; - LocalListener() { - super(); - } - public void fooChanged(FooChangeEvent event) { - this.receivedFooEvent = true; - } - } - - interface FooModel extends Model { - void addFooChangeListener(FooChangeListener listener); - void removeFooChangeListener(FooChangeListener listener); - } - - interface FooChangeListener extends EventListener { - void fooChanged(FooChangeEvent event); - } - - static class FooChangeEvent extends ChangeEvent { - private static final long serialVersionUID = 1L; - public FooChangeEvent(FooModel source) { - super(source); - } - public FooChangeEvent clone(Model newSource) { - return new FooChangeEvent((FooModel) newSource); - } - } - - static class AbstractFooModel extends AbstractModel implements FooModel { - @Override - protected synchronized FooChangeSupport getChangeSupport() { - return (FooChangeSupport) super.getChangeSupport(); - } - @Override - protected ChangeSupport buildChangeSupport() { - return new FooChangeSupport(this); - } - public void addFooChangeListener(FooChangeListener listener) { - this.getChangeSupport().addFooChangeListener(listener); - } - public void removeFooChangeListener(FooChangeListener listener) { - this.getChangeSupport().removeFooChangeListener(listener); - } - protected void fireFooChangeEvent() { - this.getChangeSupport().fireFooChanged(); - } - public boolean hasAnyFooChangeListeners() { - return this.getChangeSupport().hasAnyFooChangeListeners(); - } - public boolean hasNoFooChangeListeners() { - return ! this.hasAnyFooChangeListeners(); - } - } - - static class FooChangeSupport extends ChangeSupport { - FooChangeSupport(FooModel source) { - super(source); - } - protected static final Class<FooChangeListener> FOO_CHANGE_LISTENER_CLASS = FooChangeListener.class; - void addFooChangeListener(FooChangeListener listener) { - this.addListener(FOO_CHANGE_LISTENER_CLASS, listener); - } - void removeFooChangeListener(FooChangeListener listener) { - this.removeListener(FOO_CHANGE_LISTENER_CLASS, listener); - } - public boolean hasAnyFooChangeListeners() { - return this.hasAnyListeners(FOO_CHANGE_LISTENER_CLASS); - } - private ListenerList<FooChangeListener> getFooChangeListenerList() { - return this.getListenerList(FOO_CHANGE_LISTENER_CLASS); - } - private Iterable<FooChangeListener> getFooChangeListeners() { - ListenerList<FooChangeListener> listenerList = this.getFooChangeListenerList(); - return (listenerList == null) ? null : listenerList.getListeners(); - } - private boolean hasFooChangeListener(FooChangeListener listener) { - return CollectionTools.contains(this.getFooChangeListeners(), listener); - } - public void fireFooChanged() { - Iterable<FooChangeListener> listeners = this.getFooChangeListeners(); - if (listeners != null) { - FooChangeEvent event = null; - for (FooChangeListener listener : listeners) { - if (this.hasFooChangeListener(listener)) { - if (event == null) { - // here's the reason for the duplicate code... - event = new FooChangeEvent((FooModel) this.source); - } - listener.fooChanged(event); - } - } - } - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/SingleAspectChangeSupportTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/SingleAspectChangeSupportTests.java deleted file mode 100644 index a0dae05267..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/SingleAspectChangeSupportTests.java +++ /dev/null @@ -1,192 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.ChangeSupport; -import org.eclipse.jpt.common.utility.internal.model.SingleAspectChangeSupport; -import org.eclipse.jpt.common.utility.model.Model; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.listener.StateChangeListener; -import org.eclipse.jpt.common.utility.model.listener.TreeChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.TreeChangeListener; - -@SuppressWarnings("nls") -public class SingleAspectChangeSupportTests extends TestCase { - - public SingleAspectChangeSupportTests(String name) { - super(name); - } - - public void testAddPropertyChangeListenerInvalidClass() { - Model model = new StateTestModel(); - boolean exCaught = false; - PropertyChangeListener listener = new PropertyChangeAdapter(); - try { - model.addPropertyChangeListener("foo", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddPropertyChangeListenerInvalidAspect() { - Model model = new PropertyTestModel(); - boolean exCaught = false; - PropertyChangeListener listener = new PropertyChangeAdapter(); - try { - model.addPropertyChangeListener("bar", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddCollectionChangeListenerInvalidClass() { - Model model = new StateTestModel(); - boolean exCaught = false; - CollectionChangeListener listener = new CollectionChangeAdapter(); - try { - model.addCollectionChangeListener("foo", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddCollectionChangeListenerInvalidAspect() { - Model model = new CollectionTestModel(); - boolean exCaught = false; - CollectionChangeListener listener = new CollectionChangeAdapter(); - try { - model.addCollectionChangeListener("bar", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddListChangeListenerInvalidClass() { - Model model = new StateTestModel(); - boolean exCaught = false; - ListChangeListener listener = new ListChangeAdapter(); - try { - model.addListChangeListener("foo", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddListChangeListenerInvalidAspect() { - Model model = new ListTestModel(); - boolean exCaught = false; - ListChangeListener listener = new ListChangeAdapter(); - try { - model.addListChangeListener("bar", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddTreeChangeListenerInvalidClass() { - Model model = new StateTestModel(); - boolean exCaught = false; - TreeChangeListener listener = new TreeChangeAdapter(); - try { - model.addTreeChangeListener("foo", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testAddTreeChangeListenerInvalidAspect() { - Model model = new TreeTestModel(); - boolean exCaught = false; - TreeChangeListener listener = new TreeChangeAdapter(); - try { - model.addTreeChangeListener("bar", listener); - fail("bogus listener: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - // ********** test models ********** - - static class StateTestModel extends AbstractModel { - StateTestModel() { - super(); - } - @Override - protected ChangeSupport buildChangeSupport() { - return new SingleAspectChangeSupport(this, StateChangeListener.class, null); - } - } - - static class PropertyTestModel extends AbstractModel { - PropertyTestModel() { - super(); - } - @Override - protected ChangeSupport buildChangeSupport() { - return new SingleAspectChangeSupport(this, PropertyChangeListener.class, "foo"); - } - } - - static class CollectionTestModel extends AbstractModel { - CollectionTestModel() { - super(); - } - @Override - protected ChangeSupport buildChangeSupport() { - return new SingleAspectChangeSupport(this, CollectionChangeListener.class, "foo"); - } - } - - static class ListTestModel extends AbstractModel { - ListTestModel() { - super(); - } - @Override - protected ChangeSupport buildChangeSupport() { - return new SingleAspectChangeSupport(this, ListChangeListener.class, "foo"); - } - } - - static class TreeTestModel extends AbstractModel { - TreeTestModel() { - super(); - } - @Override - protected ChangeSupport buildChangeSupport() { - return new SingleAspectChangeSupport(this, TreeChangeListener.class, "foo"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/JptUtilityModelListenerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/JptUtilityModelListenerTests.java deleted file mode 100644 index 1de3f75c49..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/JptUtilityModelListenerTests.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.listener; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class JptUtilityModelListenerTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityModelListenerTests.class.getPackage().getName()); - - suite.addTestSuite(ReflectiveCollectionChangeListenerTests.class); - suite.addTestSuite(ReflectiveListChangeListenerTests.class); - suite.addTestSuite(ReflectivePropertyChangeListenerTests.class); - suite.addTestSuite(ReflectiveStateChangeListenerTests.class); - suite.addTestSuite(ReflectiveTreeChangeListenerTests.class); - - return suite; - } - - private JptUtilityModelListenerTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveCollectionChangeListenerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveCollectionChangeListenerTests.java deleted file mode 100644 index 96ae5c351a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveCollectionChangeListenerTests.java +++ /dev/null @@ -1,331 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.listener; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.CloneIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ReflectiveChangeListener; - -@SuppressWarnings("nls") -public class ReflectiveCollectionChangeListenerTests extends TestCase { - - public ReflectiveCollectionChangeListenerTests(String name) { - super(name); - } - - private CollectionChangeListener buildZeroArgumentListener(Object target) { - return ReflectiveChangeListener.buildCollectionChangeListener(target, "itemAddedZeroArgument", "itemRemovedZeroArgument", "collectionClearedZeroArgument", "collectionChangedZeroArgument"); - } - - private CollectionChangeListener buildSingleArgumentListener(Object target) { - return ReflectiveChangeListener.buildCollectionChangeListener(target, "itemAddedSingleArgument", "itemRemovedSingleArgument", "collectionClearedSingleArgument", "collectionChangedSingleArgument"); - } - - public void testItemAddedZeroArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildZeroArgumentListener(target)); - testModel.addString(string); - assertTrue(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testItemAddedSingleArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildSingleArgumentListener(target)); - testModel.addString(string); - assertFalse(target.itemAddedZeroArgumentFlag); - assertTrue(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testItemRemovedZeroArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildZeroArgumentListener(target)); - testModel.removeString(string); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertTrue(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testItemRemovedSingleArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildSingleArgumentListener(target)); - testModel.removeString(string); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertTrue(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testCollectionClearedZeroArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildZeroArgumentListener(target)); - testModel.clearStrings(); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertTrue(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testCollectionClearedSingleArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildSingleArgumentListener(target)); - testModel.clearStrings(); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertTrue(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testCollectionChangedZeroArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildZeroArgumentListener(target)); - testModel.replaceStrings(new String[] {"bar", "baz"}); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertTrue(target.collectionChangedZeroArgumentFlag); - assertFalse(target.collectionChangedSingleArgumentFlag); - } - - public void testCollectionChangedSingleArgumentNamedCollection() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - testModel.addCollectionChangeListener(TestModel.STRINGS_COLLECTION, this.buildSingleArgumentListener(target)); - testModel.replaceStrings(new String[] {"bar", "baz"}); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.collectionClearedZeroArgumentFlag); - assertFalse(target.collectionClearedSingleArgumentFlag); - assertFalse(target.collectionChangedZeroArgumentFlag); - assertTrue(target.collectionChangedSingleArgumentFlag); - } - - public void testBogusDoubleArgument1() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - boolean exCaught = false; - try { - CollectionChangeListener listener = ReflectiveChangeListener.buildCollectionChangeListener(target, "collectionChangedDoubleArgument"); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getCause().getClass() == NoSuchMethodException.class) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - public void testBogusDoubleArgument2() throws Exception { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - Method method = ReflectionTools.getMethod(target, "collectionChangedDoubleArgument", new Class[] {CollectionChangeEvent.class, Object.class}); - boolean exCaught = false; - try { - CollectionChangeListener listener = ReflectiveChangeListener.buildCollectionChangeListener(target, method); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getMessage().equals(method.toString())) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - public void testListenerMismatch() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_COLLECTION, string); - // build a COLLECTION change listener and hack it so we - // can add it as a LIST change listener - Object listener = ReflectiveChangeListener.buildCollectionChangeListener(target, "collectionEventSingleArgument"); - testModel.addListChangeListener("bogus list", (ListChangeListener) listener); - - boolean exCaught = false; - try { - testModel.changeList(); - fail("listener mismatch: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - class TestModel extends AbstractModel { - private Collection<String> strings = new ArrayList<String>(); - public static final String STRINGS_COLLECTION = "strings"; - TestModel() { - super(); - } - Iterator<String> strings() { - return new CloneIterator<String>(this.strings) { - @Override - protected void remove(String s) { - TestModel.this.removeString(s); - } - }; - } - void addString(String string) { - this.addItemToCollection(string, this.strings, STRINGS_COLLECTION); - } - void removeString(String string) { - this.removeItemFromCollection(string, this.strings, STRINGS_COLLECTION); - } - void clearStrings() { - this.clearCollection(this.strings, STRINGS_COLLECTION); - } - void replaceStrings(String[] newStrings) { - this.strings.clear(); - CollectionTools.addAll(this.strings, newStrings); - this.fireCollectionChanged(STRINGS_COLLECTION, this.strings); - } - void changeList() { - this.fireListChanged("bogus list", Collections.emptyList()); - } - } - - class Target { - TestModel testModel; - String collectionName; - String string; - boolean itemAddedZeroArgumentFlag = false; - boolean itemAddedSingleArgumentFlag = false; - boolean itemRemovedZeroArgumentFlag = false; - boolean itemRemovedSingleArgumentFlag = false; - boolean collectionClearedZeroArgumentFlag = false; - boolean collectionClearedSingleArgumentFlag = false; - boolean collectionChangedZeroArgumentFlag = false; - boolean collectionChangedSingleArgumentFlag = false; - boolean collectionEventSingleArgumentFlag = false; - Target(TestModel testModel, String collectionName, String string) { - super(); - this.testModel = testModel; - this.collectionName = collectionName; - this.string = string; - } - void itemAddedZeroArgument() { - this.itemAddedZeroArgumentFlag = true; - } - void itemAddedSingleArgument(CollectionAddEvent e) { - this.itemAddedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.collectionName, e.getCollectionName()); - assertEquals(this.string, e.getItems().iterator().next()); - } - void itemRemovedZeroArgument() { - this.itemRemovedZeroArgumentFlag = true; - } - void itemRemovedSingleArgument(CollectionRemoveEvent e) { - this.itemRemovedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.collectionName, e.getCollectionName()); - assertEquals(this.string, e.getItems().iterator().next()); - } - void collectionClearedZeroArgument() { - this.collectionClearedZeroArgumentFlag = true; - } - void collectionClearedSingleArgument(CollectionClearEvent e) { - this.collectionClearedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.collectionName, e.getCollectionName()); - } - void collectionChangedZeroArgument() { - this.collectionChangedZeroArgumentFlag = true; - } - void collectionChangedSingleArgument(CollectionChangeEvent e) { - this.collectionChangedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.collectionName, e.getCollectionName()); - } - void collectionEventSingleArgument(CollectionEvent e) { - this.collectionEventSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.collectionName, e.getCollectionName()); - } - void collectionChangedDoubleArgument(CollectionChangeEvent e, Object o) { - fail("bogus event: " + e + " object: " + o); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveListChangeListenerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveListChangeListenerTests.java deleted file mode 100644 index 34f6c9b49f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveListChangeListenerTests.java +++ /dev/null @@ -1,498 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.listener; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.CloneListIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ReflectiveChangeListener; - -@SuppressWarnings("nls") -public class ReflectiveListChangeListenerTests extends TestCase { - - public ReflectiveListChangeListenerTests(String name) { - super(name); - } - - private ListChangeListener buildZeroArgumentListener(Object target) { - return ReflectiveChangeListener.buildListChangeListener(target, "itemAddedZeroArgument", "itemRemovedZeroArgument", "itemReplacedZeroArgument", "itemMovedZeroArgument", "listClearedZeroArgument", "listChangedZeroArgument"); - } - - private ListChangeListener buildSingleArgumentListener(Object target) { - return ReflectiveChangeListener.buildListChangeListener(target, "itemAddedSingleArgument", "itemRemovedSingleArgument", "itemReplacedSingleArgument", "itemMovedSingleArgument", "listClearedSingleArgument", "listChangedSingleArgument"); - } - - public void testItemAddedZeroArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); - testModel.addString(string); - assertTrue(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemAddedSingleArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); - testModel.addString(string); - assertFalse(target.itemAddedZeroArgumentFlag); - assertTrue(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemRemovedZeroArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); - testModel.removeString(string); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertTrue(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemRemovedSingleArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); - testModel.removeString(string); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertTrue(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemReplacedZeroArgumentNamedList() { - TestModel testModel = new TestModel(); - String oldString = "foo"; - String newString = "bar"; - testModel.addString(oldString); - Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); - testModel.replaceString(oldString, newString); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertTrue(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemReplacedSingleArgumentNamedList() { - TestModel testModel = new TestModel(); - String oldString = "foo"; - String newString = "bar"; - testModel.addString(oldString); - Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); - testModel.replaceString(oldString, newString); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertTrue(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemMovedZeroArgumentNamedList() { - TestModel testModel = new TestModel(); - testModel.addString("zero"); - testModel.addString("one"); - testModel.addString("two"); - testModel.addString("three"); - Target target = new Target(testModel, TestModel.STRINGS_LIST, 0, 2); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); - testModel.moveString(0, 2); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertTrue(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testItemMovedSingleArgumentNamedList() { - TestModel testModel = new TestModel(); - testModel.addString("zero"); - testModel.addString("one"); - testModel.addString("two"); - testModel.addString("three"); - Target target = new Target(testModel, TestModel.STRINGS_LIST, 0, 2); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); - testModel.moveString(0, 2); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertTrue(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testListClearedZeroArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); - testModel.clearStrings(); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertTrue(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testListClearedSingleArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); - testModel.clearStrings(); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertTrue(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testListChangedZeroArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); - testModel.replaceAllStrings(new String[] {"bar", "baz"}); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertTrue(target.listChangedZeroArgumentFlag); - assertFalse(target.listChangedSingleArgumentFlag); - } - - public void testListChangedSingleArgumentNamedList() { - TestModel testModel = new TestModel(); - String string = "foo"; - testModel.addString(string); - Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); - testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); - testModel.replaceAllStrings(new String[] {"bar", "baz"}); - assertFalse(target.itemAddedZeroArgumentFlag); - assertFalse(target.itemAddedSingleArgumentFlag); - assertFalse(target.itemRemovedZeroArgumentFlag); - assertFalse(target.itemRemovedSingleArgumentFlag); - assertFalse(target.itemReplacedZeroArgumentFlag); - assertFalse(target.itemReplacedSingleArgumentFlag); - assertFalse(target.itemMovedZeroArgumentFlag); - assertFalse(target.itemMovedSingleArgumentFlag); - assertFalse(target.listClearedZeroArgumentFlag); - assertFalse(target.listClearedSingleArgumentFlag); - assertFalse(target.listChangedZeroArgumentFlag); - assertTrue(target.listChangedSingleArgumentFlag); - } - - public void testBogusDoubleArgument1() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - boolean exCaught = false; - try { - ListChangeListener listener = ReflectiveChangeListener.buildListChangeListener(target, "listChangedDoubleArgument"); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getCause().getClass() == NoSuchMethodException.class) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - public void testBogusDoubleArgument2() throws Exception { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - Method method = ReflectionTools.getMethod(target, "listChangedDoubleArgument", new Class[] {ListChangeEvent.class, Object.class}); - boolean exCaught = false; - try { - ListChangeListener listener = ReflectiveChangeListener.buildListChangeListener(target, method); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getMessage().equals(method.toString())) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - public void testListenerMismatch() { - TestModel testModel = new TestModel(); - String string = "foo"; - Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); - // build a LIST change listener and hack it so we - // can add it as a COLLECTION change listener - Object listener = ReflectiveChangeListener.buildListChangeListener(target, "listEventSingleArgument"); - testModel.addCollectionChangeListener("bogus collection", (CollectionChangeListener) listener); - - boolean exCaught = false; - try { - testModel.changeCollection(); - fail("listener mismatch: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - class TestModel extends AbstractModel { - private List<String> strings = new ArrayList<String>(); - public static final String STRINGS_LIST = "strings"; - TestModel() { - super(); - } - ListIterator<String> strings() { - return new CloneListIterator<String>(this.strings); - } - void addString(String string) { - this.addItemToList(string, this.strings, STRINGS_LIST); - } - void removeString(String string) { - this.removeItemFromList(this.strings.indexOf(string), this.strings, STRINGS_LIST); - } - void replaceString(String oldString, String newString) { - this.setItemInList(this.strings.indexOf(oldString), newString, this.strings, STRINGS_LIST); - } - void moveString(int targetIndex, int sourceIndex) { - this.moveItemInList(targetIndex, sourceIndex, this.strings, STRINGS_LIST); - } - void clearStrings() { - this.clearList(this.strings, STRINGS_LIST); - } - void replaceAllStrings(String[] newStrings) { - this.strings.clear(); - CollectionTools.addAll(this.strings, newStrings); - this.fireListChanged(STRINGS_LIST, this.strings); - } - void changeCollection() { - this.fireCollectionChanged("bogus collection", Collections.emptySet()); - } - } - - class Target { - TestModel testModel; - String listName; - String string; - int index; - String replacedString; - int sourceIndex; - boolean itemAddedZeroArgumentFlag = false; - boolean itemAddedSingleArgumentFlag = false; - boolean itemRemovedZeroArgumentFlag = false; - boolean itemRemovedSingleArgumentFlag = false; - boolean itemReplacedZeroArgumentFlag = false; - boolean itemReplacedSingleArgumentFlag = false; - boolean itemMovedZeroArgumentFlag = false; - boolean itemMovedSingleArgumentFlag = false; - boolean listClearedZeroArgumentFlag = false; - boolean listClearedSingleArgumentFlag = false; - boolean listChangedZeroArgumentFlag = false; - boolean listChangedSingleArgumentFlag = false; - boolean listEventSingleArgumentFlag = false; - Target(TestModel testModel, String listName, String string, int index) { - super(); - this.testModel = testModel; - this.listName = listName; - this.string = string; - this.index = index; - } - Target(TestModel testModel, String listName, String string, int index, String replacedString) { - this(testModel, listName, string, index); - this.replacedString = replacedString; - } - Target(TestModel testModel, String listName, int targetIndex, int sourceIndex) { - super(); - this.testModel = testModel; - this.listName = listName; - this.index = targetIndex; - this.sourceIndex = sourceIndex; - } - void itemAddedZeroArgument() { - this.itemAddedZeroArgumentFlag = true; - } - void itemAddedSingleArgument(ListAddEvent e) { - this.itemAddedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - assertEquals(this.string, e.getItems().iterator().next()); - assertEquals(this.index, e.getIndex()); - } - void itemRemovedZeroArgument() { - this.itemRemovedZeroArgumentFlag = true; - } - void itemRemovedSingleArgument(ListRemoveEvent e) { - this.itemRemovedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - assertEquals(this.string, e.getItems().iterator().next()); - assertEquals(this.index, e.getIndex()); - } - void itemReplacedZeroArgument() { - this.itemReplacedZeroArgumentFlag = true; - } - void itemReplacedSingleArgument(ListReplaceEvent e) { - this.itemReplacedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - assertEquals(this.string, e.getNewItems().iterator().next()); - assertEquals(this.replacedString, e.getOldItems().iterator().next()); - assertEquals(this.index, e.getIndex()); - } - void itemMovedZeroArgument() { - this.itemMovedZeroArgumentFlag = true; - } - void itemMovedSingleArgument(ListMoveEvent e) { - this.itemMovedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - assertEquals(this.index, e.getTargetIndex()); - assertEquals(this.sourceIndex, e.getSourceIndex()); - } - void listChangedZeroArgument() { - this.listChangedZeroArgumentFlag = true; - } - void listClearedSingleArgument(ListClearEvent e) { - this.listClearedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - } - void listClearedZeroArgument() { - this.listClearedZeroArgumentFlag = true; - } - void listChangedSingleArgument(ListChangeEvent e) { - this.listChangedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - } - void listChangedDoubleArgument(ListChangeEvent e, Object o) { - fail("bogus event: " + e + " - object: " + o); - } - void listEventSingleArgument(ListEvent e) { - this.listEventSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.listName, e.getListName()); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectivePropertyChangeListenerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectivePropertyChangeListenerTests.java deleted file mode 100644 index 9b27d57fcb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectivePropertyChangeListenerTests.java +++ /dev/null @@ -1,176 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.listener; - -import java.lang.reflect.Method; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ReflectiveChangeListener; -import org.eclipse.jpt.common.utility.model.listener.StateChangeListener; - -@SuppressWarnings("nls") -public class ReflectivePropertyChangeListenerTests extends TestCase { - - public ReflectivePropertyChangeListenerTests(String name) { - super(name); - } - - public void testZeroArgumentNamedProperty() { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - testModel.addPropertyChangeListener(TestModel.VALUE_PROPERTY, ReflectiveChangeListener.buildPropertyChangeListener(target, "propertyChangedZeroArgument")); - testModel.setValue(99); - assertTrue(target.zeroArgumentFlag); - assertFalse(target.singleArgumentFlag); - } - - /** - * test method that has more general method parameter type - */ - public void testSingleArgument2() throws Exception { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - Method method = ReflectionTools.getMethod(target, "propertyChangedSingleArgument2", new Class[] {Object.class}); - testModel.addPropertyChangeListener(TestModel.VALUE_PROPERTY, ReflectiveChangeListener.buildPropertyChangeListener(target, method)); - testModel.setValue(99); - assertFalse(target.zeroArgumentFlag); - assertTrue(target.singleArgumentFlag); - } - - public void testSingleArgumentNamedProperty() { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - testModel.addPropertyChangeListener(TestModel.VALUE_PROPERTY, ReflectiveChangeListener.buildPropertyChangeListener(target, "propertyChangedSingleArgument")); - testModel.setValue(99); - assertFalse(target.zeroArgumentFlag); - assertTrue(target.singleArgumentFlag); - } - - /** - * test method that has more general method parameter type - */ - public void testSingleArgumentNamedProperty2() throws Exception { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - Method method = ReflectionTools.getMethod(target, "propertyChangedSingleArgument2", new Class[] {Object.class}); - testModel.addPropertyChangeListener(TestModel.VALUE_PROPERTY, ReflectiveChangeListener.buildPropertyChangeListener(target, method)); - testModel.setValue(99); - assertFalse(target.zeroArgumentFlag); - assertTrue(target.singleArgumentFlag); - } - - public void testListenerMismatch() { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - // build a PROPERTY change listener and hack it so we - // can add it as a STATE change listener - Object listener = ReflectiveChangeListener.buildPropertyChangeListener(target, "propertyChangedSingleArgument"); - testModel.addStateChangeListener((StateChangeListener) listener); - - boolean exCaught = false; - try { - testModel.setValue(99); - fail("listener mismatch: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testBogusDoubleArgument1() { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - boolean exCaught = false; - try { - PropertyChangeListener listener = ReflectiveChangeListener.buildPropertyChangeListener(target, "stateChangedDoubleArgument"); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getCause().getClass() == NoSuchMethodException.class) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - public void testBogusDoubleArgument2() throws Exception { - TestModel testModel = new TestModel(7); - Target target = new Target(testModel, TestModel.VALUE_PROPERTY, 7, 99); - Method method = ReflectionTools.getMethod(target, "propertyChangedDoubleArgument", new Class[] {PropertyChangeEvent.class, Object.class}); - boolean exCaught = false; - try { - PropertyChangeListener listener = ReflectiveChangeListener.buildPropertyChangeListener(target, method); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getMessage().equals(method.toString())) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - - class TestModel extends AbstractModel { - private int value = 0; - public static final String VALUE_PROPERTY = "value"; - TestModel(int value) { - super(); - this.value = value; - } - void setValue(int value) { - int old = this.value; - this.value = value; - this.firePropertyChanged(VALUE_PROPERTY, old, value); - if (old != value) { - this.fireStateChanged(); - } - } - } - - class Target { - TestModel testModel; - String propertyName; - Object oldValue; - Object newValue; - boolean zeroArgumentFlag = false; - boolean singleArgumentFlag = false; - Target(TestModel testModel, String propertyName, int oldValue, int newValue) { - super(); - this.testModel = testModel; - this.propertyName = propertyName; - this.oldValue = new Integer(oldValue); - this.newValue = new Integer(newValue); - } - void propertyChangedZeroArgument() { - this.zeroArgumentFlag = true; - } - void propertyChangedSingleArgument(PropertyChangeEvent e) { - this.singleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.propertyName, e.getPropertyName()); - assertEquals(this.oldValue, e.getOldValue()); - assertEquals(this.newValue, e.getNewValue()); - } - void propertyChangedSingleArgument2(Object o) { - PropertyChangeEvent e = (PropertyChangeEvent) o; - this.singleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.propertyName, e.getPropertyName()); - assertEquals(this.oldValue, e.getOldValue()); - assertEquals(this.newValue, e.getNewValue()); - } - void propertyChangedDoubleArgument(PropertyChangeEvent e, Object o) { - fail("bogus event: " + e + " - object: " + o); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveStateChangeListenerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveStateChangeListenerTests.java deleted file mode 100644 index 9a799e37db..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveStateChangeListenerTests.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.listener; - -import java.lang.reflect.Method; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ReflectiveChangeListener; -import org.eclipse.jpt.common.utility.model.listener.StateChangeListener; - -@SuppressWarnings("nls") -public class ReflectiveStateChangeListenerTests extends TestCase { - - public ReflectiveStateChangeListenerTests(String name) { - super(name); - } - - public void testZeroArgument() { - TestModel testModel = new TestModel(); - Target target = new Target(testModel); - testModel.addStateChangeListener(ReflectiveChangeListener.buildStateChangeListener(target, "stateChangedZeroArgument")); - testModel.changeState(); - assertTrue(target.zeroArgumentFlag); - assertFalse(target.singleArgumentFlag); - } - - public void testSingleArgument() { - TestModel testModel = new TestModel(); - Target target = new Target(testModel); - testModel.addStateChangeListener(ReflectiveChangeListener.buildStateChangeListener(target, "stateChangedSingleArgument")); - testModel.changeState(); - assertFalse(target.zeroArgumentFlag); - assertTrue(target.singleArgumentFlag); - } - - /** - * test method that has more general method parameter type - */ - public void testSingleArgument2() throws Exception { - TestModel testModel = new TestModel(); - Target target = new Target(testModel); - Method method = ReflectionTools.getMethod(target, "stateChangedSingleArgument2", new Class[] {Object.class}); - testModel.addStateChangeListener(ReflectiveChangeListener.buildStateChangeListener(target, method)); - testModel.changeState(); - assertFalse(target.zeroArgumentFlag); - assertTrue(target.singleArgumentFlag); - } - - public void testListenerMismatch() { - TestModel testModel = new TestModel(); - Target target = new Target(testModel); - // build a STATE change listener and hack it so we - // can add it as a PROPERTY change listener - Object listener = ReflectiveChangeListener.buildStateChangeListener(target, "stateChangedSingleArgument"); - testModel.addPropertyChangeListener("value", (PropertyChangeListener) listener); - - boolean exCaught = false; - try { - testModel.changeProperty(); - fail("listener mismatch: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testBogusDoubleArgument1() { - TestModel testModel = new TestModel(); - Target target = new Target(testModel); - boolean exCaught = false; - try { - StateChangeListener listener = ReflectiveChangeListener.buildStateChangeListener(target, "stateChangedDoubleArgument"); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getCause().getClass() == NoSuchMethodException.class) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - public void testBogusDoubleArgument2() throws Exception { - TestModel testModel = new TestModel(); - Target target = new Target(testModel); - Method method = ReflectionTools.getMethod(target, "stateChangedDoubleArgument", new Class[] {StateChangeEvent.class, Object.class}); - boolean exCaught = false; - try { - StateChangeListener listener = ReflectiveChangeListener.buildStateChangeListener(target, method); - fail("bogus listener: " + listener); - } catch (RuntimeException ex) { - if (ex.getMessage().equals(method.toString())) { - exCaught = true; - } - } - assertTrue(exCaught); - } - - - class TestModel extends AbstractModel { - TestModel() { - super(); - } - void changeState() { - this.fireStateChanged(); - } - void changeProperty() { - this.firePropertyChanged("value", 55, 42); - } - } - - class Target { - TestModel testModel; - boolean zeroArgumentFlag = false; - boolean singleArgumentFlag = false; - Target(TestModel testModel) { - super(); - this.testModel = testModel; - } - void stateChangedZeroArgument() { - this.zeroArgumentFlag = true; - } - void stateChangedSingleArgument(StateChangeEvent e) { - this.singleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - } - void stateChangedSingleArgument2(Object e) { - this.singleArgumentFlag = true; - assertSame(this.testModel, ((StateChangeEvent) e).getSource()); - } - void stateChangedDoubleArgument(StateChangeEvent e, Object o) { - fail("bogus event: " + e + " - object: " + o); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveTreeChangeListenerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveTreeChangeListenerTests.java deleted file mode 100644 index e6dbfe7253..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/listener/ReflectiveTreeChangeListenerTests.java +++ /dev/null @@ -1,362 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.listener; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.CloneIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.model.event.TreeAddEvent; -import org.eclipse.jpt.common.utility.model.event.TreeChangeEvent; -import org.eclipse.jpt.common.utility.model.event.TreeClearEvent; -import org.eclipse.jpt.common.utility.model.event.TreeEvent; -import org.eclipse.jpt.common.utility.model.event.TreeRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ReflectiveChangeListener; -import org.eclipse.jpt.common.utility.model.listener.TreeChangeListener; - -@SuppressWarnings("nls") -public class ReflectiveTreeChangeListenerTests extends TestCase { - - public ReflectiveTreeChangeListenerTests(String name) { - super(name); - } - - private TreeChangeListener buildZeroArgumentListener(Object target) { - return ReflectiveChangeListener.buildTreeChangeListener(target, "nodeAddedZeroArgument", "nodeRemovedZeroArgument", "treeClearedZeroArgument", "treeChangedZeroArgument"); - } - - private TreeChangeListener buildSingleArgumentListener(Object target) { - return ReflectiveChangeListener.buildTreeChangeListener(target, "nodeAddedSingleArgument", "nodeRemovedSingleArgument", "treeClearedSingleArgument", "treeChangedSingleArgument"); - } - - public void testNodeAddedZeroArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "child"}); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildZeroArgumentListener(target)); - testModel.addNode("root", "child"); - assertTrue(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testNodeAddedSingleArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "child"}); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildSingleArgumentListener(target)); - testModel.addNode("root", "child"); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertTrue(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testNodeRemovedZeroArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "child"}); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildZeroArgumentListener(target)); - testModel.removeNode("child"); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertTrue(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testNodeRemovedSingleArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "child"}); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildSingleArgumentListener(target)); - testModel.removeNode("child"); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertTrue(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testTreeClearedZeroArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - testModel.addNode("child", "grandchild"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[0]); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildZeroArgumentListener(target)); - testModel.clearTree(); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertTrue(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testTreeClearedSingleArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - testModel.addNode("child", "grandchild"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[0]); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildSingleArgumentListener(target)); - testModel.clearTree(); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertTrue(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testTreeChangedZeroArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "another child"}); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildZeroArgumentListener(target)); - testModel.replaceNode("child", "another child"); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertTrue(target.treeChangedZeroArgumentFlag); - assertFalse(target.treeChangedSingleArgumentFlag); - } - - public void testTreeChangedSingleArgumentNamedTree() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "another child"}); - testModel.addTreeChangeListener(TestModel.STRINGS_TREE, this.buildSingleArgumentListener(target)); - testModel.replaceNode("child", "another child"); - assertFalse(target.nodeAddedZeroArgumentFlag); - assertFalse(target.nodeAddedSingleArgumentFlag); - assertFalse(target.nodeRemovedZeroArgumentFlag); - assertFalse(target.nodeRemovedSingleArgumentFlag); - assertFalse(target.treeClearedZeroArgumentFlag); - assertFalse(target.treeClearedSingleArgumentFlag); - assertFalse(target.treeChangedZeroArgumentFlag); - assertTrue(target.treeChangedSingleArgumentFlag); - } - - public void testListenerMismatch() { - TestModel testModel = new TestModel("root"); - testModel.addNode("root", "child"); - Target target = new Target(testModel, TestModel.STRINGS_TREE, new String[]{"root", "child"}); - // build a TREE change listener and hack it so we - // can add it as a COLLECTION change listener - Object listener = ReflectiveChangeListener.buildTreeChangeListener(target, "treeEventSingleArgument"); - testModel.addCollectionChangeListener("bogus collection", (CollectionChangeListener) listener); - - boolean exCaught = false; - try { - testModel.changeCollection(); - fail("listener mismatch: " + listener); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - - class TestModel extends AbstractModel { - private final String root; - private Map<String, Collection<String>> childrenLists = new HashMap<String, Collection<String>>(); - private Map<String, String> parents = new HashMap<String, String>(); - public static final String STRINGS_TREE = "strings"; - TestModel(String root) { - super(); - if (root == null) { - throw new NullPointerException(); - } - this.root = root; - this.childrenLists.put(root, new ArrayList<String>()); - this.parents.put(root, null); - } - String getRoot() { - return this.root; - } - private List<String> path(String node) { - String temp = node; - List<String> reversePath = new ArrayList<String>(); - do { - reversePath.add(temp); - temp = this.parents.get(temp); - } while (temp != null); - return CollectionTools.reverse(reversePath); - } - Iterator<String> strings() { - return new CloneIterator<String>(this.childrenLists.keySet()) { - @Override - protected void remove(String s) { - TestModel.this.removeNode(s); - } - }; - } - void addNode(String parent, String child) { - if ((parent == null) || (child == null)) { - throw new NullPointerException(); - } - - Collection<String> children = this.childrenLists.get(parent); - if (children == null) { - throw new IllegalStateException("cannot add a child to a non-existent parent"); - } - - if (this.childrenLists.get(child) != null) { - throw new IllegalStateException("cannot add a child that is already in the tree"); - } - - children.add(child); - this.childrenLists.put(child, new ArrayList<String>()); - this.parents.put(child, parent); - this.fireNodeAdded(STRINGS_TREE, this.path(child)); - } - void removeNode(String node) { - if (node == null) { - throw new NullPointerException(); - } - - Collection<String> children = this.childrenLists.get(node); - if (children == null) { - throw new IllegalStateException("node is not in tree"); - } - List<String> path = this.path(node); - for (String s : children) { - this.removeNode(s); - } - this.childrenLists.remove(node); - this.parents.remove(node); - this.fireNodeRemoved(STRINGS_TREE, path); - } - void replaceNode(String oldNode, String newNode) { - if ((oldNode == null) || (newNode == null)) { - throw new NullPointerException(); - } - - Collection<String> children = this.childrenLists.remove(oldNode); - if (children == null) { - throw new IllegalStateException("old node is not in tree"); - } - this.childrenLists.put(newNode, children); - for (String child : children) { - this.parents.put(child, newNode); - } - - String parent = this.parents.remove(oldNode); - this.parents.put(newNode, parent); - - this.fireTreeChanged(STRINGS_TREE, this.path(newNode)); - } - void clearTree() { - this.childrenLists.clear(); - this.childrenLists.put(root, new ArrayList<String>()); - this.parents.clear(); - this.parents.put(root, null); - this.fireTreeCleared(STRINGS_TREE); - } - void changeCollection() { - this.fireCollectionChanged("bogus collection", Collections.emptySet()); - } - } - - class Target { - TestModel testModel; - String treeName; - List<String> path; - boolean nodeAddedZeroArgumentFlag = false; - boolean nodeAddedSingleArgumentFlag = false; - boolean nodeRemovedZeroArgumentFlag = false; - boolean nodeRemovedSingleArgumentFlag = false; - boolean treeClearedZeroArgumentFlag = false; - boolean treeClearedSingleArgumentFlag = false; - boolean treeChangedZeroArgumentFlag = false; - boolean treeChangedSingleArgumentFlag = false; - boolean treeEventSingleArgumentFlag = false; - Target(TestModel testModel, String treeName, String[] path) { - super(); - this.testModel = testModel; - this.treeName = treeName; - this.path = Arrays.asList(path); - } - void nodeAddedZeroArgument() { - this.nodeAddedZeroArgumentFlag = true; - } - void nodeAddedSingleArgument(TreeAddEvent e) { - this.nodeAddedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.treeName, e.getTreeName()); - assertEquals(this.path, CollectionTools.list(e.getPath())); - } - void nodeRemovedZeroArgument() { - this.nodeRemovedZeroArgumentFlag = true; - } - void nodeRemovedSingleArgument(TreeRemoveEvent e) { - this.nodeRemovedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.treeName, e.getTreeName()); - assertEquals(this.path, CollectionTools.list(e.getPath())); - } - void treeClearedZeroArgument() { - this.treeClearedZeroArgumentFlag = true; - } - void treeClearedSingleArgument(TreeClearEvent e) { - this.treeClearedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.treeName, e.getTreeName()); - } - void treeChangedZeroArgument() { - this.treeChangedZeroArgumentFlag = true; - } - void treeChangedSingleArgument(TreeChangeEvent e) { - this.treeChangedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.treeName, e.getTreeName()); - } - void treeEventSingleArgument(TreeEvent e) { - this.treeChangedSingleArgumentFlag = true; - assertSame(this.testModel, e.getSource()); - assertEquals(this.treeName, e.getTreeName()); - } - void collectionChangedDoubleArgument(TreeChangeEvent e, Object o) { - fail("bogus event: " + e + " - object: " + o); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/BufferedWritablePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/BufferedWritablePropertyValueModelTests.java deleted file mode 100644 index 9e38380992..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/BufferedWritablePropertyValueModelTests.java +++ /dev/null @@ -1,504 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Date; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.BufferedWritablePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class BufferedWritablePropertyValueModelTests extends TestCase { - private Employee employee; - private ModifiablePropertyValueModel<Employee> employeeHolder; - PropertyChangeEvent employeeEvent; - - private ModifiablePropertyValueModel<Integer> idAdapter; - private ModifiablePropertyValueModel<String> nameAdapter; - private ModifiablePropertyValueModel<Date> hireDateAdapter; - PropertyChangeEvent adapterEvent; - - private BufferedWritablePropertyValueModel.Trigger trigger; - private BufferedWritablePropertyValueModel<Integer> bufferedIDHolder; - private BufferedWritablePropertyValueModel<String> bufferedNameHolder; - private BufferedWritablePropertyValueModel<Date> bufferedHireDateHolder; - PropertyChangeEvent bufferedEvent; - - public BufferedWritablePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - this.employee = new Employee(17, "Freddy", new Date()); - this.employeeHolder = new SimplePropertyValueModel<Employee>(this.employee); - - this.trigger = new BufferedWritablePropertyValueModel.Trigger(); - - this.idAdapter = this.buildIDAdapter(this.employeeHolder); - this.bufferedIDHolder = new BufferedWritablePropertyValueModel<Integer>(this.idAdapter, this.trigger); - - this.nameAdapter = this.buildNameAdapter(this.employeeHolder); - this.bufferedNameHolder = new BufferedWritablePropertyValueModel<String>(this.nameAdapter, this.trigger); - - this.hireDateAdapter = this.buildHireDateAdapter(this.employeeHolder); - this.bufferedHireDateHolder = new BufferedWritablePropertyValueModel<Date>(this.hireDateAdapter, this.trigger); - } - - private ModifiablePropertyValueModel<Integer> buildIDAdapter(PropertyValueModel<Employee> eHolder) { - return new PropertyAspectAdapter<Employee, Integer>(eHolder, Employee.ID_PROPERTY) { - @Override - protected Integer buildValue_() { - return new Integer(this.subject.getID()); - } - @Override - protected void setValue_(Integer value) { - this.subject.setID(value.intValue()); - } - }; - } - - private ModifiablePropertyValueModel<String> buildNameAdapter(PropertyValueModel<Employee> eHolder) { - return new PropertyAspectAdapter<Employee, String>(eHolder, Employee.NAME_PROPERTY) { - @Override - protected String buildValue_() { - return this.subject.getName(); - } - @Override - protected void setValue_(String value) { - this.subject.setName(value); - } - }; - } - - private ModifiablePropertyValueModel<Date> buildHireDateAdapter(PropertyValueModel<Employee> eHolder) { - return new PropertyAspectAdapter<Employee, Date>(eHolder, Employee.HIRE_DATE_PROPERTY) { - @Override - protected Date buildValue_() { - return this.subject.getHireDate(); - } - @Override - protected void setValue_(Date value) { - this.subject.setHireDate(value); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetValue() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedIDHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedHireDateHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - assertEquals(new Integer(17), this.idAdapter.getValue()); - assertEquals(new Integer(17), this.bufferedIDHolder.getValue()); - - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Freddy", this.bufferedNameHolder.getValue()); - - Date temp = this.employee.getHireDate(); - assertEquals(temp, this.employee.getHireDate()); - assertEquals(temp, this.hireDateAdapter.getValue()); - assertEquals(temp, this.bufferedHireDateHolder.getValue()); - - this.bufferedIDHolder.setValue(new Integer(323)); - assertEquals(17, this.employee.getID()); - assertEquals(new Integer(17), this.idAdapter.getValue()); - assertEquals(new Integer(323), this.bufferedIDHolder.getValue()); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - - this.bufferedHireDateHolder.setValue(null); - assertEquals(temp, this.employee.getHireDate()); - assertEquals(temp, this.hireDateAdapter.getValue()); - assertEquals(null, this.bufferedHireDateHolder.getValue()); - } - - public void testTriggerAccept() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedIDHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedHireDateHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedIDHolder.setValue(new Integer(323)); - assertEquals(17, this.employee.getID()); - assertEquals(new Integer(17), this.idAdapter.getValue()); - assertEquals(new Integer(323), this.bufferedIDHolder.getValue()); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - - Date temp = this.employee.getHireDate(); - this.bufferedHireDateHolder.setValue(null); - assertEquals(temp, this.employee.getHireDate()); - assertEquals(temp, this.hireDateAdapter.getValue()); - assertEquals(null, this.bufferedHireDateHolder.getValue()); - - this.trigger.accept(); - - assertEquals(323, this.employee.getID()); - assertEquals(new Integer(323), this.idAdapter.getValue()); - assertEquals(new Integer(323), this.bufferedIDHolder.getValue()); - - assertEquals("Ripley", this.employee.getName()); - assertEquals("Ripley", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - - assertEquals(null, this.employee.getHireDate()); - assertEquals(null, this.hireDateAdapter.getValue()); - assertEquals(null, this.bufferedHireDateHolder.getValue()); - } - - public void testTriggerReset() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedIDHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedHireDateHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedIDHolder.setValue(new Integer(323)); - assertEquals(17, this.employee.getID()); - assertEquals(new Integer(17), this.idAdapter.getValue()); - assertEquals(new Integer(323), this.bufferedIDHolder.getValue()); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - - Date temp = this.employee.getHireDate(); - this.bufferedHireDateHolder.setValue(null); - assertEquals(temp, this.employee.getHireDate()); - assertEquals(temp, this.hireDateAdapter.getValue()); - assertEquals(null, this.bufferedHireDateHolder.getValue()); - - this.trigger.reset(); - - assertEquals(17, this.employee.getID()); - assertEquals(new Integer(17), this.idAdapter.getValue()); - assertEquals(new Integer(17), this.bufferedIDHolder.getValue()); - - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Freddy", this.bufferedNameHolder.getValue()); - - assertEquals(temp, this.employee.getHireDate()); - assertEquals(temp, this.hireDateAdapter.getValue()); - assertEquals(temp, this.bufferedHireDateHolder.getValue()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.bufferedIDHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.bufferedNameHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.bufferedHireDateHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - assertTrue(((AbstractModel) this.idAdapter).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.nameAdapter).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.hireDateAdapter).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - assertTrue(this.employee.hasNoPropertyChangeListeners(Employee.ID_PROPERTY)); - assertTrue(this.employee.hasNoPropertyChangeListeners(Employee.NAME_PROPERTY)); - assertTrue(this.employee.hasNoPropertyChangeListeners(Employee.HIRE_DATE_PROPERTY)); - - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedIDHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedHireDateHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - assertTrue(((AbstractModel) this.bufferedIDHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.bufferedNameHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.bufferedHireDateHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - assertTrue(((AbstractModel) this.idAdapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.nameAdapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.hireDateAdapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - assertTrue(this.employee.hasAnyPropertyChangeListeners(Employee.ID_PROPERTY)); - assertTrue(this.employee.hasAnyPropertyChangeListeners(Employee.NAME_PROPERTY)); - assertTrue(this.employee.hasAnyPropertyChangeListeners(Employee.HIRE_DATE_PROPERTY)); - - this.bufferedIDHolder.removePropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedNameHolder.removePropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - this.bufferedHireDateHolder.removePropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - assertTrue(((AbstractModel) this.bufferedIDHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.bufferedNameHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.bufferedHireDateHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - assertTrue(((AbstractModel) this.idAdapter).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.nameAdapter).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.hireDateAdapter).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - assertTrue(this.employee.hasNoPropertyChangeListeners(Employee.ID_PROPERTY)); - assertTrue(this.employee.hasNoPropertyChangeListeners(Employee.NAME_PROPERTY)); - assertTrue(this.employee.hasNoPropertyChangeListeners(Employee.HIRE_DATE_PROPERTY)); - } - - public void testPropertyChange1() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - PropertyChangeListener adapterListener = this.buildAdapterListener(); - this.nameAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, adapterListener); - - PropertyChangeListener employeeListener = this.buildEmployeeListener(); - this.employee.addPropertyChangeListener(Employee.NAME_PROPERTY, employeeListener); - - this.verifyPropertyChanges(); - } - - public void testPropertyChange2() { - ChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addChangeListener(bufferedListener); - - ChangeListener adapterListener = this.buildAdapterListener(); - this.nameAdapter.addChangeListener(adapterListener); - - ChangeListener employeeListener = this.buildEmployeeListener(); - this.employee.addChangeListener(employeeListener); - - this.verifyPropertyChanges(); - } - - private void verifyPropertyChanges() { - this.bufferedEvent = null; - this.adapterEvent = null; - this.employeeEvent = null; - this.bufferedNameHolder.setValue("Ripley"); - this.verifyEvent(this.bufferedEvent, this.bufferedNameHolder, PropertyValueModel.VALUE, "Freddy", "Ripley"); - assertNull(this.adapterEvent); - assertNull(this.employeeEvent); - - this.bufferedEvent = null; - this.adapterEvent = null; - this.employeeEvent = null; - this.bufferedNameHolder.setValue("Charlie"); - this.verifyEvent(this.bufferedEvent, this.bufferedNameHolder, PropertyValueModel.VALUE, "Ripley", "Charlie"); - assertNull(this.adapterEvent); - assertNull(this.employeeEvent); - - this.bufferedEvent = null; - this.adapterEvent = null; - this.employeeEvent = null; - this.trigger.accept(); - assertNull(this.bufferedEvent); - this.verifyEvent(this.adapterEvent, this.nameAdapter, PropertyValueModel.VALUE, "Freddy", "Charlie"); - this.verifyEvent(this.employeeEvent, this.employee, Employee.NAME_PROPERTY, "Freddy", "Charlie"); - - this.bufferedEvent = null; - this.adapterEvent = null; - this.employeeEvent = null; - this.bufferedNameHolder.setValue("Jason"); - this.verifyEvent(this.bufferedEvent, this.bufferedNameHolder, PropertyValueModel.VALUE, "Charlie", "Jason"); - assertNull(this.adapterEvent); - assertNull(this.employeeEvent); - - this.bufferedEvent = null; - this.adapterEvent = null; - this.employeeEvent = null; - this.trigger.reset(); - this.verifyEvent(this.bufferedEvent, this.bufferedNameHolder, PropertyValueModel.VALUE, "Jason", "Charlie"); - assertNull(this.adapterEvent); - assertNull(this.employeeEvent); - } - - /** - * changing the value should trigger buffering - */ - public void testBuffering1() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - assertTrue(this.bufferedNameHolder.isBuffering()); - } - - /** - * setting to the same value should not trigger buffering (?) - */ - public void testBuffering2() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedNameHolder.setValue("Freddy"); - assertEquals("Freddy", this.bufferedNameHolder.getValue()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertFalse(this.bufferedNameHolder.isBuffering()); - } - - /** - * setting to the original value should not trigger buffering (?) - */ - public void testBuffering3() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - assertTrue(this.bufferedNameHolder.isBuffering()); - - this.bufferedNameHolder.setValue("Freddy"); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Freddy", this.bufferedNameHolder.getValue()); - assertFalse(this.bufferedNameHolder.isBuffering()); - } - - /** - * back-door changes are ignored - "Last One In Wins" - */ - public void testChangeConflict1() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - - this.nameAdapter.setValue("Jason"); - assertEquals("Jason", this.employee.getName()); - assertEquals("Jason", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - - this.trigger.accept(); - // "Jason" is dropped on the floor... - assertEquals("Ripley", this.employee.getName()); - assertEquals("Ripley", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - } - - /** - * back-door changes can de-activate buffering (?) - */ - public void testChangeConflict2() { - PropertyChangeListener bufferedListener = this.buildBufferedListener(); - this.bufferedNameHolder.addPropertyChangeListener(PropertyValueModel.VALUE, bufferedListener); - - this.bufferedNameHolder.setValue("Ripley"); - assertEquals("Freddy", this.employee.getName()); - assertEquals("Freddy", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - assertTrue(this.bufferedNameHolder.isBuffering()); - - this.nameAdapter.setValue("Ripley"); - assertEquals("Ripley", this.employee.getName()); - assertEquals("Ripley", this.nameAdapter.getValue()); - assertEquals("Ripley", this.bufferedNameHolder.getValue()); - assertFalse(this.bufferedNameHolder.isBuffering()); - } - - private ChangeListener buildBufferedListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - BufferedWritablePropertyValueModelTests.this.bufferedEvent = e; - } - }; - } - - private ChangeListener buildAdapterListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - BufferedWritablePropertyValueModelTests.this.adapterEvent = e; - } - }; - } - - private ChangeListener buildEmployeeListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - BufferedWritablePropertyValueModelTests.this.employeeEvent = e; - } - }; - } - - private void verifyEvent(PropertyChangeEvent event, Object source, String propertyName, Object oldValue, Object newValue) { - assertEquals(source, event.getSource()); - assertEquals(propertyName, event.getPropertyName()); - assertEquals(oldValue, event.getOldValue()); - assertEquals(newValue, event.getNewValue()); - } - - - // ********** inner class ********** - - class Employee extends AbstractModel { - private int id; - public static final String ID_PROPERTY = "id"; - private String name; - public static final String NAME_PROPERTY = "name"; - private Date hireDate; - public static final String HIRE_DATE_PROPERTY = "hireDate"; - - Employee(int id, String name, Date hireDate) { - super(); - this.id = id; - this.name = name; - this.hireDate = hireDate; - } - int getID() { - return this.id; - } - void setID(int id) { - int old = this.id; - this.id = id; - this.firePropertyChanged(ID_PROPERTY, old, id); - } - String getName() { - return this.name; - } - void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - Date getHireDate() { - return this.hireDate; - } - void setHireDate(Date hireDate) { - Object old = this.hireDate; - this.hireDate = hireDate; - this.firePropertyChanged(HIRE_DATE_PROPERTY, old, hireDate); - } - @Override - public void toString(StringBuilder sb) { - sb.append(this.name); - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CachingTransformationPropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CachingTransformationPropertyValueModelTests.java deleted file mode 100644 index 63fc3f2bfb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CachingTransformationPropertyValueModelTests.java +++ /dev/null @@ -1,239 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.BidiTransformer; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.TransformationPropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CachingTransformationPropertyValueModelTests extends TestCase { - private ModifiablePropertyValueModel<Person> objectHolder; - PropertyChangeEvent event; - - private PropertyValueModel<Person> transformationObjectHolder; - PropertyChangeEvent transformationEvent; - - public CachingTransformationPropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = new SimplePropertyValueModel<Person>(new Person("Karen", "Peggy", null)); - this.transformationObjectHolder = new TransformationPropertyValueModel<Person, Person>(this.objectHolder, this.buildTransformer()); - } - - private BidiTransformer<Person, Person> buildTransformer() { - return new BidiTransformer<Person, Person>() { - public Person transform(Person p) { - return (p == null) ? null : p.getParent(); - } - public Person reverseTransform(Person p) { - return (p == null) ? null : p.getChild(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - ChangeListener listener = this.buildTransformationChangeListener(); - this.transformationObjectHolder.addChangeListener(listener); - - Person person = this.objectHolder.getValue(); - assertEquals("Karen", person.getName()); - Person parent = this.transformationObjectHolder.getValue(); - assertEquals(person.getParent().getName(), parent.getName()); - assertNotSame(person.getParent(), this.transformationObjectHolder.getValue()); - assertEquals(parent, this.transformationObjectHolder.getValue()); - - Person person1 = new Person("Matt", "Mitch", null); - this.objectHolder.setValue(person1); - Person parent2 = this.transformationObjectHolder.getValue(); - assertEquals(person1.getParent().getName(), parent2.getName()); - assertNotSame(person1.getParent(), this.transformationObjectHolder.getValue()); - assertEquals(parent2, this.transformationObjectHolder.getValue()); - - - this.objectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.transformationObjectHolder.getValue()); - - Person person3 = new Person("Karen", "Peggy", null); - this.objectHolder.setValue(person3); - assertEquals("Karen", person3.getName()); - Person parent3 = this.transformationObjectHolder.getValue(); - assertEquals(person3.getParent().getName(), parent3.getName()); - assertNotSame(person3.getParent(), this.transformationObjectHolder.getValue()); - assertEquals(parent3, this.transformationObjectHolder.getValue()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildTransformationChangeListener(); - this.transformationObjectHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.transformationObjectHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.transformationObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.transformationObjectHolder.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testPropertyChange1() { - this.objectHolder.addChangeListener(this.buildChangeListener()); - this.transformationObjectHolder.addChangeListener(this.buildTransformationChangeListener()); - this.verifyPropertyChanges(); - } - - public void testPropertyChange2() { - this.objectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.transformationObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildTransformationListener()); - this.verifyPropertyChanges(); - } - - private void verifyPropertyChanges() { - this.event = null; - this.transformationEvent = null; - Person karen = this.objectHolder.getValue(); - Person peggyParent = this.transformationObjectHolder.getValue(); - Person peggy = new Person("Peggy", "Marian", null); - this.objectHolder.setValue(peggy); - Person marianParent = this.transformationObjectHolder.getValue(); - this.verifyEvent(this.event, this.objectHolder, karen, peggy); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, peggyParent, marianParent); - - this.event = null; - this.transformationEvent = null; - Person matt = new Person("Matt", "Mitch", null); - this.objectHolder.setValue(matt); - Person mitchParent = this.transformationObjectHolder.getValue(); - this.verifyEvent(this.event, this.objectHolder, peggy, matt); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, marianParent, mitchParent); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue(null); - this.verifyEvent(this.event, this.objectHolder, matt, null); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, mitchParent, null); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue(matt); - mitchParent = this.transformationObjectHolder.getValue(); - this.verifyEvent(this.event, this.objectHolder, null, matt); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, null, mitchParent); - } - - private PropertyChangeListener buildListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - CachingTransformationPropertyValueModelTests.this.event = e; - } - }; - } - - private PropertyChangeListener buildTransformationListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - CachingTransformationPropertyValueModelTests.this.transformationEvent = e; - } - }; - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - CachingTransformationPropertyValueModelTests.this.event = e; - } - }; - } - - private ChangeListener buildTransformationChangeListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - CachingTransformationPropertyValueModelTests.this.transformationEvent = e; - } - }; - } - - private void verifyEvent(PropertyChangeEvent e, Object source, Object oldValue, Object newValue) { - assertEquals(source, e.getSource()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - assertEquals(oldValue, e.getOldValue()); - assertEquals(newValue, e.getNewValue()); - } - - - class Person - extends AbstractModel - { - private String name; - public static final String NAME_PROPERTY = "name"; - - private String parentName; - public static final String PARENT_NAME_PROPERTY = "parentName"; - - private Person child; - - public Person(String name, String parentName, Person child) { - this.name = name; - this.parentName = parentName; - this.child = child; - } - - public String getName() { - return this.name; - } - - public void setName(String newName) { - String oldName = this.name; - this.name = newName; - firePropertyChanged(NAME_PROPERTY, oldName, newName); - } - - public Person getParent() { - return new Person(this.parentName, null, this); - } - - public String getParentName() { - return this.parentName; - } - - public void setParentName(String newParentName) { - String oldParentName = this.parentName; - this.parentName = newParentName; - firePropertyChanged(PARENT_NAME_PROPERTY, oldParentName, newParentName); - } - - public Person getChild() { - return this.child; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CachingTransformationWritablePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CachingTransformationWritablePropertyValueModelTests.java deleted file mode 100644 index 7c711a316e..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CachingTransformationWritablePropertyValueModelTests.java +++ /dev/null @@ -1,259 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.TransformationWritablePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CachingTransformationWritablePropertyValueModelTests - extends TestCase -{ - private ModifiablePropertyValueModel<Person> objectHolder; - PropertyChangeEvent event; - - private ModifiablePropertyValueModel<Person> transformationObjectHolder; - PropertyChangeEvent transformationEvent; - - public CachingTransformationWritablePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = new SimplePropertyValueModel<Person>(new Person("Karen", "Peggy", null)); - this.transformationObjectHolder = new TransformationWritablePropertyValueModel<Person, Person>(this.objectHolder, this.buildTransformer(), this.buildReverseTransformer()); - } - - private Transformer<Person, Person> buildTransformer() { - return new Transformer<Person, Person>() { - public Person transform(Person p) { - return (p == null) ? null : p.getParent(); - } - }; - } - - private Transformer<Person, Person> buildReverseTransformer() { - return new Transformer<Person, Person>() { - public Person transform(Person p) { - return (p == null) ? null : p.getChild(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - ChangeListener listener = this.buildTransformationListener(); - this.transformationObjectHolder.addChangeListener(listener); - - - Person person = this.objectHolder.getValue(); - assertEquals("Karen", person.getName()); - Person parent = this.transformationObjectHolder.getValue(); - assertEquals(person.getParent().getName(), parent.getName()); - assertNotSame(person.getParent(), this.transformationObjectHolder.getValue()); - assertEquals(parent, this.transformationObjectHolder.getValue()); - - Person person1 = new Person("Matt", "Mitch", null); - this.objectHolder.setValue(person1); - Person parent2 = this.transformationObjectHolder.getValue(); - assertEquals(person1.getParent().getName(), parent2.getName()); - assertNotSame(person1.getParent(), this.transformationObjectHolder.getValue()); - assertEquals(parent2, this.transformationObjectHolder.getValue()); - - - this.objectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.transformationObjectHolder.getValue()); - - Person person3 = new Person("Karen", "Peggy", null); - this.objectHolder.setValue(person3); - assertEquals("Karen", person3.getName()); - Person parent3 = this.transformationObjectHolder.getValue(); - assertEquals(person3.getParent().getName(), parent3.getName()); - assertNotSame(person3.getParent(), this.transformationObjectHolder.getValue()); - assertEquals(parent3, this.transformationObjectHolder.getValue()); - } - - public void testSetValue() { - ChangeListener listener = this.buildTransformationListener(); - this.transformationObjectHolder.addChangeListener(listener); - - Person person = new Person("Chris", "Noel", null); - this.transformationObjectHolder.setValue(person.getParent()); - assertEquals(person, this.objectHolder.getValue()); - assertEquals(person.getParent().getName(), this.transformationObjectHolder.getValue().getName()); - assertNotSame(person.getParent(), this.transformationObjectHolder.getValue()); - - Person person2 = new Person("Jon", "Elizabeth", null); - this.transformationObjectHolder.setValue(person2.getParent()); - assertEquals(person2, this.objectHolder.getValue()); - assertEquals(person2.getParent().getName(), this.transformationObjectHolder.getValue().getName()); - assertNotSame(person2.getParent(), this.transformationObjectHolder.getValue()); - - this.transformationObjectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.transformationObjectHolder.getValue()); - - this.transformationObjectHolder.setValue(person.getParent()); - assertEquals(person, this.objectHolder.getValue()); - assertEquals(person.getParent().getName(), this.transformationObjectHolder.getValue().getName()); - assertNotSame(person.getParent(), this.transformationObjectHolder.getValue()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildTransformationListener(); - this.transformationObjectHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.transformationObjectHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.transformationObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.transformationObjectHolder.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testPropertyChange1() { - this.objectHolder.addChangeListener(this.buildListener()); - this.transformationObjectHolder.addChangeListener(this.buildTransformationListener()); - this.verifyPropertyChanges(); - } - - public void testPropertyChange2() { - this.objectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.transformationObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildTransformationListener()); - this.verifyPropertyChanges(); - } - - private void verifyPropertyChanges() { - this.event = null; - this.transformationEvent = null; - Person oldPerson = this.objectHolder.getValue(); - Person oldParent = this.transformationObjectHolder.getValue(); - Person newPerson = new Person("Karen" , "Peggy", null); - this.objectHolder.setValue(newPerson); - Person newParent = this.transformationObjectHolder.getValue(); - this.verifyEvent(this.event, this.objectHolder, oldPerson, newPerson); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, oldParent, newParent); - -// -// this.event = null; -// this.transformationEvent = null; -// this.objectHolder.setValue("Foo"); -// this.verifyEvent(this.event, this.objectHolder, "baz", "Foo"); -// this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, "BAZ", "FOO"); -// -// this.event = null; -// this.transformationEvent = null; -// this.objectHolder.setValue("FOO"); -// this.verifyEvent(this.event, this.objectHolder, "Foo", "FOO"); -// assertNull(this.transformationEvent); -// -// this.event = null; -// this.transformationEvent = null; -// this.objectHolder.setValue(null); -// this.verifyEvent(this.event, this.objectHolder, "FOO", null); -// this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, "FOO", null); -// -// this.event = null; -// this.transformationEvent = null; -// this.objectHolder.setValue("bar"); -// this.verifyEvent(this.event, this.objectHolder, null, "bar"); -// this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, null, "BAR"); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - CachingTransformationWritablePropertyValueModelTests.this.event = e; - } - }; - } - - private ChangeListener buildTransformationListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - CachingTransformationWritablePropertyValueModelTests.this.transformationEvent = e; - } - }; - } - - private void verifyEvent(PropertyChangeEvent e, Object source, Object oldValue, Object newValue) { - assertEquals(source, e.getSource()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - assertEquals(oldValue, e.getOldValue()); - assertEquals(newValue, e.getNewValue()); - } - - - class Person extends AbstractModel { - - private String name; - public static final String NAME_PROPERTY = "name"; - - private String parentName; - public static final String PARENT_NAME_PROPERTY = "parentName"; - - private Person child; - - public Person(String name, String parentName, Person child) { - this.name = name; - this.parentName = parentName; - this.child = child; - } - - public String getName() { - return this.name; - } - - public void setName(String newName) { - String oldName = this.name; - this.name = newName; - firePropertyChanged(NAME_PROPERTY, oldName, newName); - } - - public Person getParent() { - return new Person(this.parentName, null, this); - } - - public String getParentName() { - return this.parentName; - } - - public void setParentName(String newParentName) { - String oldParentName = this.parentName; - this.parentName = newParentName; - firePropertyChanged(PARENT_NAME_PROPERTY, oldParentName, newParentName); - } - - public Person getChild() { - return this.child; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionAspectAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionAspectAdapterTests.java deleted file mode 100644 index eadcc93bff..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionAspectAdapterTests.java +++ /dev/null @@ -1,370 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CollectionAspectAdapterTests extends TestCase { - private TestSubject subject1; - private ModifiablePropertyValueModel<TestSubject> subjectHolder1; - private LocalCollectionAspectAdapter aa1; - private CollectionEvent event1; - private CollectionChangeListener listener1; - private String event1Type; - - private static final String ADD = "add"; - private static final String REMOVE = "remove"; - private static final String CHANGE = "change"; - private static final String CLEAR = "clear"; - - private TestSubject subject2; - - public CollectionAspectAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.subject1 = new TestSubject(); - this.subject1.addNames(this.subject1Names()); - this.subject1.addDescriptions(this.subject1Descriptions()); - this.subjectHolder1 = new SimplePropertyValueModel<TestSubject>(this.subject1); - this.aa1 = this.buildAspectAdapter(this.subjectHolder1); - this.listener1 = this.buildValueChangeListener1(); - this.aa1.addCollectionChangeListener(CollectionValueModel.VALUES, this.listener1); - this.event1 = null; - this.event1Type = null; - - this.subject2 = new TestSubject(); - this.subject2.addNames(this.subject2Names()); - this.subject2.addDescriptions(this.subject2Descriptions()); - } - - private Collection<String> subject1Names() { - Collection<String> result = new HashBag<String>(); - result.add("foo"); - result.add("bar"); - return result; - } - - private Collection<String> subject1Descriptions() { - Collection<String> result = new HashBag<String>(); - result.add("this.subject1 description1"); - result.add("this.subject1 description2"); - return result; - } - - private Collection<String> subject2Names() { - Collection<String> result = new HashBag<String>(); - result.add("baz"); - result.add("bam"); - return result; - } - - private Collection<String> subject2Descriptions() { - Collection<String> result = new HashBag<String>(); - result.add("this.subject2 description1"); - result.add("this.subject2 description2"); - return result; - } - - private LocalCollectionAspectAdapter buildAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - return new LocalCollectionAspectAdapter(subjectHolder); - } - - private CollectionChangeListener buildValueChangeListener1() { - return new CollectionChangeListener() { - public void itemsAdded(CollectionAddEvent e) { - CollectionAspectAdapterTests.this.value1Changed(e, ADD); - } - public void itemsRemoved(CollectionRemoveEvent e) { - CollectionAspectAdapterTests.this.value1Changed(e, REMOVE); - } - public void collectionCleared(CollectionClearEvent e) { - CollectionAspectAdapterTests.this.value1Changed(e, CLEAR); - } - public void collectionChanged(CollectionChangeEvent e) { - CollectionAspectAdapterTests.this.value1Changed(e, CHANGE); - } - }; - } - - void value1Changed(CollectionEvent e, String eventType) { - this.event1 = e; - this.event1Type = eventType; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSubjectHolder() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); - assertNull(this.event1); - - this.subjectHolder1.setValue(this.subject2); - assertNotNull(this.event1); - assertEquals(this.event1Type, CHANGE); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals(this.subject2Names(), CollectionTools.bag(this.aa1.iterator())); - - this.event1 = null; - this.event1Type = null; - this.subjectHolder1.setValue(null); - assertNotNull(this.event1); - assertEquals(this.event1Type, CHANGE); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertFalse(this.aa1.iterator().hasNext()); - - this.event1 = null; - this.event1Type = null; - this.subjectHolder1.setValue(this.subject1); - assertNotNull(this.event1); - assertEquals(this.event1Type, CHANGE); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); - } - - public void testAdd() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); - assertNull(this.event1); - - this.subject1.addName("jam"); - assertNotNull(this.event1); - assertEquals(this.event1Type, ADD); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals("jam", ((CollectionAddEvent) this.event1).getItems().iterator().next()); - Collection<String> namesPlus = this.subject1Names(); - namesPlus.add("jam"); - assertEquals(namesPlus, CollectionTools.bag(this.aa1.iterator())); - - this.event1 = null; - this.event1Type = null; - this.aa1.addAll(Collections.singleton("jaz")); - assertNotNull(this.event1); - assertEquals(this.event1Type, ADD); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals("jaz", ((CollectionAddEvent) this.event1).getItems().iterator().next()); - namesPlus.add("jaz"); - assertEquals(namesPlus, CollectionTools.bag(this.aa1.iterator())); - } - - public void testRemove() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); - assertNull(this.event1); - - this.subject1.removeName("foo"); - assertNotNull(this.event1); - assertEquals(this.event1Type, REMOVE); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals("foo", ((CollectionRemoveEvent) this.event1).getItems().iterator().next()); - Collection<String> namesMinus = this.subject1Names(); - namesMinus.remove("foo"); - assertEquals(namesMinus, CollectionTools.bag(this.aa1.iterator())); - - this.event1 = null; - this.event1Type = null; - this.aa1.removeAll(Collections.singleton("bar")); - assertNotNull(this.event1); - assertEquals(this.event1Type, REMOVE); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals("bar", ((CollectionRemoveEvent) this.event1).getItems().iterator().next()); - namesMinus.remove("bar"); - assertEquals(namesMinus, CollectionTools.bag(this.aa1.iterator())); - } - - public void testCollectionChange() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); - assertNull(this.event1); - - this.subject1.addTwoNames("jam", "jaz"); - assertNotNull(this.event1); - assertEquals(this.event1Type, CHANGE); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - Collection<String> namesPlus2 = this.subject1Names(); - namesPlus2.add("jam"); - namesPlus2.add("jaz"); - assertEquals(namesPlus2, CollectionTools.bag(this.aa1.iterator())); - } - - public void testIterator() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.subject1.names())); - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); - } - - public void testSize() { - assertEquals(this.subject1Names().size(), CollectionTools.size(this.subject1.names())); - assertEquals(this.subject1Names().size(), CollectionTools.size(this.aa1.iterator())); - } - - public void testHasListeners() { - assertTrue(this.aa1.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertTrue(this.subject1.hasAnyCollectionChangeListeners(TestSubject.NAMES_COLLECTION)); - this.aa1.removeCollectionChangeListener(CollectionValueModel.VALUES, this.listener1); - assertFalse(this.subject1.hasAnyCollectionChangeListeners(TestSubject.NAMES_COLLECTION)); - assertFalse(this.aa1.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - ChangeListener listener2 = new ChangeAdapter(); - this.aa1.addChangeListener(listener2); - assertTrue(this.aa1.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertTrue(this.subject1.hasAnyCollectionChangeListeners(TestSubject.NAMES_COLLECTION)); - this.aa1.removeChangeListener(listener2); - assertFalse(this.subject1.hasAnyCollectionChangeListeners(TestSubject.NAMES_COLLECTION)); - assertFalse(this.aa1.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - - // ********** inner class ********** - - private class TestSubject extends AbstractModel { - private Collection<String> names; - public static final String NAMES_COLLECTION = "names"; - private Collection<String> descriptions; - public static final String DESCRIPTIONS_COLLECTION = "descriptions"; - - public TestSubject() { - this.names = new HashBag<String>(); - this.descriptions = new HashBag<String>(); - } - public Iterator<String> names() { - return new ReadOnlyIterator<String>(this.names); - } - public void addName(String name) { - if (this.names.add(name)) { - this.fireItemAdded(NAMES_COLLECTION, name); - } - } - public void addNames(Iterator<String> newNames) { - while (newNames.hasNext()) { - this.addName(newNames.next()); - } - } - public void addNames(Collection<String> newNames) { - this.addNames(newNames.iterator()); - } - public void addTwoNames(String name1, String name2) { - if (this.names.add(name1) | this.names.add(name2)) { - this.fireCollectionChanged(NAMES_COLLECTION, this.names); - } - } - public void removeName(String name) { - if (this.names.remove(name)) { - this.fireItemRemoved(NAMES_COLLECTION, name); - } - } - public Iterator<String> descriptions() { - return new ReadOnlyIterator<String>(this.descriptions); - } - public void addDescription(String description) { - if (this.descriptions.add(description)) { - this.fireItemAdded(DESCRIPTIONS_COLLECTION, description); - } - } - public void addDescriptions(Iterator<String> newDescriptions) { - while (newDescriptions.hasNext()) { - this.addDescription(newDescriptions.next()); - } - } - public void addDescriptions(Collection<String> newDescriptions) { - this.addDescriptions(newDescriptions.iterator()); - } - public void removeDescription(String description) { - if (this.descriptions.remove(description)) { - this.fireItemRemoved(DESCRIPTIONS_COLLECTION, description); - } - } - } - - // this is not a typical aspect adapter - the value is determined by the aspect name - private class LocalCollectionAspectAdapter extends CollectionAspectAdapter<TestSubject, String> { - - LocalCollectionAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - super(subjectHolder, TestSubject.NAMES_COLLECTION); - } - - @Override - protected Iterator<String> iterator_() { - if (this.aspectNames[0] == TestSubject.NAMES_COLLECTION) { - return this.subject.names(); - } - if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_COLLECTION) { - return this.subject.descriptions(); - } - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - - public void add(String item) { - if (this.aspectNames[0] == TestSubject.NAMES_COLLECTION) { - this.subject.addName(item); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_COLLECTION) { - this.subject.addDescription(item); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - - public void addAll(Collection<String> items) { - for (Iterator<String> stream = items.iterator(); stream.hasNext(); ) { - this.add(stream.next()); - } - } - - public void remove(Object item) { - if (this.aspectNames[0] == TestSubject.NAMES_COLLECTION) { - this.subject.removeName((String) item); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_COLLECTION) { - this.subject.removeDescription((String) item); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - - public void removeAll(Collection<String> items) { - for (Iterator<String> stream = items.iterator(); stream.hasNext(); ) { - this.remove(stream.next()); - } - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionListValueModelAdapterTests.java deleted file mode 100644 index 7c0a154f5b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionListValueModelAdapterTests.java +++ /dev/null @@ -1,247 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; -import java.util.List; - -import javax.swing.JList; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CollectionListValueModelAdapterTests extends TestCase { - private ListValueModel<String> adapter; - private SimpleCollectionValueModel<String> wrappedCollectionHolder; - private Collection<String> wrappedCollection; - - public CollectionListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.wrappedCollection = new HashBag<String>(); - this.wrappedCollectionHolder = new SimpleCollectionValueModel<String>(this.wrappedCollection); - this.adapter = new CollectionListValueModelAdapter<String>(this.wrappedCollectionHolder); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - }); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - Collection<String> adapterCollection = this.adapterCollection(); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection, adapterCollection); - } - - private Collection<String> adapterCollection() { - return CollectionTools.collection(this.adapter.iterator()); - } - - public void testStaleValue() { - ListChangeListener listener = new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - }; - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, listener); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - Collection<String> adapterCollection = this.adapterCollection(); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection, adapterCollection); - - this.adapter.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - adapterCollection = this.adapterCollection(); - assertEquals(0, adapterCollection.size()); - assertEquals(new HashBag<String>(), adapterCollection); - - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, listener); - adapterCollection = this.adapterCollection(); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection, adapterCollection); - } - - public void testAdd() { - List<String> synchList = new CoordinatedList<String>(this.adapter); - Bag<String> synchCollection = new CoordinatedBag<String>(this.wrappedCollectionHolder); - this.wrappedCollectionHolder.add("foo"); - assertTrue(this.wrappedCollection.contains("foo")); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - assertEquals(6, this.wrappedCollection.size()); - - Collection<String> adapterCollection = this.adapterCollection(); - assertEquals(this.wrappedCollection, adapterCollection); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection, synchCollection); - } - - public void testRemove() { - List<String> synchList = new CoordinatedList<String>(this.adapter); - Bag<String> synchCollection = new CoordinatedBag<String>(this.wrappedCollectionHolder); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - assertTrue(this.wrappedCollection.contains("jaz")); - this.wrappedCollectionHolder.remove("jaz"); - assertFalse(this.wrappedCollection.contains("jaz")); - this.wrappedCollectionHolder.remove("foo"); - assertFalse(this.wrappedCollection.contains("foo")); - assertEquals(4, this.wrappedCollection.size()); - - Collection<String> adapterCollection = this.adapterCollection(); - assertEquals(this.wrappedCollection, adapterCollection); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection, synchCollection); - } - - public void testListSynch() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsRemoved(ListRemoveEvent e) {/* OK */} - }); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - this.wrappedCollectionHolder.remove("jaz"); - assertFalse(this.wrappedCollection.contains("jaz")); - this.wrappedCollectionHolder.remove("foo"); - assertFalse(this.wrappedCollection.contains("foo")); - assertEquals(4, this.wrappedCollection.size()); - - Collection<String> adapterCollection = this.adapterCollection(); - assertEquals(this.wrappedCollection, adapterCollection); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - CoordinatedList<String> synchList = new CoordinatedList<String>(this.adapter); - assertTrue(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.adapter.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener cl = new ChangeAdapter(); - this.adapter.addChangeListener(cl); - assertTrue(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.adapter.removeChangeListener(cl); - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - public void testCollectionChangedToEmpty() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void listCleared(ListClearEvent e) {/* OK */} - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - }); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - JList jList = new JList(new ListModelAdapter(this.adapter)); - this.wrappedCollectionHolder.setValues(new HashBag<String>()); - assertEquals(0, jList.getModel().getSize()); - } - - public void testCollectionChangedFromEmpty() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsRemoved(ListRemoveEvent e) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - HashBag<String> bag = new HashBag<String>(); - bag.add("foo"); - bag.add("bar"); - this.wrappedCollectionHolder.setValues(bag); - assertEquals(2, jList.getModel().getSize()); - } - - public void testCollectionChangedFromEmptyToEmpty() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsRemoved(ListRemoveEvent e) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - HashBag<String> bag = new HashBag<String>(); - this.wrappedCollectionHolder.setValues(bag); - assertEquals(0, jList.getModel().getSize()); - } - - - class TestListChangeListener implements ListChangeListener { - public void itemsAdded(ListAddEvent e) { - fail("unexpected event"); - } - public void itemsRemoved(ListRemoveEvent e) { - fail("unexpected event"); - } - public void itemsReplaced(ListReplaceEvent e) { - fail("unexpected event"); - } - public void itemsMoved(ListMoveEvent e) { - fail("unexpected event"); - } - public void listCleared(ListClearEvent e) { - fail("unexpected event"); - } - public void listChanged(ListChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionPropertyValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionPropertyValueModelAdapterTests.java deleted file mode 100644 index 9b9343ce75..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CollectionPropertyValueModelAdapterTests.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionPropertyValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CollectionPropertyValueModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Boolean> adapter; - private SimpleCollectionValueModel<String> wrappedCollectionHolder; - PropertyChangeEvent event; - - public CollectionPropertyValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.wrappedCollectionHolder = new SimpleCollectionValueModel<String>(); - this.adapter = new LocalAdapter(this.wrappedCollectionHolder, "666"); - this.event = null; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - private boolean booleanValue() { - return this.adapter.getValue().booleanValue(); - } - - private Collection<String> wrappedCollection() { - return CollectionTools.collection(this.wrappedCollectionHolder.iterator()); - } - - public void testValue() { - this.adapter.addPropertyChangeListener(PropertyValueModel.VALUE, new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) {/* OK */} - }); - assertFalse(this.booleanValue()); - assertFalse(this.wrappedCollection().contains("666")); - - this.wrappedCollectionHolder.add("111"); - assertFalse(this.booleanValue()); - - this.wrappedCollectionHolder.add("222"); - assertFalse(this.booleanValue()); - - this.wrappedCollectionHolder.add("666"); - assertTrue(this.booleanValue()); - assertTrue(this.wrappedCollection().contains("666")); - - this.wrappedCollectionHolder.remove("666"); - assertFalse(this.booleanValue()); - assertFalse(this.wrappedCollection().contains("666")); - - this.wrappedCollectionHolder.add("666"); - assertTrue(this.booleanValue()); - assertTrue(this.wrappedCollection().contains("666")); - - this.wrappedCollectionHolder.clear(); - assertFalse(this.booleanValue()); - assertFalse(this.wrappedCollection().contains("666")); - } - - public void testSetValue() { - this.adapter.addPropertyChangeListener(PropertyValueModel.VALUE, new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) {/* OK */} - }); - assertFalse(this.booleanValue()); - assertFalse(this.wrappedCollection().contains("666")); - - this.adapter.setValue(Boolean.TRUE); - assertTrue(this.booleanValue()); - assertTrue(this.wrappedCollection().contains("666")); - - this.adapter.setValue(Boolean.FALSE); - assertFalse(this.booleanValue()); - assertFalse(this.wrappedCollection().contains("666")); - } - - public void testEventFiring() { - this.adapter.addPropertyChangeListener(PropertyValueModel.VALUE, new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - CollectionPropertyValueModelAdapterTests.this.event = e; - } - }); - assertNull(this.event); - - this.wrappedCollectionHolder.add("111"); - assertNull(this.event); - - this.wrappedCollectionHolder.add("222"); - assertNull(this.event); - - this.wrappedCollectionHolder.add("666"); - this.verifyEvent(false, true); - - this.wrappedCollectionHolder.remove("666"); - this.verifyEvent(true, false); - - this.wrappedCollectionHolder.add("666"); - this.verifyEvent(false, true); - - this.wrappedCollectionHolder.clear(); - this.verifyEvent(true, false); - } - - private void verifyEvent(boolean oldValue, boolean newValue) { - assertEquals(this.adapter, this.event.getSource()); - assertEquals(Boolean.valueOf(oldValue), this.event.getOldValue()); - assertEquals(Boolean.valueOf(newValue), this.event.getNewValue()); - this.event = null; - } - - public void testStaleValue() { - PropertyChangeListener listener = new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) {/* OK */} - }; - this.adapter.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - this.wrappedCollectionHolder.add("666"); - assertTrue(this.booleanValue()); - assertTrue(this.wrappedCollection().contains("666")); - - this.adapter.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertFalse(this.booleanValue()); - assertTrue(this.wrappedCollection().contains("666")); - - this.adapter.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(this.booleanValue()); - assertTrue(this.wrappedCollection().contains("666")); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.adapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(((AbstractModel) this.wrappedCollectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - ChangeListener listener = new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) {/* OK */} - }; - this.adapter.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.adapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.wrappedCollectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - this.adapter.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertFalse(((AbstractModel) this.adapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(((AbstractModel) this.wrappedCollectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - this.adapter.addChangeListener(listener); - assertTrue(((AbstractModel) this.adapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.wrappedCollectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - this.adapter.removeChangeListener(listener); - assertFalse(((AbstractModel) this.adapter).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(((AbstractModel) this.wrappedCollectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - - // ********** member class ********** - - /** - * the value is true if the wrapped collection contains the specified item, - * otherwise the value is false - */ - static class LocalAdapter - extends CollectionPropertyValueModelAdapter<Boolean, String> - implements ModifiablePropertyValueModel<Boolean> - { - private String item; - - LocalAdapter(CollectionValueModel<String> collectionHolder, String item) { - super(collectionHolder); - this.item = item; - } - - // ********** CollectionPropertyValueModelAdapter implementation ********** - /** - * always return a Boolean - */ - @Override - public Boolean getValue() { - Boolean result = super.getValue(); - return (result == null) ? Boolean.FALSE : result; - } - @SuppressWarnings("unchecked") - public void setValue(Boolean value) { - if (this.booleanValue()) { - if ( ! this.booleanValueOf(value)) { - // the value is changing from true to false - ((SimpleCollectionValueModel<String>) this.collectionModel).remove(this.item); - } - } else { - if (this.booleanValueOf(value)) { - // the value is changing from false to true - ((SimpleCollectionValueModel<String>) this.collectionModel).add(this.item); - } - } - } - @Override - protected Boolean buildValue() { - return Boolean.valueOf(CollectionTools.contains(this.collectionModel.iterator(), this.item)); - } - - // ********** internal methods ********** - private boolean booleanValue() { - return this.booleanValueOf(this.value); - } - private boolean booleanValueOf(Object b) { - return (b == null) ? false : ((Boolean) b).booleanValue(); - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeBooleanPropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeBooleanPropertyValueModelTests.java deleted file mode 100644 index 5f27baf3f1..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeBooleanPropertyValueModelTests.java +++ /dev/null @@ -1,201 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.value.CompositeBooleanPropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class CompositeBooleanPropertyValueModelTests extends TestCase { - private SimplePropertyValueModel<Boolean> pvm1; - private ModifiablePropertyValueModel<Boolean> pvm2; - private ModifiablePropertyValueModel<Boolean> pvm3; - private ModifiablePropertyValueModel<Boolean> pvm4; - private Collection<ModifiablePropertyValueModel<Boolean>> collection; - private SimpleCollectionValueModel<ModifiablePropertyValueModel<Boolean>> cvm; - private PropertyValueModel<Boolean> compositePVM; - PropertyChangeEvent event; - - - public CompositeBooleanPropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.pvm1 = new SimplePropertyValueModel<Boolean>(Boolean.TRUE); - this.pvm2 = new SimplePropertyValueModel<Boolean>(Boolean.TRUE); - this.pvm3 = new SimplePropertyValueModel<Boolean>(Boolean.TRUE); - this.pvm4 = new SimplePropertyValueModel<Boolean>(Boolean.TRUE); - this.collection = new ArrayList<ModifiablePropertyValueModel<Boolean>>(); - this.collection.add(this.pvm1); - this.collection.add(this.pvm2); - this.collection.add(this.pvm3); - this.collection.add(this.pvm4); - this.cvm = new SimpleCollectionValueModel<ModifiablePropertyValueModel<Boolean>>(this.collection); - - this.compositePVM = this.buildCompositePVM(cvm); - } - - private PropertyValueModel<Boolean> buildCompositePVM(CollectionValueModel<ModifiablePropertyValueModel<Boolean>> pvms) { - return CompositeBooleanPropertyValueModel.and(pvms); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetValue() { - assertNull(this.compositePVM.getValue()); - ChangeListener listener = this.buildListener(); - this.compositePVM.addChangeListener(listener); - assertTrue(this.compositePVM.getValue().booleanValue()); - } - - public void testValueAndListeners1() { - assertNull(this.compositePVM.getValue()); - ChangeListener listener = this.buildListener(); - this.compositePVM.addChangeListener(listener); - assertTrue(this.compositePVM.getValue().booleanValue()); - this.compositePVM.removeChangeListener(listener); - assertNull(this.compositePVM.getValue()); - } - - public void testValueAndListeners2() { - assertNull(this.compositePVM.getValue()); - ChangeListener listener = this.buildListener(); - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(this.compositePVM.getValue().booleanValue()); - this.compositePVM.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertNull(this.compositePVM.getValue()); - } - - public void testPropertyChange1() { - this.compositePVM.addChangeListener(this.buildListener()); - this.verifyPropertyChange(); - } - - public void testPropertyChange2() { - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.verifyPropertyChange(); - } - - private void verifyPropertyChange() { - this.event = null; - this.pvm1.setValue(Boolean.FALSE); - this.verifyEvent(true, false); - - this.event = null; - this.pvm2.setValue(Boolean.FALSE); - assertNull(this.event); // no change - - this.event = null; - this.pvm2.setValue(Boolean.TRUE); - assertNull(this.event); // no change - - this.event = null; - this.pvm1.setValue(Boolean.TRUE); - this.verifyEvent(false, true); - - this.event = null; - this.pvm4.setValue(Boolean.FALSE); - this.verifyEvent(true, false); - } - - public void testCollectionChange1() { - this.compositePVM.addChangeListener(this.buildListener()); - this.verifyCollectionChange(); - } - - public void testCollectionChange2() { - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.verifyCollectionChange(); - } - - private void verifyCollectionChange() { - this.event = null; - ModifiablePropertyValueModel<Boolean> pvm = new SimplePropertyValueModel<Boolean>(Boolean.FALSE); - this.cvm.add(pvm); - this.verifyEvent(true, false); - - this.event = null; - this.cvm.remove(pvm); - this.verifyEvent(false, true); - - this.event = null; - this.cvm.clear(); - this.verifyEvent(Boolean.TRUE, null); - - Collection<ModifiablePropertyValueModel<Boolean>> c2 = new ArrayList<ModifiablePropertyValueModel<Boolean>>(); - c2.add(this.pvm1); - c2.add(this.pvm2); - this.event = null; - this.cvm.setValues(c2); - this.verifyEvent(null, Boolean.TRUE); - } - - public void testLazyListening1() { - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildListener(); - - this.compositePVM.addChangeListener(listener); - assertTrue(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.compositePVM.removeChangeListener(listener); - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testLazyListening2() { - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildListener(); - - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.compositePVM.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - CompositeBooleanPropertyValueModelTests.this.event = e; - } - }; - } - - private void verifyEvent(boolean oldValue, boolean newValue) { - this.verifyEvent(Boolean.valueOf(oldValue), Boolean.valueOf(newValue)); - } - - private void verifyEvent(Boolean oldValue, Boolean newValue) { - assertEquals(this.compositePVM, this.event.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event.getPropertyName()); - assertEquals(oldValue, this.event.getOldValue()); - assertEquals(newValue, this.event.getNewValue()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeCollectionValueModelTests.java deleted file mode 100644 index 6e8e9346f1..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeCollectionValueModelTests.java +++ /dev/null @@ -1,415 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.iterators.CompositeIterator; -import org.eclipse.jpt.common.utility.internal.iterators.TransformationIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.CompositeCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CompositeCollectionValueModelTests extends TestCase { - private Neighborhood neighborhood; - private ModifiablePropertyValueModel<Neighborhood> neighborhoodHolder; - - public CompositeCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.neighborhood = new Neighborhood("Hanna-Barbera"); - this.neighborhoodHolder = new SimplePropertyValueModel<Neighborhood>(this.neighborhood); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSynch1() { - this.verifySynch(this.buildAllMembersComposite(this.neighborhoodHolder)); - } - - public void testSynch2() { - this.verifySynch(this.buildAllMembersComposite2(this.neighborhoodHolder)); - } - - private void verifySynch(CollectionValueModel<Member> compositeCVM) { - assertEquals(0, CollectionTools.size(compositeCVM.iterator())); - Bag<Family> familiesSynch = new CoordinatedBag<Family>(this.buildFamiliesAspectAdapter(this.neighborhoodHolder)); - Bag<Member> membersSynch = new CoordinatedBag<Member>(compositeCVM); - this.populateNeighborhood(this.neighborhood); - - Family jetsons = this.neighborhood.familyNamed("Jetson"); - - assertEquals(3, familiesSynch.size()); - assertEquals(12, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(12, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - jetsons.removeMember(jetsons.memberNamed("Astro")); - assertEquals(3, familiesSynch.size()); - assertEquals(11, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(11, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - jetsons.removeMember(jetsons.memberNamed("Judy")); - assertEquals(3, familiesSynch.size()); - assertEquals(10, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(10, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - jetsons.addMember("Fido"); - assertEquals(3, familiesSynch.size()); - assertEquals(11, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(11, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - this.neighborhood.removeFamily(jetsons); - assertEquals(2, familiesSynch.size()); - assertEquals(7, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(7, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - Family bears = this.neighborhood.addFamily("Bear"); - bears.addMember("Yogi"); - assertEquals(3, familiesSynch.size()); - assertEquals(8, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(8, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - bears.addMember("Boo-Boo"); - assertEquals(3, familiesSynch.size()); - assertEquals(9, CollectionTools.size(this.neighborhood.allMembers())); - assertEquals(9, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - - Neighborhood n2 = new Neighborhood("Hanna-Barbera 2"); - this.neighborhoodHolder.setValue(n2); - this.populateNeighborhood(n2); - assertEquals(3, familiesSynch.size()); - assertEquals(12, CollectionTools.size(n2.allMembers())); - assertEquals(12, membersSynch.size()); - assertEquals(CollectionTools.bag(n2.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); - } - - public void testNoTransformer() { - SimpleCollectionValueModel<String> subCVM1 = new SimpleCollectionValueModel<String>(); - SimpleCollectionValueModel<String> subCVM2 = new SimpleCollectionValueModel<String>(); - Collection<CollectionValueModel<String>> collection = new ArrayList<CollectionValueModel<String>>(); - collection.add(subCVM1); - collection.add(subCVM2); - Bag<String> synchBag = new CoordinatedBag<String>(new CompositeCollectionValueModel<CollectionValueModel<String>, String>(collection)); - - assertEquals(0, synchBag.size()); - - subCVM1.add("foo"); - subCVM1.add("bar"); - subCVM1.add("baz"); - assertEquals(3, synchBag.size()); - assertTrue(synchBag.contains("foo")); - - subCVM2.add("joo"); - subCVM2.add("jar"); - subCVM2.add("jaz"); - assertEquals(6, synchBag.size()); - assertTrue(synchBag.contains("foo")); - assertTrue(synchBag.contains("jaz")); - - subCVM1.remove("baz"); - assertEquals(5, synchBag.size()); - assertFalse(synchBag.contains("baz")); - } - - public void testDuplicateItem() { - Bag<Member> synchBag = new CoordinatedBag<Member>(this.buildAllMembersComposite(this.neighborhoodHolder)); - this.populateNeighborhood(this.neighborhood); - boolean exCaught = false; - try { - this.neighborhood.addFamily(this.neighborhood.familyNamed("Jetson")); - } catch (IllegalStateException ex) { - if (ex.getMessage().indexOf("duplicate component") != -1) { - exCaught = true; - } - } - assertTrue(exCaught); - assertEquals(12, synchBag.size()); - } - - public void testHasListeners() { - CompositeCollectionValueModel<Family, Member> compositeCVM = this.buildAllMembersComposite(this.neighborhoodHolder); - CoordinatedBag<Member> synchBag = new CoordinatedBag<Member>(compositeCVM); - this.populateNeighborhood(this.neighborhood); - Family jetsons = this.neighborhood.familyNamed("Jetson"); - - assertTrue(compositeCVM.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertTrue(jetsons.hasAnyCollectionChangeListeners(Family.MEMBERS_COLLECTION)); - - compositeCVM.removeCollectionChangeListener(CollectionValueModel.VALUES, synchBag); - assertFalse(compositeCVM.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertFalse(jetsons.hasAnyCollectionChangeListeners(Family.MEMBERS_COLLECTION)); - - compositeCVM.addCollectionChangeListener(CollectionValueModel.VALUES, synchBag); - assertTrue(compositeCVM.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertTrue(jetsons.hasAnyCollectionChangeListeners(Family.MEMBERS_COLLECTION)); - } - - private void populateNeighborhood(Neighborhood n) { - Family family1 = n.addFamily("Flintstone"); - family1.addMember("Fred"); - family1.addMember("Wilma"); - family1.addMember("Pebbles"); - family1.addMember("Dino"); - Family family2 = n.addFamily("Rubble"); - family2.addMember("Barney"); - family2.addMember("Betty"); - family2.addMember("Bamm-Bamm"); - Family family3 = n.addFamily("Jetson"); - family3.addMember("George"); - family3.addMember("Jane"); - family3.addMember("Judy"); - family3.addMember("Elroy"); - family3.addMember("Astro"); - } - - private CollectionValueModel<Family> buildFamiliesAspectAdapter(PropertyValueModel<Neighborhood> communeHolder) { - return new CollectionAspectAdapter<Neighborhood, Family>(communeHolder, Neighborhood.FAMILIES_COLLECTION) { - @Override - protected Iterator<Family> iterator_() { - return this.subject.families(); - } - }; - } - - CollectionValueModel<Member> buildMembersAdapter(Family family) { - return new CollectionAspectAdapter<Family, Member>(Family.MEMBERS_COLLECTION, family) { - @Override - protected Iterator<Member> iterator_() { - return this.subject.members(); - } - }; - } - - private CompositeCollectionValueModel<Family, Member> buildAllMembersComposite(PropertyValueModel<Neighborhood> communeHolder) { - // override #transform(Object) - return new CompositeCollectionValueModel<Family, Member>(this.buildFamiliesAspectAdapter(communeHolder)) { - @Override - protected CollectionValueModel<Member> transform(Family family) { - return CompositeCollectionValueModelTests.this.buildMembersAdapter(family); - } - }; - } - - private CollectionValueModel<Member> buildAllMembersComposite2(PropertyValueModel<Neighborhood> communeHolder) { - // build a custom Transformer - return new CompositeCollectionValueModel<Family, Member>(this.buildFamiliesAspectAdapter(communeHolder), this.buildTransformer()); - } - - private Transformer<Family, CollectionValueModel<Member>> buildTransformer() { - return new Transformer<Family, CollectionValueModel<Member>>() { - public CollectionValueModel<Member> transform(Family family) { - return CompositeCollectionValueModelTests.this.buildMembersAdapter(family); - } - @Override - public String toString() { - return "Local Transformer"; - } - }; - } - - -// ********** inner classes ********** - - /** - * inner class - */ - public class Neighborhood extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - private Collection<Family> families = new ArrayList<Family>(); - public static final String FAMILIES_COLLECTION = "families"; - - public Neighborhood(String name) { - super(); - this.name = name; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - public Iterator<Family> families() { - return this.families.iterator(); - } - - public Family addFamily(String familyName) { - return this.addFamily(new Family(familyName)); - } - - // backdoor to allow duplicates - public Family addFamily(Family family) { - this.addItemToCollection(family, this.families, FAMILIES_COLLECTION); - return family; - } - - public void removeFamily(Family family) { - this.removeItemFromCollection(family, this.families, FAMILIES_COLLECTION); - } - - public Family familyNamed(String familyName) { - for (Family family : this.families) { - if (family.getName().equals(familyName)) { - return family; - } - } - throw new IllegalArgumentException(familyName); - } - - public Iterator<Member> allMembers() { - return new CompositeIterator<Member>(this.membersIterators()); - } - - private Iterator<Iterator<Member>> membersIterators() { - return new TransformationIterator<Family, Iterator<Member>>(this.families()) { - @Override - protected Iterator<Member> transform(Family family) { - return family.members(); - } - }; - } - - public Member memberNamed(String familyName, String memberName) { - return this.familyNamed(familyName).memberNamed(memberName); - } - - @Override - public void toString(StringBuilder sb) { - sb.append(this.name); - } - - } - - - /** - * inner class - */ - public class Family extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - private Collection<Member> members = new ArrayList<Member>(); - public static final String MEMBERS_COLLECTION = "members"; - - public Family(String name) { - super(); - this.name = name; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - public Iterator<Member> members() { - return this.members.iterator(); - } - - public Member addMember(String memberName) { - Member member = new Member(memberName); - this.addItemToCollection(member, this.members, MEMBERS_COLLECTION); - return member; - } - - public void removeMember(Member member) { - this.removeItemFromCollection(member, this.members, MEMBERS_COLLECTION); - } - - public Member memberNamed(String memberName) { - for (Member member : this.members) { - if (member.getName().equals(memberName)) { - return member; - } - } - throw new IllegalArgumentException(memberName); - } - - @Override - public void toString(StringBuilder sb) { - sb.append(this.name); - } - - } - - - /** - * inner class - */ - public class Member extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - - public Member(String name) { - super(); - this.name = name; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - @Override - public void toString(StringBuilder sb) { - sb.append(this.name); - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeListValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeListValueModelTests.java deleted file mode 100644 index 82cf531454..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositeListValueModelTests.java +++ /dev/null @@ -1,1248 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.CompositeListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CompositeListValueModelTests extends TestCase { - private LocalListValueModel<String> lvm0; - private LocalListValueModel<String> lvm1; - private LocalListValueModel<String> lvm2; - private LocalListValueModel<String> lvm3; - private LocalListValueModel<LocalListValueModel<String>> uberLVM; - private CompositeListValueModel<LocalListValueModel<String>, String> compositeLVM; - - public CompositeListValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - this.lvm0 = new LocalListValueModel<String>(); - this.lvm0.add("aaa"); - this.lvm0.add("bbb"); - this.lvm0.add("ccc"); - - this.lvm1 = new LocalListValueModel<String>(); - this.lvm1.add("ddd"); - this.lvm1.add("eee"); - - this.lvm2 = new LocalListValueModel<String>(); - this.lvm2.add("fff"); - - this.lvm3 = new LocalListValueModel<String>(); - this.lvm3.add("ggg"); - this.lvm3.add("hhh"); - this.lvm3.add("iii"); - this.lvm3.add("jjj"); - this.lvm3.add("kkk"); - - this.uberLVM = new LocalListValueModel<LocalListValueModel<String>>(); - this.uberLVM.add(this.lvm0); - this.uberLVM.add(this.lvm1); - this.uberLVM.add(this.lvm2); - this.uberLVM.add(this.lvm3); - - this.compositeLVM = new CompositeListValueModel<LocalListValueModel<String>, String>((ListValueModel<LocalListValueModel<String>>) this.uberLVM); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetInt() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - assertEquals("aaa", this.compositeLVM.get(0)); - assertEquals("aaa", coordList.get(0)); - assertEquals("bbb", this.compositeLVM.get(1)); - assertEquals("bbb", coordList.get(1)); - assertEquals("ccc", this.compositeLVM.get(2)); - assertEquals("ccc", coordList.get(2)); - - assertEquals("ddd", this.compositeLVM.get(3)); - assertEquals("ddd", coordList.get(3)); - assertEquals("eee", this.compositeLVM.get(4)); - assertEquals("eee", coordList.get(4)); - - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testIterator() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - assertEquals("aaa", this.compositeLVM.iterator().next()); - assertEquals("aaa", coordList.iterator().next()); - Iterator<String> stream1 = coordList.iterator(); - for (Iterator<String> stream2 = this.compositeLVM.iterator(); stream2.hasNext(); ) { - assertEquals(stream1.next(), stream2.next()); - } - assertFalse(stream1.hasNext()); - } - - public void testSize() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - assertEquals(11, this.compositeLVM.size()); - assertEquals(11, coordList.size()); - } - - public void testToArray() { - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - } - - public void testHasListeners() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - assertTrue(this.compositeLVM.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.lvm0.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.compositeLVM.removeListChangeListener(ListValueModel.LIST_VALUES, coordList); - assertFalse(this.compositeLVM.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.lvm0.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, coordList); - assertTrue(this.compositeLVM.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.lvm0.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - public void testAddSource_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - LocalListValueModel<String> lvm = new LocalListValueModel<String>(); - lvm.add("xxx"); - lvm.add("yyy"); - lvm.add("zzz"); - this.uberLVM.add(0, lvm); - - Object[] expected = new Object[] { "xxx", "yyy", "zzz", "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(9)); - assertEquals("ggg", coordList.get(9)); - } - - public void testAddSource_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - LocalListValueModel<String> lvm = new LocalListValueModel<String>(); - lvm.add("xxx"); - lvm.add("yyy"); - lvm.add("zzz"); - this.uberLVM.add(2, lvm); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "xxx", "yyy", "zzz", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(9)); - assertEquals("ggg", coordList.get(9)); - } - - public void testAddSource_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - LocalListValueModel<String> lvm = new LocalListValueModel<String>(); - lvm.add("xxx"); - lvm.add("yyy"); - lvm.add("zzz"); - this.uberLVM.add(lvm); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "xxx", "yyy", "zzz" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testAddSources() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - LocalListValueModel<String> lvmA = new LocalListValueModel<String>(); - lvmA.add("xxx"); - lvmA.add("yyy"); - lvmA.add("zzz"); - LocalListValueModel<String> lvmB = new LocalListValueModel<String>(); - lvmB.add("ppp"); - lvmB.add("qqq"); - lvmB.add("rrr"); - Collection<LocalListValueModel<String>> c = new ArrayList<LocalListValueModel<String>>(); - c.add(lvmA); - c.add(lvmB); - this.uberLVM.addAll(2, c); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "xxx", "yyy", "zzz", "ppp", "qqq", "rrr", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(12)); - assertEquals("ggg", coordList.get(12)); - } - - public void testRemoveSource_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.remove(0); - - Object[] expected = new Object[] { "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(3)); - assertEquals("ggg", coordList.get(3)); - } - - public void testRemoveSource_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.remove(2); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(5)); - assertEquals("ggg", coordList.get(5)); - } - - public void testRemoveSource_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.remove(3); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - public void testRemoveSources() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.remove(2, 2); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("eee", this.compositeLVM.get(4)); - assertEquals("eee", coordList.get(4)); - } - - public void testReplaceSources() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - LocalListValueModel<String> lvmA = new LocalListValueModel<String>(); - lvmA.add("xxx"); - lvmA.add("yyy"); - lvmA.add("zzz"); - LocalListValueModel<String> lvmB = new LocalListValueModel<String>(); - lvmB.add("ppp"); - lvmB.add("qqq"); - lvmB.add("rrr"); - List<LocalListValueModel<String>> list = new ArrayList<LocalListValueModel<String>>(); - list.add(lvmA); - list.add(lvmB); - this.uberLVM.set(2, list); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "xxx", "yyy", "zzz", "ppp", "qqq", "rrr" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("qqq", this.compositeLVM.get(9)); - assertEquals("qqq", coordList.get(9)); - } - - public void testMoveSources_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.move(0, 2, 2); - - Object[] expected = new Object[] { "fff", "ggg", "hhh", "iii", "jjj", "kkk", "aaa", "bbb", "ccc", "ddd", "eee" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(1)); - assertEquals("ggg", coordList.get(1)); - } - - public void testMoveSources_Middle() { - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - this.uberLVM.add(lvm4); - - LocalListValueModel<String> lvm5 = new LocalListValueModel<String>(); - lvm5.add("nnn"); - lvm5.add("ooo"); - lvm5.add("ppp"); - lvm5.add("qqq"); - this.uberLVM.add(lvm5); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.move(1, 3, 2); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk", "lll", "mmm", "ddd", "eee", "fff", "nnn", "ooo", "ppp", "qqq" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(3)); - assertEquals("ggg", coordList.get(3)); - } - - public void testMoveSources_End() { - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - this.uberLVM.add(lvm4); - - LocalListValueModel<String> lvm5 = new LocalListValueModel<String>(); - lvm5.add("nnn"); - lvm5.add("ooo"); - lvm5.add("ppp"); - lvm5.add("qqq"); - this.uberLVM.add(lvm5); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.move(3, 0, 3); - - Object[] expected = new Object[] { "ggg", "hhh", "iii", "jjj", "kkk", "lll", "mmm", "nnn", "ooo", "ppp", "qqq", "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(0)); - assertEquals("ggg", coordList.get(0)); - } - - public void testMoveSource() { - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - this.uberLVM.add(lvm4); - - LocalListValueModel<String> lvm5 = new LocalListValueModel<String>(); - lvm5.add("nnn"); - lvm5.add("ooo"); - lvm5.add("ppp"); - lvm5.add("qqq"); - this.uberLVM.add(lvm5); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.move(3, 1); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "ddd", "eee", "lll", "mmm", "nnn", "ooo", "ppp", "qqq" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ooo", this.compositeLVM.get(14)); - assertEquals("ooo", coordList.get(14)); - } - - public void testClearSources() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.clear(); - - Object[] expected = new Object[0]; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - } - - public void testChangeSources1() { - List<LocalListValueModel<String>> newList = new ArrayList<LocalListValueModel<String>>(); - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - newList.add(lvm4); - - LocalListValueModel<String> lvm5 = new LocalListValueModel<String>(); - lvm5.add("nnn"); - lvm5.add("ooo"); - lvm5.add("ppp"); - lvm5.add("qqq"); - newList.add(lvm5); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.setListValues(newList); - - Object[] expected = new Object[] { "lll", "mmm", "nnn", "ooo", "ppp", "qqq" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ooo", this.compositeLVM.get(3)); - assertEquals("ooo", coordList.get(3)); - } - - public void testChangeSources2() { - List<LocalListValueModel<String>> newList = new ArrayList<LocalListValueModel<String>>(); - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - newList.add(lvm4); - - LocalListValueModel<String> lvm5 = new LocalListValueModel<String>(); - lvm5.add("nnn"); - lvm5.add("ooo"); - lvm5.add("ppp"); - lvm5.add("qqq"); - newList.add(lvm5); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.changeListValues(newList); - - Object[] expected = new Object[] { "lll", "mmm", "nnn", "ooo", "ppp", "qqq" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ooo", this.compositeLVM.get(3)); - assertEquals("ooo", coordList.get(3)); - } - - public void testChangeSources3() { - ListChangeListener listener = new ErrorListener(); - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - - List<LocalListValueModel<String>> newList = new ArrayList<LocalListValueModel<String>>(); - newList.add(this.lvm0); - newList.add(this.lvm1); - newList.add(this.lvm2); - newList.add(this.lvm3); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.changeListValues(newList); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ddd", this.compositeLVM.get(3)); - assertEquals("ddd", coordList.get(3)); - } - - public void testChangeSources4() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsAdded(ListAddEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - - List<LocalListValueModel<String>> newList = new ArrayList<LocalListValueModel<String>>(); - newList.add(this.lvm0); - newList.add(this.lvm1); - newList.add(this.lvm2); - newList.add(this.lvm3); - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - newList.add(lvm4); - - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.changeListValues(newList); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "lll", "mmm" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ddd", this.compositeLVM.get(3)); - assertEquals("ddd", coordList.get(3)); - } - - public void testChangeSources5() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsRemoved(ListRemoveEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - - List<LocalListValueModel<String>> newList = new ArrayList<LocalListValueModel<String>>(); - newList.add(this.lvm0); - newList.add(this.lvm1); - newList.add(this.lvm2); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.changeListValues(newList); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ddd", this.compositeLVM.get(3)); - assertEquals("ddd", coordList.get(3)); - } - - public void testChangeSources6() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsAdded(ListAddEvent event) { /* OK */ } - @Override - public void itemsRemoved(ListRemoveEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - - List<LocalListValueModel<String>> newList = new ArrayList<LocalListValueModel<String>>(); - newList.add(this.lvm0); - newList.add(this.lvm1); - - LocalListValueModel<String> lvm4 = new LocalListValueModel<String>(); - lvm4.add("lll"); - lvm4.add("mmm"); - newList.add(lvm4); - - newList.add(this.lvm3); - - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.uberLVM.changeListValues(newList); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "lll", "mmm", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ddd", this.compositeLVM.get(3)); - assertEquals("ddd", coordList.get(3)); - } - - public void testAddItem_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.add(0, "xxx"); - - Object[] expected = new Object[] { "xxx", "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(7)); - assertEquals("ggg", coordList.get(7)); - } - - public void testAddItem_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm2.add(1, "xxx"); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "xxx", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(7)); - assertEquals("ggg", coordList.get(7)); - } - - public void testAddItem_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.add(5, "xxx"); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "xxx" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testAddItems_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.addAll(0, Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "xxx", "yyy", "zzz", "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(9)); - assertEquals("ggg", coordList.get(9)); - } - - public void testAddItems_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm2.addAll(1, Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "xxx", "yyy", "zzz", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(9)); - assertEquals("ggg", coordList.get(9)); - } - - public void testAddItems_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.addAll(5, Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "xxx", "yyy", "zzz" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testRemoveItem_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.remove(0); - - Object[] expected = new Object[] { "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(5)); - assertEquals("ggg", coordList.get(5)); - } - - public void testRemoveItem_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm2.remove(0); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(5)); - assertEquals("ggg", coordList.get(5)); - } - - public void testRemoveItem_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.remove(4); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testRemoveItems_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.remove(0, 3); - - Object[] expected = new Object[] { "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(3)); - assertEquals("ggg", coordList.get(3)); - } - - public void testRemoveItems_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.remove(1, 3); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("kkk", this.compositeLVM.get(7)); - assertEquals("kkk", coordList.get(7)); - } - - public void testRemoveItems_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.remove(3, 2); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testReplaceItem_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.set(0, "xxx"); - - Object[] expected = new Object[] { "xxx", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testReplaceItem_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm2.set(0, "xxx"); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "xxx", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testReplaceItem_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.set(4, "xxx"); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "xxx" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testReplaceItems_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.set(0, Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "xxx", "yyy", "zzz", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testReplaceItems_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.set(1, Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "xxx", "yyy", "zzz", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("kkk", this.compositeLVM.get(10)); - assertEquals("kkk", coordList.get(10)); - } - - public void testReplaceItems_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.set(3, Arrays.asList(new String[] { "xxx", "yyy" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "xxx", "yyy" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testMoveItem_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.move(2, 0); - - Object[] expected = new Object[] { "bbb", "ccc", "aaa", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testMoveItem_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.move(0, 1); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "eee", "ddd", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testMoveItem_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.move(0, 4); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "kkk", "ggg", "hhh", "iii", "jjj" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(7)); - assertEquals("ggg", coordList.get(7)); - } - - public void testMoveItems_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.move(1, 0, 2); - - Object[] expected = new Object[] { "ccc", "aaa", "bbb", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testMoveItems_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.add("eee.1"); - this.lvm1.add("eee.2"); - this.lvm1.add("eee.3"); - this.lvm1.move(1, 2, 3); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee.1", "eee.2", "eee.3", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(9)); - assertEquals("ggg", coordList.get(9)); - } - - public void testMoveItems_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.move(0, 2, 3); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "iii", "jjj", "kkk", "ggg", "hhh" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(9)); - assertEquals("ggg", coordList.get(9)); - } - - public void testClearItems_Begin() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.clear(); - - Object[] expected = new Object[] { "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(3)); - assertEquals("ggg", coordList.get(3)); - } - - public void testClearItems_Middle() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.clear(); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(4)); - assertEquals("ggg", coordList.get(4)); - } - - public void testClearItems_End() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.clear(); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - public void testChangeItems_Begin1() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.setListValues(Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "xxx", "yyy", "zzz", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testChangeItems_Middle1() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.setListValues(Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "xxx", "yyy", "zzz", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(7)); - assertEquals("ggg", coordList.get(7)); - } - - public void testChangeItems_End1() { - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.setListValues(Arrays.asList(new String[] { "xxx", "yyy", "zzz" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "xxx", "yyy", "zzz" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - public void testChangeItems_Begin2() { - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, new ErrorListener()); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.changeListValues(Arrays.asList(new String[] { "aaa", "bbb", "ccc" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testChangeItems_Middle2() { - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, new ErrorListener()); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.changeListValues(Arrays.asList(new String[] { "ddd", "eee" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("hhh", this.compositeLVM.get(7)); - assertEquals("hhh", coordList.get(7)); - } - - public void testChangeItems_End2() { - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, new ErrorListener()); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.changeListValues(Arrays.asList(new String[] { "ggg", "hhh", "iii", "jjj", "kkk" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - public void testChangeItems_Begin3() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsReplaced(ListReplaceEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.changeListValues(Arrays.asList(new String[] { "aaa", "bbb", "xxx" })); - - Object[] expected = new Object[] { "aaa", "bbb", "xxx", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(6)); - assertEquals("ggg", coordList.get(6)); - } - - public void testChangeItems_Middle3() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsReplaced(ListReplaceEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.changeListValues(Arrays.asList(new String[] { "ddd", "xxx" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "xxx", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("hhh", this.compositeLVM.get(7)); - assertEquals("hhh", coordList.get(7)); - } - - public void testChangeItems_End3() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsReplaced(ListReplaceEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.changeListValues(Arrays.asList(new String[] { "ggg", "hhh", "iii", "xxx", "kkk" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "xxx", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - public void testChangeItems_Begin4() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsAdded(ListAddEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.changeListValues(Arrays.asList(new String[] { "aaa", "bbb", "ccc", "xxx" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "xxx", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(6)); - assertEquals("fff", coordList.get(6)); - } - - public void testChangeItems_Middle4() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsAdded(ListAddEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.changeListValues(Arrays.asList(new String[] { "ddd", "eee", "xxx" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "xxx", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("ggg", this.compositeLVM.get(7)); - assertEquals("ggg", coordList.get(7)); - } - - public void testChangeItems_End4() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsAdded(ListAddEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.changeListValues(Arrays.asList(new String[] { "ggg", "hhh", "iii", "jjj", "kkk", "xxx" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "xxx" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - public void testChangeItems_Begin5() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsRemoved(ListRemoveEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm0.changeListValues(Arrays.asList(new String[] { "aaa" })); - - Object[] expected = new Object[] { "aaa", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("iii", this.compositeLVM.get(6)); - assertEquals("iii", coordList.get(6)); - } - - public void testChangeItems_Middle5() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsRemoved(ListRemoveEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm1.changeListValues(Arrays.asList(new String[] { "ddd" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "fff", "ggg", "hhh", "iii", "jjj", "kkk" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("iii", this.compositeLVM.get(7)); - assertEquals("iii", coordList.get(7)); - } - - public void testChangeItems_End5() { - ListChangeListener listener = new ErrorListener() { - @Override - public void itemsRemoved(ListRemoveEvent event) { /* OK */ } - }; - this.compositeLVM.addListChangeListener(ListValueModel.LIST_VALUES, listener); - CoordinatedList<String> coordList = new CoordinatedList<String>(this.compositeLVM); - - this.lvm3.changeListValues(Arrays.asList(new String[] { "ggg", "hhh", "iii" })); - - Object[] expected = new Object[] { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii" }; - assertEquals(expected.length, this.compositeLVM.size()); - assertEquals(expected.length, coordList.size()); - assertTrue(Arrays.equals(expected, this.compositeLVM.toArray())); - assertTrue(Arrays.equals(expected, coordList.toArray())); - assertEquals("fff", this.compositeLVM.get(5)); - assertEquals("fff", coordList.get(5)); - } - - class ErrorListener implements ListChangeListener { - public void itemsAdded(ListAddEvent event) { - fail(); - } - public void itemsRemoved(ListRemoveEvent event) { - fail(); - } - public void itemsMoved(ListMoveEvent event) { - fail(); - } - public void itemsReplaced(ListReplaceEvent event) { - fail(); - } - public void listCleared(ListClearEvent event) { - fail(); - } - public void listChanged(ListChangeEvent event) { - fail(); - } - } - - class LocalListValueModel<E> extends SimpleListValueModel<E> { - LocalListValueModel() { - super(); - } - void changeListValues(Iterable<E> listValues) { - if (listValues == null) { - throw new NullPointerException(); - } - this.list.clear(); - CollectionTools.addAll(this.list, listValues); - this.fireListChanged(LIST_VALUES, this.list); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositePropertyValueModelTests.java deleted file mode 100644 index 229cbfede5..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CompositePropertyValueModelTests.java +++ /dev/null @@ -1,193 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.value.CompositePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class CompositePropertyValueModelTests extends TestCase { - private SimplePropertyValueModel<Integer> pvm1; - private ModifiablePropertyValueModel<Integer> pvm2; - private ModifiablePropertyValueModel<Integer> pvm3; - private ModifiablePropertyValueModel<Integer> pvm4; - private Collection<ModifiablePropertyValueModel<Integer>> collection; - private SimpleCollectionValueModel<ModifiablePropertyValueModel<Integer>> cvm; - private PropertyValueModel<Integer> compositePVM; - PropertyChangeEvent event; - - - public CompositePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.pvm1 = new SimplePropertyValueModel<Integer>(Integer.valueOf(1)); - this.pvm2 = new SimplePropertyValueModel<Integer>(Integer.valueOf(2)); - this.pvm3 = new SimplePropertyValueModel<Integer>(Integer.valueOf(3)); - this.pvm4 = new SimplePropertyValueModel<Integer>(Integer.valueOf(4)); - this.collection = new ArrayList<ModifiablePropertyValueModel<Integer>>(); - this.collection.add(this.pvm1); - this.collection.add(this.pvm2); - this.collection.add(this.pvm3); - this.collection.add(this.pvm4); - this.cvm = new SimpleCollectionValueModel<ModifiablePropertyValueModel<Integer>>(this.collection); - - this.compositePVM = this.buildCompositePVM(cvm); - } - - private <T extends PropertyValueModel<Integer>> PropertyValueModel<Integer> buildCompositePVM(CollectionValueModel<T> pvms) { - return new CompositePropertyValueModel<Integer, Integer>(pvms) { - @Override - protected Integer buildValue() { - int sum = 0; - for (PropertyValueModel<? extends Integer> each : this.collectionModel) { - sum += each.getValue().intValue(); - } - return Integer.valueOf(sum); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetValue() { - assertNull(this.compositePVM.getValue()); - ChangeListener listener = this.buildListener(); - this.compositePVM.addChangeListener(listener); - assertEquals(10, this.compositePVM.getValue().intValue()); - } - - public void testValueAndListeners1() { - assertNull(this.compositePVM.getValue()); - ChangeListener listener = this.buildListener(); - this.compositePVM.addChangeListener(listener); - assertEquals(10, this.compositePVM.getValue().intValue()); - this.compositePVM.removeChangeListener(listener); - assertNull(this.compositePVM.getValue()); - } - - public void testValueAndListeners2() { - assertNull(this.compositePVM.getValue()); - ChangeListener listener = this.buildListener(); - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertEquals(10, this.compositePVM.getValue().intValue()); - this.compositePVM.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertNull(this.compositePVM.getValue()); - } - - public void testPropertyChange1() { - this.compositePVM.addChangeListener(this.buildListener()); - this.verifyPropertyChange(); - } - - public void testPropertyChange2() { - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.verifyPropertyChange(); - } - - private void verifyPropertyChange() { - this.event = null; - this.pvm1.setValue(Integer.valueOf(5)); - this.verifyEvent(10, 14); - - this.event = null; - this.pvm4.setValue(Integer.valueOf(0)); - this.verifyEvent(14, 10); - } - - public void testCollectionChange1() { - this.compositePVM.addChangeListener(this.buildListener()); - this.verifyCollectionChange(); - } - - public void testCollectionChange2() { - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.verifyCollectionChange(); - } - - private void verifyCollectionChange() { - this.event = null; - ModifiablePropertyValueModel<Integer> pvm = new SimplePropertyValueModel<Integer>(Integer.valueOf(77)); - this.cvm.add(pvm); - this.verifyEvent(10, 87); - - this.event = null; - this.cvm.remove(pvm); - this.verifyEvent(87, 10); - - this.event = null; - this.cvm.clear(); - this.verifyEvent(10, 0); - - Collection<ModifiablePropertyValueModel<Integer>> c2 = new ArrayList<ModifiablePropertyValueModel<Integer>>(); - c2.add(this.pvm1); - c2.add(this.pvm2); - this.event = null; - this.cvm.setValues(c2); - this.verifyEvent(0, 3); - } - - public void testLazyListening1() { - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildListener(); - - this.compositePVM.addChangeListener(listener); - assertTrue(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.compositePVM.removeChangeListener(listener); - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testLazyListening2() { - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildListener(); - - this.compositePVM.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.compositePVM.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertFalse(this.pvm1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - CompositePropertyValueModelTests.this.event = e; - } - }; - } - - private void verifyEvent(int oldValue, int newValue) { - assertEquals(this.compositePVM, this.event.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event.getPropertyName()); - assertEquals(Integer.valueOf(oldValue), this.event.getOldValue()); - assertEquals(Integer.valueOf(newValue), this.event.getNewValue()); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CoordinatedBag.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CoordinatedBag.java deleted file mode 100644 index 508a4d62f4..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CoordinatedBag.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; -import java.util.Iterator; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; - -/** - * Helper class that keeps an internal collection in synch with the - * collection held by a collection value model. - */ -class CoordinatedBag<E> implements Bag<E>, CollectionChangeListener { - - private Bag<E> bag = new HashBag<E>(); - - CoordinatedBag(CollectionValueModel<E> cvm) { - cvm.addCollectionChangeListener(CollectionValueModel.VALUES, this); - } - - - // ********** Collection implementation ********** - - public boolean add(E o) { - return this.bag.add(o); - } - - public boolean addAll(Collection<? extends E> c) { - return this.bag.addAll(c); - } - - public void clear() { - this.bag.clear(); - } - - public boolean contains(Object o) { - return this.bag.contains(o); - } - - public boolean containsAll(Collection<?> c) { - return this.bag.containsAll(c); - } - - public boolean isEmpty() { - return this.bag.isEmpty(); - } - - public Iterator<E> iterator() { - return this.bag.iterator(); - } - - public boolean remove(Object o) { - return this.bag.remove(o); - } - - public boolean removeAll(Collection<?> c) { - return this.bag.removeAll(c); - } - - public boolean retainAll(Collection<?> c) { - return this.bag.retainAll(c); - } - - public int size() { - return this.bag.size(); - } - - public Object[] toArray() { - return this.bag.toArray(); - } - - public <T> T[] toArray(T[] a) { - return this.bag.toArray(a); - } - - - // ********** Bag implementation ********** - - public int count(Object o) { - return this.bag.count(o); - } - - public boolean add(E o, int count) { - return this.bag.add(o, count); - } - - public boolean remove(Object o, int count) { - return this.bag.remove(o, count); - } - - public Iterator<E> uniqueIterator() { - return this.bag.uniqueIterator(); - } - - public int uniqueCount() { - return this.bag.uniqueCount(); - } - - public Iterator<Bag.Entry<E>> entries() { - return this.bag.entries(); - } - - // ********** CollectionChangeListener implementation ********** - - @SuppressWarnings("unchecked") - public void itemsAdded(CollectionAddEvent event) { - for (E item : (Iterable<E>) event.getItems()) { - this.bag.add(item); - } - } - - @SuppressWarnings("unchecked") - public void itemsRemoved(CollectionRemoveEvent event) { - for (E item : (Iterable<E>) event.getItems()) { - this.bag.remove(item); - } - } - - public void collectionCleared(CollectionClearEvent event) { - this.bag.clear(); - } - - @SuppressWarnings("unchecked") - public void collectionChanged(CollectionChangeEvent event) { - this.bag.clear(); - CollectionTools.addAll(this.bag, ((CollectionValueModel<E>) event.getSource()).iterator()); - } - - - // ********** standard methods ********** - - @Override - public boolean equals(Object o) { - return this.bag.equals(o); - } - - @Override - public int hashCode() { - return this.bag.hashCode(); - } - - @Override - public String toString() { - return this.bag.toString(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CoordinatedList.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CoordinatedList.java deleted file mode 100644 index 95cf02457b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/CoordinatedList.java +++ /dev/null @@ -1,264 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import javax.swing.ListModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; - -/** - * Helper class that keeps an internal list in synch with the - * list held by a list value model. - */ -public class CoordinatedList<E> implements List<E>, ListChangeListener, ListDataListener { - private List<E> list = new ArrayList<E>(); - - public CoordinatedList(ListValueModel<E> listValueModel) { - listValueModel.addListChangeListener(ListValueModel.LIST_VALUES, this); - for (Iterator<E> stream = listValueModel.iterator(); stream.hasNext(); ) { - this.add(stream.next()); - } - } - - public CoordinatedList(ListModel listModel) { - listModel.addListDataListener(this); - for (int i = 0; i < listModel.getSize(); i++) { - this.add(i, this.getElementAt(listModel, i)); - } - } - - - // ********** List implementation ********** - - public void add(int index, E element) { - this.list.add(index, element); - } - - public boolean add(E o) { - return this.list.add(o); - } - - public boolean addAll(Collection<? extends E> c) { - return this.list.addAll(c); - } - - public boolean addAll(int index, Collection<? extends E> c) { - return this.list.addAll(index, c); - } - - public void clear() { - this.list.clear(); - } - - public boolean contains(Object o) { - return this.list.contains(o); - } - - public boolean containsAll(Collection<?> c) { - return this.list.containsAll(c); - } - - public E get(int index) { - return this.list.get(index); - } - - public int indexOf(Object o) { - return this.list.indexOf(o); - } - - public boolean isEmpty() { - return this.list.isEmpty(); - } - - public Iterator<E> iterator() { - return this.list.iterator(); - } - - public int lastIndexOf(Object o) { - return this.list.lastIndexOf(o); - } - - public ListIterator<E> listIterator() { - return this.list.listIterator(); - } - - public ListIterator<E> listIterator(int index) { - return this.list.listIterator(index); - } - - public E remove(int index) { - return this.list.remove(index); - } - - public boolean remove(Object o) { - return this.list.remove(o); - } - - public boolean removeAll(Collection<?> c) { - return this.list.removeAll(c); - } - - public boolean retainAll(Collection<?> c) { - return this.list.retainAll(c); - } - - public E set(int index, E element) { - return this.list.set(index, element); - } - - public int size() { - return this.list.size(); - } - - public List<E> subList(int fromIndex, int toIndex) { - return this.list.subList(fromIndex, toIndex); - } - - public Object[] toArray() { - return this.list.toArray(); - } - - public <T> T[] toArray(T[] a) { - return this.list.toArray(a); - } - - - // ********** ListChangeListener implementation ********** - - public void itemsAdded(ListAddEvent e) { - int i = e.getIndex(); - for (E item : this.getItems(e)) { - this.list.add(i++, item); - } - } - - public void itemsRemoved(ListRemoveEvent e) { - int base = e.getIndex(); - for (int i = e.getItemsSize(); i-- > 0; ) { - this.list.remove(base + i); // remove from end - } - } - - public void itemsReplaced(ListReplaceEvent e) { - int i = e.getIndex(); - for (E item : this.getNewItems(e)) { - this.list.set(i++, item); - } - } - - public void itemsMoved(ListMoveEvent e) { - CollectionTools.move(this.list, e.getTargetIndex(), e.getSourceIndex(), e.getLength()); - } - - public void listCleared(ListClearEvent e) { - this.list.clear(); - } - - public void listChanged(ListChangeEvent e) { - this.list.clear(); - CollectionTools.addAll(this.list, this.getSource(e).iterator()); - } - - - // ********** ListDataListener implementation ********** - - public void contentsChanged(ListDataEvent e) { - this.list.clear(); - ListModel lm = (ListModel) e.getSource(); - int size = lm.getSize(); - for (int i = 0; i < size; i++) { - this.list.add(i, this.getElementAt(lm, i)); - } - } - - public void intervalAdded(ListDataEvent e) { - ListModel lm = (ListModel) e.getSource(); - int start = Math.min(e.getIndex0(), e.getIndex1()); - int end = Math.max(e.getIndex0(), e.getIndex1()); - for (int i = start; i <= end; i++) { - this.list.add(i, this.getElementAt(lm, i)); - } - } - - public void intervalRemoved(ListDataEvent e) { - int start = Math.min(e.getIndex0(), e.getIndex1()); - int end = Math.max(e.getIndex0(), e.getIndex1()); - int length = end - start + 1; - for (int i = 1; i <= length; i++) { - this.list.remove(start); - } - } - - - // ********** standard methods ********** - - @Override - public boolean equals(Object o) { - return this.list.equals(o); - } - - @Override - public int hashCode() { - return this.list.hashCode(); - } - - @Override - public String toString() { - return this.list.toString(); - } - - - // ********** internal methods ********** - - /** - * minimize the scope of the suppressed warnings.= - */ - @SuppressWarnings("unchecked") - private E getElementAt(ListModel listModel, int index) { - return (E) listModel.getElementAt(index); - } - - // minimized scope of suppressed warnings - @SuppressWarnings("unchecked") - private Iterable<E> getItems(ListAddEvent event) { - return (Iterable<E>) event.getItems(); - } - - // minimized scope of suppressed warnings - @SuppressWarnings("unchecked") - private Iterable<E> getNewItems(ListReplaceEvent event) { - return (Iterable<E>) event.getNewItems(); - } - - /** - * minimize the scope of the suppressed warnings.= - */ - @SuppressWarnings("unchecked") - private ListValueModel<E> getSource(ListChangeEvent event) { - return (ListValueModel<E>) event.getSource(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/DoubleModifiablePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/DoubleModifiablePropertyValueModelTests.java deleted file mode 100644 index d12aae8f8c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/DoubleModifiablePropertyValueModelTests.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import org.eclipse.jpt.common.utility.internal.model.value.DoubleModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -@SuppressWarnings("nls") -public class DoubleModifiablePropertyValueModelTests - extends DoublePropertyValueModelTests -{ - public DoubleModifiablePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected PropertyValueModel<String> buildDoubleModel() { - return new DoubleModifiablePropertyValueModel<String>(this.stringModelModel); - } - - protected ModifiablePropertyValueModel<String> getDoubleModel() { - return (ModifiablePropertyValueModel<String>) this.doubleModel; - } - - public void testSetValue() { - assertEquals("foo", this.stringModel.getValue()); - assertEquals(this.stringModel, this.stringModelModel.getValue()); - assertNull(this.doubleModel.getValue()); - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - assertEquals("foo", this.doubleModel.getValue()); - - this.getDoubleModel().setValue("bar"); - assertEquals("bar", this.stringModel.getValue()); - assertEquals("bar", this.doubleModel.getValue()); - - this.stringModelModel.setValue(null); - assertNull(this.doubleModel.getValue()); - this.getDoubleModel().setValue("TTT"); // NOP? - assertEquals("bar", this.stringModel.getValue()); - assertNull(this.doubleModel.getValue()); - } - - public void testPropertyChange3() { - this.stringModel.addChangeListener(this.stringModelListener); - this.stringModelModel.addChangeListener(this.stringModelModelListener); - this.doubleModel.addChangeListener(this.doubleModelListener); - this.verifyPropertyChanges2(); - } - - public void testPropertyChange4() { - this.stringModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.stringModelListener); - this.stringModelModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.stringModelModelListener); - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - this.verifyPropertyChanges2(); - } - - protected void verifyPropertyChanges2() { - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.getDoubleModel().setValue("bar"); - this.verifyEvent(this.stringModelEvent, this.stringModel, "foo", "bar"); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "foo", "bar"); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.getDoubleModel().setValue(null); - this.verifyEvent(this.stringModelEvent, this.stringModel, "bar", null); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "bar", null); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.getDoubleModel().setValue("foo"); - this.verifyEvent(this.stringModelEvent, this.stringModel, null, "foo"); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, null, "foo"); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - ModifiablePropertyValueModel<String> stringModel2 = new SimplePropertyValueModel<String>("TTT"); - this.stringModelModel.setValue(stringModel2); - assertNull(this.stringModelEvent); - this.verifyEvent(this.stringModelModelEvent, this.stringModelModel, this.stringModel, stringModel2); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "foo", "TTT"); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.getDoubleModel().setValue("XXX"); - assertNull(this.stringModelEvent); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "TTT", "XXX"); - assertEquals("foo", this.stringModel.getValue()); - assertEquals("XXX", stringModel2.getValue()); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.stringModelModel.setValue(this.stringModel); - assertNull(this.stringModelEvent); - this.verifyEvent(this.stringModelModelEvent, this.stringModelModel, stringModel2, this.stringModel); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "XXX", "foo"); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/DoublePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/DoublePropertyValueModelTests.java deleted file mode 100644 index e9cf6ae65b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/DoublePropertyValueModelTests.java +++ /dev/null @@ -1,223 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.DoublePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class DoublePropertyValueModelTests - extends TestCase -{ - protected ModifiablePropertyValueModel<String> stringModel; - protected ChangeListener stringModelListener; - protected PropertyChangeEvent stringModelEvent; - - protected ModifiablePropertyValueModel<ModifiablePropertyValueModel<String>> stringModelModel; - protected ChangeListener stringModelModelListener; - protected PropertyChangeEvent stringModelModelEvent; - - protected PropertyValueModel<String> doubleModel; - protected ChangeListener doubleModelListener; - protected PropertyChangeEvent doubleModelEvent; - - public DoublePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.stringModel = new SimplePropertyValueModel<String>("foo"); - this.stringModelListener = new StringModelListener(); - - this.stringModelModel = new SimplePropertyValueModel<ModifiablePropertyValueModel<String>>(stringModel); - this.stringModelModelListener = new StringModelModelListener(); - - this.doubleModel = this.buildDoubleModel(); - this.doubleModelListener = new DoubleModelListener(); - } - - protected PropertyValueModel<String> buildDoubleModel() { - return new DoublePropertyValueModel<String>(this.stringModelModel); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetValue1() { - assertEquals("foo", this.stringModel.getValue()); - assertEquals(this.stringModel, this.stringModelModel.getValue()); - assertNull(this.doubleModel.getValue()); - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - assertEquals("foo", this.doubleModel.getValue()); - - this.stringModel.setValue("bar"); - assertEquals("bar", this.stringModel.getValue()); - assertEquals("bar", this.doubleModel.getValue()); - - this.stringModel.setValue("baz"); - assertEquals("baz", this.stringModel.getValue()); - assertEquals("baz", this.doubleModel.getValue()); - - this.stringModel.setValue(null); - assertNull(this.stringModel.getValue()); - assertNull(this.doubleModel.getValue()); - - this.stringModel.setValue("foo"); - assertEquals("foo", this.stringModel.getValue()); - assertEquals("foo", this.doubleModel.getValue()); - } - - public void testGetValue2() { - assertNull(this.doubleModel.getValue()); - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - assertEquals("foo", this.doubleModel.getValue()); - - this.stringModelModel.setValue(null); - assertNull(this.doubleModel.getValue()); - - ModifiablePropertyValueModel<String> stringModel2 = new SimplePropertyValueModel<String>("TTT"); - this.stringModelModel.setValue(stringModel2); - assertEquals("TTT", this.doubleModel.getValue()); - - this.stringModelModel.setValue(this.stringModel); - assertEquals("foo", this.doubleModel.getValue()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.stringModel).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.stringModelModel).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - this.doubleModel.addChangeListener(this.doubleModelListener); - assertTrue(((AbstractModel) this.stringModel).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.stringModelModel).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.doubleModel.removeChangeListener(this.doubleModelListener); - assertTrue(((AbstractModel) this.stringModel).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) this.stringModelModel).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - assertTrue(((AbstractModel) this.stringModel).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.doubleModel.removePropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - assertTrue(((AbstractModel) this.stringModel).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - ModifiablePropertyValueModel<String> stringModel2 = new SimplePropertyValueModel<String>("TTT"); - assertTrue(((AbstractModel) this.stringModel).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) stringModel2).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - this.stringModelModel.setValue(stringModel2); - assertTrue(((AbstractModel) this.stringModel).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) stringModel2).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.stringModelModel.setValue(this.stringModel); - assertTrue(((AbstractModel) this.stringModel).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(((AbstractModel) stringModel2).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testPropertyChange1() { - this.stringModel.addChangeListener(this.stringModelListener); - this.stringModelModel.addChangeListener(this.stringModelModelListener); - this.doubleModel.addChangeListener(this.doubleModelListener); - this.verifyPropertyChanges1(); - } - - public void testPropertyChange2() { - this.stringModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.stringModelListener); - this.stringModelModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.stringModelModelListener); - this.doubleModel.addPropertyChangeListener(PropertyValueModel.VALUE, this.doubleModelListener); - this.verifyPropertyChanges1(); - } - - protected void verifyPropertyChanges1() { - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.stringModel.setValue("bar"); - this.verifyEvent(this.stringModelEvent, this.stringModel, "foo", "bar"); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "foo", "bar"); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.stringModel.setValue(null); - this.verifyEvent(this.stringModelEvent, this.stringModel, "bar", null); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "bar", null); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.stringModel.setValue("foo"); - this.verifyEvent(this.stringModelEvent, this.stringModel, null, "foo"); - assertNull(this.stringModelModelEvent); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, null, "foo"); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - ModifiablePropertyValueModel<String> stringModel2 = new SimplePropertyValueModel<String>("TTT"); - this.stringModelModel.setValue(stringModel2); - assertNull(this.stringModelEvent); - this.verifyEvent(this.stringModelModelEvent, this.stringModelModel, this.stringModel, stringModel2); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "foo", "TTT"); - - this.stringModelEvent = null; - this.stringModelModelEvent = null; - this.doubleModelEvent = null; - this.stringModelModel.setValue(this.stringModel); - assertNull(this.stringModelEvent); - this.verifyEvent(this.stringModelModelEvent, this.stringModelModel, stringModel2, this.stringModel); - this.verifyEvent(this.doubleModelEvent, this.doubleModel, "TTT", "foo"); - } - - protected void verifyEvent(PropertyChangeEvent event, Object source, Object oldValue, Object newValue) { - assertEquals(source, event.getSource()); - assertEquals(PropertyValueModel.VALUE, event.getPropertyName()); - assertEquals(oldValue, event.getOldValue()); - assertEquals(newValue, event.getNewValue()); - } - - protected class StringModelListener - extends ChangeAdapter - { - @Override - public void propertyChanged(PropertyChangeEvent event) { - DoublePropertyValueModelTests.this.stringModelEvent = event; - } - } - - protected class StringModelModelListener - extends ChangeAdapter - { - @Override - public void propertyChanged(PropertyChangeEvent event) { - DoublePropertyValueModelTests.this.stringModelModelEvent = event; - } - } - - protected class DoubleModelListener - extends ChangeAdapter - { - @Override - public void propertyChanged(PropertyChangeEvent event) { - DoublePropertyValueModelTests.this.doubleModelEvent = event; - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ExtendedListValueModelWrapperTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ExtendedListValueModelWrapperTests.java deleted file mode 100644 index 56e1a25d14..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ExtendedListValueModelWrapperTests.java +++ /dev/null @@ -1,313 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ExtendedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ExtendedListValueModelWrapperTests extends TestCase { - private SimpleListValueModel<String> listHolder; - private ListValueModel<String> extendedListHolder; - ListEvent event; - String eventType; - - private static final String ADD = "add"; - private static final String REMOVE = "remove"; - private static final String REPLACE = "replace"; - private static final String MOVE = "move"; - private static final String CLEAR = "clear"; - private static final String CHANGE = "change"; - - public ExtendedListValueModelWrapperTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.listHolder = new SimpleListValueModel<String>(this.buildList()); - this.extendedListHolder = this.buildExtendedListHolder(this.listHolder); - } - - private List<String> buildList() { - List<String> result = new ArrayList<String>(); - result.add("A"); - result.add("B"); - result.add("C"); - result.add("D"); - return result; - } - - private List<String> buildExtendedList() { - List<String> extendedList = new ArrayList<String>(); - extendedList.addAll(this.buildPrefix()); - extendedList.addAll(this.buildList()); - extendedList.addAll(this.buildSuffix()); - return extendedList; - } - - private List<String> buildPrefix() { - List<String> prefix = new ArrayList<String>(); - prefix.add("x"); - prefix.add("y"); - prefix.add("z"); - return prefix; - } - - private List<String> buildSuffix() { - List<String> suffix = new ArrayList<String>(); - suffix.add("i"); - suffix.add("j"); - return suffix; - } - - private ListValueModel<String> buildExtendedListHolder(ListValueModel<String> lvm) { - return new ExtendedListValueModelWrapper<String>(this.buildPrefix(), lvm, this.buildSuffix()); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - assertEquals(this.buildExtendedList(), CollectionTools.list(this.extendedListHolder.iterator())); - } - - public void testSize() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - assertEquals(this.buildExtendedList().size(), CollectionTools.size(this.extendedListHolder.iterator())); - assertEquals(this.buildExtendedList().size(), this.extendedListHolder.size()); - } - - private boolean extendedListContains(Object item) { - return CollectionTools.contains(this.extendedListHolder.iterator(), item); - } - - private boolean extendedListContainsAll(Collection<String> items) { - return CollectionTools.containsAll(this.extendedListHolder.iterator(), items); - } - - private boolean extendedListContainsAny(Collection<String> items) { - List<String> extendedList = CollectionTools.list(this.extendedListHolder.iterator()); - for (Iterator<String> stream = items.iterator(); stream.hasNext(); ) { - if (extendedList.contains(stream.next())) { - return true; - } - } - return false; - } - - private boolean listContains(Object item) { - return CollectionTools.contains(this.listHolder.iterator(), item); - } - - private boolean listContainsAll(Collection<String> items) { - return CollectionTools.containsAll(this.listHolder.iterator(), items); - } - -// private boolean listContainsAny(Collection<String> items) { -// List<String> extendedList = CollectionTools.list(this.listHolder.iterator()); -// for (Iterator<String> stream = items.iterator(); stream.hasNext(); ) { -// if (extendedList.contains(stream.next())) { -// return true; -// } -// } -// return false; -// } -// - public void testAdd1() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertFalse(this.extendedListContains("E")); - this.listHolder.add(4, "E"); - assertTrue(this.extendedListContains("E")); - assertTrue(this.listContains("E")); - } - - public void testAdd2() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertFalse(this.extendedListContains(null)); - this.listHolder.add(4, null); - assertTrue(this.extendedListContains(null)); - assertTrue(this.listContains(null)); - } - - private List<String> buildAddList() { - List<String> addList = new ArrayList<String>(); - addList.add("E"); - addList.add("F"); - return addList; - } - - public void testAddAll1() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertFalse(this.extendedListContainsAny(this.buildAddList())); - this.listHolder.addAll(4, this.buildAddList()); - assertTrue(this.extendedListContainsAll(this.buildAddList())); - assertTrue(this.listContainsAll(this.buildAddList())); - } - - public void testRemove1() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertTrue(this.extendedListContains("B")); - this.listHolder.remove(this.buildList().indexOf("B")); - assertFalse(this.extendedListContains("B")); - assertFalse(this.listContains("B")); - } - - public void testListChangeGeneric() { - this.extendedListHolder.addChangeListener(this.buildListener()); - this.verifyListChange(); - } - - public void testListChangeNamed() { - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - this.verifyListChange(); - } - - private void verifyListChange() { - this.event = null; - this.eventType = null; - this.listHolder.add(4, "E"); - this.verifyEvent(ADD, 7, "E"); - - this.event = null; - this.eventType = null; - this.listHolder.add(5, null); - this.verifyEvent(ADD, 8, null); - - this.event = null; - this.eventType = null; - this.listHolder.remove(5); - this.verifyEvent(REMOVE, 8, null); - - this.event = null; - this.eventType = null; - this.listHolder.remove(4); - this.verifyEvent(REMOVE, 7, "E"); - - this.event = null; - this.eventType = null; - this.listHolder.addAll(0, this.buildList()); - this.verifyEvent(ADD); - assertEquals(this.buildList(), CollectionTools.list(((ListAddEvent) this.event).getItems())); - - this.event = null; - this.eventType = null; - this.listHolder.set(0, "AA"); - this.verifyEvent(REPLACE); - assertFalse(CollectionTools.contains(((ListReplaceEvent) this.event).getNewItems(), "A")); - assertTrue(CollectionTools.contains(((ListReplaceEvent) this.event).getNewItems(), "AA")); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(ListAddEvent e) { - ExtendedListValueModelWrapperTests.this.eventType = ADD; - ExtendedListValueModelWrapperTests.this.event = e; - } - @Override - public void itemsRemoved(ListRemoveEvent e) { - ExtendedListValueModelWrapperTests.this.eventType = REMOVE; - ExtendedListValueModelWrapperTests.this.event = e; - } - @Override - public void itemsReplaced(ListReplaceEvent e) { - ExtendedListValueModelWrapperTests.this.eventType = REPLACE; - ExtendedListValueModelWrapperTests.this.event = e; - } - @Override - public void itemsMoved(ListMoveEvent e) { - ExtendedListValueModelWrapperTests.this.eventType = MOVE; - ExtendedListValueModelWrapperTests.this.event = e; - } - @Override - public void listCleared(ListClearEvent e) { - ExtendedListValueModelWrapperTests.this.eventType = CLEAR; - ExtendedListValueModelWrapperTests.this.event = e; - } - @Override - public void listChanged(ListChangeEvent e) { - ExtendedListValueModelWrapperTests.this.eventType = CHANGE; - ExtendedListValueModelWrapperTests.this.event = e; - } - }; - } - - private void verifyEvent(String type) { - assertEquals(type, this.eventType); - assertEquals(this.extendedListHolder, this.event.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event.getListName()); - } - - private void verifyEvent(String type, int index, Object item) { - this.verifyEvent(type); - if (type == ADD) { - assertEquals(index, ((ListAddEvent) this.event).getIndex()); - assertEquals(item, ((ListAddEvent) this.event).getItems().iterator().next()); - } else if (type == REMOVE) { - assertEquals(index, ((ListRemoveEvent) this.event).getIndex()); - assertEquals(item, ((ListRemoveEvent) this.event).getItems().iterator().next()); - } - } - - public void testHasListeners() { - /* - * adding listeners to the extended list will cause listeners - * to be added to the wrapped list; - * likewise, removing listeners from the extended list will - * cause listeners to be removed from the wrapped list - */ - assertFalse(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener listener = this.buildListener(); - - this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, listener); - assertTrue(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.extendedListHolder.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - assertFalse(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.extendedListHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.extendedListHolder.removeChangeListener(listener); - assertFalse(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/FilteringCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/FilteringCollectionValueModelTests.java deleted file mode 100644 index df0787fe93..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/FilteringCollectionValueModelTests.java +++ /dev/null @@ -1,348 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Vector; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.Filter; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.FilteringCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class FilteringCollectionValueModelTests extends TestCase { - private SimpleCollectionValueModel<String> collectionHolder; - CollectionAddEvent addEvent; - CollectionRemoveEvent removeEvent; - CollectionClearEvent collectionClearedEvent; - CollectionChangeEvent collectionChangedEvent; - - private CollectionValueModel<String> filteredCollectionHolder; - CollectionAddEvent filteredAddEvent; - CollectionRemoveEvent filteredRemoveEvent; - CollectionClearEvent filteredCollectionClearedEvent; - CollectionChangeEvent filteredCollectionChangedEvent; - - public FilteringCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.collectionHolder = new SimpleCollectionValueModel<String>(buildCollection()); - this.filteredCollectionHolder = new FilteringCollectionValueModel<String>(this.collectionHolder, this.buildFilter()); - } - - private Collection<String> buildCollection() { - Collection<String> collection = new Vector<String>(); - collection.add("foo"); - return collection; - } - - private Filter<String> buildFilter() { - return new Filter<String>() { - public boolean accept(String s) { - return s.startsWith("b"); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - // add a listener to "activate" the wrapper - this.filteredCollectionHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildFilteredListener()); - - assertEquals("foo", this.collectionHolder.iterator().next()); - assertFalse(this.filteredCollectionHolder.iterator().hasNext()); - - this.collectionHolder.add("bar"); - Iterator<String> collectionHolderValue = this.collectionHolder.iterator(); - assertEquals("foo", collectionHolderValue.next()); - assertEquals("bar", collectionHolderValue.next()); - assertTrue(this.filteredCollectionHolder.iterator().hasNext()); - assertEquals("bar", this.filteredCollectionHolder.iterator().next()); - - this.collectionHolder.remove("bar"); - assertEquals("foo", this.collectionHolder.iterator().next()); - assertFalse(this.filteredCollectionHolder.iterator().hasNext()); - - this.collectionHolder.remove("foo"); - assertFalse(this.collectionHolder.iterator().hasNext()); - assertFalse(this.filteredCollectionHolder.iterator().hasNext()); - - this.collectionHolder.add("foo"); - assertEquals("foo", this.collectionHolder.iterator().next()); - assertFalse(this.filteredCollectionHolder.iterator().hasNext()); - } - - public void testSetValue() { - // add a listener to "activate" the wrapper - this.filteredCollectionHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildFilteredListener()); - - Collection<String> newCollection = new Vector<String>(); - newCollection.add("fox"); - newCollection.add("baz"); - - this.collectionHolder.setValues(newCollection); - - Iterator<String> collectionValues = this.collectionHolder.iterator(); - assertEquals("fox", collectionValues.next()); - assertEquals("baz", collectionValues.next()); - Iterator<String> filteredCollectionValues = this.filteredCollectionHolder.iterator(); - assertEquals("baz", filteredCollectionValues.next()); - assertFalse(filteredCollectionValues.hasNext()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.collectionHolder).hasNoCollectionChangeListeners(CollectionValueModel.VALUES)); - ChangeListener listener = this.buildFilteredChangeListener(); - this.filteredCollectionHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.collectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.filteredCollectionHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.collectionHolder).hasNoCollectionChangeListeners(CollectionValueModel.VALUES)); - - this.filteredCollectionHolder.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - assertTrue(((AbstractModel) this.collectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.filteredCollectionHolder.removeCollectionChangeListener(CollectionValueModel.VALUES, listener); - assertTrue(((AbstractModel) this.collectionHolder).hasNoCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - public void testCollectionChange1() { - this.collectionHolder.addChangeListener(this.buildChangeListener()); - this.filteredCollectionHolder.addChangeListener(this.buildFilteredChangeListener()); - this.verifyCollectionChanges(); - } - - public void testCollectionChange2() { - this.collectionHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildListener()); - this.filteredCollectionHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildFilteredListener()); - this.verifyCollectionChanges(); - } - - private void clearEvents() { - this.addEvent = null; - this.removeEvent = null; - this.collectionClearedEvent = null; - this.collectionChangedEvent = null; - this.filteredAddEvent = null; - this.filteredRemoveEvent = null; - this.filteredCollectionClearedEvent = null; - this.filteredCollectionChangedEvent = null; - } - - private void verifyCollectionChanges() { - clearEvents(); - this.collectionHolder.add("bar"); - Collection<String> tempCollection = new Vector<String>(); - tempCollection.add("bar"); - this.verifyEvent(this.addEvent, this.collectionHolder, tempCollection); - this.verifyEvent(this.filteredAddEvent, this.filteredCollectionHolder, tempCollection); - - clearEvents(); - this.collectionHolder.remove("foo"); - tempCollection.remove("bar"); - tempCollection.add("foo"); - this.verifyEvent(this.removeEvent, this.collectionHolder, tempCollection); - assertNull(this.filteredRemoveEvent); - - - clearEvents(); - this.collectionHolder.remove("bar"); - tempCollection.add("bar"); - tempCollection.remove("foo"); - this.verifyEvent(this.removeEvent, this.collectionHolder, tempCollection); - this.verifyEvent(this.filteredRemoveEvent, this.filteredCollectionHolder, tempCollection); - - - clearEvents(); - this.collectionHolder.add("foo"); - tempCollection.remove("bar"); - tempCollection.add("foo"); - this.verifyEvent(this.addEvent, this.collectionHolder, tempCollection); - assertNull(this.filteredAddEvent); - - - clearEvents(); - Collection<String> newCollection = new Vector<String>(); - newCollection.add("fox"); - newCollection.add("baz"); - - this.collectionHolder.setValues(newCollection); - - this.verifyEvent(this.collectionChangedEvent, this.collectionHolder); - - tempCollection.remove("foo"); - tempCollection.add("baz"); - this.verifyEvent(this.filteredCollectionChangedEvent, this.filteredCollectionHolder); - - } - - private CollectionChangeListener buildListener() { - return new CollectionChangeListener() { - public void itemsAdded(CollectionAddEvent e) { - FilteringCollectionValueModelTests.this.addEvent = e; - } - public void itemsRemoved(CollectionRemoveEvent e) { - FilteringCollectionValueModelTests.this.removeEvent = e; - } - public void collectionCleared(CollectionClearEvent e) { - FilteringCollectionValueModelTests.this.collectionClearedEvent = e; - } - public void collectionChanged(CollectionChangeEvent e) { - FilteringCollectionValueModelTests.this.collectionChangedEvent = e; - } - }; - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(CollectionAddEvent e) { - FilteringCollectionValueModelTests.this.addEvent = e; - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - FilteringCollectionValueModelTests.this.removeEvent = e; - } - @Override - public void collectionCleared(CollectionClearEvent e) { - FilteringCollectionValueModelTests.this.collectionClearedEvent = e; - } - @Override - public void collectionChanged(CollectionChangeEvent e) { - FilteringCollectionValueModelTests.this.collectionChangedEvent = e; - } - }; - } - - private CollectionChangeListener buildFilteredListener() { - return new CollectionChangeListener() { - public void itemsAdded(CollectionAddEvent e) { - FilteringCollectionValueModelTests.this.filteredAddEvent = e; - } - public void itemsRemoved(CollectionRemoveEvent e) { - FilteringCollectionValueModelTests.this.filteredRemoveEvent = e; - } - public void collectionCleared(CollectionClearEvent e) { - FilteringCollectionValueModelTests.this.filteredCollectionClearedEvent = e; - } - public void collectionChanged(CollectionChangeEvent e) { - FilteringCollectionValueModelTests.this.filteredCollectionChangedEvent = e; - } - }; - } - - private ChangeListener buildFilteredChangeListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(CollectionAddEvent e) { - FilteringCollectionValueModelTests.this.filteredAddEvent = e; - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - FilteringCollectionValueModelTests.this.filteredRemoveEvent = e; - } - @Override - public void collectionCleared(CollectionClearEvent e) { - FilteringCollectionValueModelTests.this.filteredCollectionClearedEvent = e; - } - @Override - public void collectionChanged(CollectionChangeEvent e) { - FilteringCollectionValueModelTests.this.filteredCollectionChangedEvent = e; - } - }; - } - - private void verifyEvent(CollectionChangeEvent event, Object source) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - } - - private void verifyEvent(CollectionAddEvent event, Object source, Object items) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - assertEquals(items, CollectionTools.vector(event.getItems())); - } - - private void verifyEvent(CollectionRemoveEvent event, Object source, Object items) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - assertEquals(items, CollectionTools.vector(event.getItems())); - } - - public void testRemoveFilteredItem() { - // build collection with TestItems - SimpleCollectionValueModel<TestItem> tiHolder = new SimpleCollectionValueModel<TestItem>(this.buildCollection2()); - CollectionValueModel<TestItem> filteredTIHolder = new FilteringCollectionValueModel<TestItem>(tiHolder, this.buildFilter2()); - // add a listener to "activate" the wrapper - filteredTIHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildFilteredListener()); - - assertEquals(0, filteredTIHolder.size()); - - tiHolder.add(new TestItem("bar")); - assertEquals(1, filteredTIHolder.size()); - - TestItem baz = new TestItem("baz"); - tiHolder.add(baz); - assertEquals(2, filteredTIHolder.size()); - // before removing it, change the item so that it is filtered - baz.name = "jaz"; - tiHolder.remove(baz); - // this would fail because the item was not removed from - // the filtered collection cache... but we've fixed it now - assertEquals(1, filteredTIHolder.size()); - } - - private Collection<TestItem> buildCollection2() { - Collection<TestItem> collection = new Vector<TestItem>(); - collection.add(new TestItem("foo")); - return collection; - } - - private Filter<TestItem> buildFilter2() { - return new Filter<TestItem>() { - public boolean accept(TestItem ti) { - return ti.name.startsWith("b"); - } - }; - } - - - // ********** TestItem inner class ********** - - private class TestItem { - String name; - TestItem(String name) { - super(); - this.name = name; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/FilteringPropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/FilteringPropertyValueModelTests.java deleted file mode 100644 index 8b2f4f0f86..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/FilteringPropertyValueModelTests.java +++ /dev/null @@ -1,194 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.Filter; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.FilteringWritablePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class FilteringPropertyValueModelTests extends TestCase { - private ModifiablePropertyValueModel<String> objectHolder; - PropertyChangeEvent event; - - private ModifiablePropertyValueModel<String> filteredObjectHolder; - PropertyChangeEvent filteredEvent; - - public FilteringPropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = new SimplePropertyValueModel<String>("foo"); - this.filteredObjectHolder = new FilteringWritablePropertyValueModel<String>(this.objectHolder, this.buildFilter(), this.buildSetFilter()); - } - - private Filter<String> buildFilter() { - return new Filter<String>() { - public boolean accept(String s) { - return (s != null) && s.startsWith("b"); - } - }; - } - - private Filter<String> buildSetFilter() { - return new Filter<String>() { - public boolean accept(String s) { - return (s != null) && s.startsWith("b"); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - assertEquals("foo", this.objectHolder.getValue()); - assertNull(this.filteredObjectHolder.getValue()); - - this.objectHolder.setValue("bar"); - assertEquals("bar", this.objectHolder.getValue()); - assertNotNull(this.filteredObjectHolder.getValue()); - assertEquals("bar", this.filteredObjectHolder.getValue()); - - this.objectHolder.setValue("baz"); - assertEquals("baz", this.objectHolder.getValue()); - assertNotNull(this.filteredObjectHolder.getValue()); - assertEquals("baz", this.filteredObjectHolder.getValue()); - - this.objectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.filteredObjectHolder.getValue()); - - this.objectHolder.setValue("foo"); - assertEquals("foo", this.objectHolder.getValue()); - assertNull(this.filteredObjectHolder.getValue()); - } - - public void testSetValue() { - this.filteredObjectHolder.setValue("bar"); - assertEquals("bar", this.objectHolder.getValue()); - assertEquals("bar", this.filteredObjectHolder.getValue()); - - this.filteredObjectHolder.setValue("foo"); - assertEquals("bar", this.objectHolder.getValue()); - assertEquals("bar", this.filteredObjectHolder.getValue()); - - this.filteredObjectHolder.setValue(null); - assertEquals("bar", this.objectHolder.getValue()); - assertEquals("bar", this.filteredObjectHolder.getValue()); - - this.filteredObjectHolder.setValue("baz"); - assertEquals("baz", this.objectHolder.getValue()); - assertEquals("baz", this.filteredObjectHolder.getValue()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildFilteredListener(); - this.filteredObjectHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.filteredObjectHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.filteredObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.filteredObjectHolder.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testPropertyChange1() { - this.objectHolder.addChangeListener(this.buildListener()); - this.filteredObjectHolder.addChangeListener(this.buildFilteredListener()); - this.verifyPropertyChanges(); - } - - public void testPropertyChange2() { - this.objectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.filteredObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildFilteredListener()); - this.verifyPropertyChanges(); - } - - private void verifyPropertyChanges() { - this.event = null; - this.filteredEvent = null; - this.objectHolder.setValue("bar"); - this.verifyEvent(this.event, this.objectHolder, "foo", "bar"); - this.verifyEvent(this.filteredEvent, this.filteredObjectHolder, null, "bar"); - - this.event = null; - this.filteredEvent = null; - this.objectHolder.setValue("baz"); - this.verifyEvent(this.event, this.objectHolder, "bar", "baz"); - this.verifyEvent(this.filteredEvent, this.filteredObjectHolder, "bar", "baz"); - - this.event = null; - this.filteredEvent = null; - this.objectHolder.setValue("foo"); - this.verifyEvent(this.event, this.objectHolder, "baz", "foo"); - this.verifyEvent(this.filteredEvent, this.filteredObjectHolder, "baz", null); - - this.event = null; - this.filteredEvent = null; - this.objectHolder.setValue("fop"); - this.verifyEvent(this.event, this.objectHolder, "foo", "fop"); - assertNull(this.filteredEvent); - - this.event = null; - this.filteredEvent = null; - this.objectHolder.setValue(null); - this.verifyEvent(this.event, this.objectHolder, "fop", null); - assertNull(this.filteredEvent); - - this.event = null; - this.filteredEvent = null; - this.objectHolder.setValue("bar"); - this.verifyEvent(this.event, this.objectHolder, null, "bar"); - this.verifyEvent(this.filteredEvent, this.filteredObjectHolder, null, "bar"); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - FilteringPropertyValueModelTests.this.event = e; - } - }; - } - - private ChangeListener buildFilteredListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - FilteringPropertyValueModelTests.this.filteredEvent = e; - } - }; - } - - private void verifyEvent(PropertyChangeEvent e, Object source, Object oldValue, Object newValue) { - assertEquals(source, e.getSource()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - assertEquals(oldValue, e.getOldValue()); - assertEquals(newValue, e.getNewValue()); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemCollectionListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemCollectionListValueModelAdapterTests.java deleted file mode 100644 index 7ede9fcd6a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemCollectionListValueModelAdapterTests.java +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.swing.Icon; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ItemCollectionListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ItemCollectionListValueModelAdapterTests extends TestCase { - private Junk foo; - private Junk bar; - private Junk baz; - private Junk joo; - private Junk jar; - private Junk jaz; - - private Junk tom; - private Junk dick; - private Junk harry; - - public ItemCollectionListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.foo = new Junk("foo"); - this.bar = new Junk("bar"); - this.baz = new Junk("baz"); - this.joo = new Junk("joo"); - this.jar = new Junk("jar"); - this.jaz = new Junk("jaz"); - - this.tom = new Junk("tom"); - this.dick = new Junk("dick"); - this.harry = new Junk("harry"); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testCollectionSynchronization() { - SimpleCollectionValueModel<Junk> collectionHolder = this.buildCollectionHolder(); - ListValueModel<Junk> listValueModel = new ItemCollectionListValueModelAdapter<Junk>(collectionHolder, Junk.STUFF_COLLECTION); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.add(this.tom); - collectionHolder.add(this.dick); - collectionHolder.add(this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.remove(this.foo); - collectionHolder.remove(this.jar); - collectionHolder.remove(this.harry); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - public void testListSynchronization() { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemCollectionListValueModelAdapter<Junk>(listHolder, Junk.STUFF_COLLECTION); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.add(6, this.tom); - listHolder.add(7, this.dick); - listHolder.add(8, this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.remove(8); - listHolder.remove(0); - listHolder.remove(4); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - private void compare(ListValueModel<Junk> listValueModel, List<Junk> list) { - assertEquals(listValueModel.size(), list.size()); - for (int i = 0; i < listValueModel.size(); i++) { - assertEquals(listValueModel.get(i), list.get(i)); - } - } - - - public void testHasListeners() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyListChangeListeners(Junk.STUFF_COLLECTION)); - assertFalse(this.jaz.hasAnyListChangeListeners(Junk.STUFF_COLLECTION)); - - ListValueModel<Junk> listValueModel = new ItemCollectionListValueModelAdapter<Junk>(listHolder, Junk.STUFF_COLLECTION); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - assertFalse(this.jaz.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - this.verifyHasNoListeners(listValueModel); - - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertTrue(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.foo.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - assertTrue(this.jaz.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - this.verifyHasListeners(listValueModel); - - listValueModel.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - assertFalse(this.jaz.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - this.verifyHasNoListeners(listValueModel); - } - - public void testGetSize() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemCollectionListValueModelAdapter<Junk>(listHolder, Junk.STUFF_COLLECTION); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(6, listValueModel.size()); - assertEquals(6, synchList.size()); - } - - public void testGet() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new SortedListValueModelWrapper<Junk>(new ItemCollectionListValueModelAdapter<Junk>(listHolder, Junk.STUFF_COLLECTION)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(this.bar, listValueModel.get(0)); - assertEquals(this.bar, synchList.get(0)); - this.bar.removeStuff("bar"); - this.bar.addStuff("zzz"); - this.bar.addStuff("bar"); - assertEquals(this.bar, listValueModel.get(5)); - assertEquals(this.bar, synchList.get(5)); - this.bar.removeStuff("zzz"); - } - - private void verifyHasNoListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private void verifyHasListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private SimpleCollectionValueModel<Junk> buildCollectionHolder() { - return new SimpleCollectionValueModel<Junk>(this.buildCollection()); - } - - private Collection<Junk> buildCollection() { - Bag<Junk> bag = new HashBag<Junk>(); - this.populateCollection(bag); - return bag; - } - - private SimpleListValueModel<Junk> buildListHolder() { - return new SimpleListValueModel<Junk>(this.buildList()); - } - - private List<Junk> buildList() { - List<Junk> list = new ArrayList<Junk>(); - this.populateCollection(list); - return list; - } - - private void populateCollection(Collection<Junk> c) { - c.add(this.foo); - c.add(this.bar); - c.add(this.baz); - c.add(this.joo); - c.add(this.jar); - c.add(this.jaz); - } - - - // ********** Junk class ********** - - private class Junk extends AbstractModel implements Displayable, Comparable<Junk> { - private Collection<String> stuff; - public static final String STUFF_COLLECTION = "stuff"; - - - public Junk(String stuffItem) { - this.stuff = new ArrayList<String>(); - this.stuff.add(stuffItem); - } - - public void addStuff(String stuffItem) { - this.addItemToCollection(stuffItem, this.stuff, STUFF_COLLECTION); - } - - public void removeStuff(String stuffItem) { - this.removeItemFromCollection(stuffItem, this.stuff, STUFF_COLLECTION); - } - - public String displayString() { - return toString(); - } - - public Icon icon() { - return null; - } - - public int compareTo(Junk o) { - return this.displayString().compareTo(o.displayString()); - } - - @Override - public String toString() { - return "Junk(" + this.stuff + ")"; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemListListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemListListValueModelAdapterTests.java deleted file mode 100644 index d566ece7d8..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemListListValueModelAdapterTests.java +++ /dev/null @@ -1,244 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.swing.Icon; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ItemListListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ItemListListValueModelAdapterTests extends TestCase { - private Junk foo; - private Junk bar; - private Junk baz; - private Junk joo; - private Junk jar; - private Junk jaz; - - private Junk tom; - private Junk dick; - private Junk harry; - - public ItemListListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.foo = new Junk("foo"); - this.bar = new Junk("bar"); - this.baz = new Junk("baz"); - this.joo = new Junk("joo"); - this.jar = new Junk("jar"); - this.jaz = new Junk("jaz"); - - this.tom = new Junk("tom"); - this.dick = new Junk("dick"); - this.harry = new Junk("harry"); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testCollectionSynchronization() { - SimpleCollectionValueModel<Junk> collectionHolder = this.buildCollectionHolder(); - ListValueModel<Junk> listValueModel = new ItemListListValueModelAdapter<Junk>(collectionHolder, Junk.STUFF_LIST); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.add(this.tom); - collectionHolder.add(this.dick); - collectionHolder.add(this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.remove(this.foo); - collectionHolder.remove(this.jar); - collectionHolder.remove(this.harry); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - public void testListSynchronization() { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemListListValueModelAdapter<Junk>(listHolder, Junk.STUFF_LIST); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.add(6, this.tom); - listHolder.add(7, this.dick); - listHolder.add(8, this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.remove(8); - listHolder.remove(0); - listHolder.remove(4); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - private void compare(ListValueModel<Junk> listValueModel, List<Junk> list) { - assertEquals(listValueModel.size(), list.size()); - for (int i = 0; i < listValueModel.size(); i++) { - assertEquals(listValueModel.get(i), list.get(i)); - } - } - - - public void testHasListeners() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertFalse(this.jaz.hasAnyListChangeListeners(Junk.STUFF_LIST)); - - ListValueModel<Junk> listValueModel = new ItemListListValueModelAdapter<Junk>(listHolder, Junk.STUFF_LIST); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertFalse(this.jaz.hasAnyListChangeListeners(Junk.STUFF_LIST)); - this.verifyHasNoListeners(listValueModel); - - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertTrue(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.foo.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertTrue(this.jaz.hasAnyListChangeListeners(Junk.STUFF_LIST)); - this.verifyHasListeners(listValueModel); - - listValueModel.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertFalse(this.jaz.hasAnyListChangeListeners(Junk.STUFF_LIST)); - this.verifyHasNoListeners(listValueModel); - } - - public void testGetSize() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemListListValueModelAdapter<Junk>(listHolder, Junk.STUFF_LIST); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(6, listValueModel.size()); - assertEquals(6, synchList.size()); - } - - public void testGet() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new SortedListValueModelWrapper<Junk>(new ItemListListValueModelAdapter<Junk>(listHolder, Junk.STUFF_LIST)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(this.bar, listValueModel.get(0)); - assertEquals(this.bar, synchList.get(0)); - this.bar.removeStuff("bar"); - this.bar.addStuff("zzz"); - this.bar.addStuff("bar"); - assertEquals(this.bar, listValueModel.get(5)); - assertEquals(this.bar, synchList.get(5)); - this.bar.removeStuff("zzz"); - } - - private void verifyHasNoListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private void verifyHasListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private SimpleCollectionValueModel<Junk> buildCollectionHolder() { - return new SimpleCollectionValueModel<Junk>(this.buildCollection()); - } - - private Collection<Junk> buildCollection() { - Bag<Junk> bag = new HashBag<Junk>(); - this.populateCollection(bag); - return bag; - } - - private SimpleListValueModel<Junk> buildListHolder() { - return new SimpleListValueModel<Junk>(this.buildList()); - } - - private List<Junk> buildList() { - List<Junk> list = new ArrayList<Junk>(); - this.populateCollection(list); - return list; - } - - private void populateCollection(Collection<Junk> c) { - c.add(this.foo); - c.add(this.bar); - c.add(this.baz); - c.add(this.joo); - c.add(this.jar); - c.add(this.jaz); - } - - - // ********** Junk class ********** - - private class Junk extends AbstractModel implements Displayable, Comparable<Junk> { - private List<String> stuff; - public static final String STUFF_LIST = "stuff"; - - - public Junk(String stuffItem) { - this.stuff = new ArrayList<String>(); - this.stuff.add(stuffItem); - } - public void addStuff(String stuffItem) { - this.stuff.add(stuffItem); - fireItemAdded(STUFF_LIST, this.stuff.indexOf(stuffItem), stuffItem); - } - - public void removeStuff(String stuffItem) { - int index = this.stuff.indexOf(stuffItem); - this.stuff.remove(stuffItem); - fireItemRemoved(STUFF_LIST, index, stuffItem); - } - - public String displayString() { - return toString(); - } - - public Icon icon() { - return null; - } - - public int compareTo(Junk o) { - return this.displayString().compareTo(o.displayString()); - } - - @Override - public String toString() { - return "Junk(" + this.stuff + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemPropertyListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemPropertyListValueModelAdapterTests.java deleted file mode 100644 index 35fce2a3e9..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemPropertyListValueModelAdapterTests.java +++ /dev/null @@ -1,335 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.swing.Icon; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ItemPropertyListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ItemPropertyListValueModelAdapterTests extends TestCase { - private Junk foo; - private Junk bar; - private Junk baz; - private Junk joo; - private Junk jar; - private Junk jaz; - - private Junk tom; - private Junk dick; - private Junk harry; - - public ItemPropertyListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.foo = new Junk("this.foo"); - this.bar = new Junk("this.bar"); - this.baz = new Junk("this.baz"); - this.joo = new Junk("this.joo"); - this.jar = new Junk("this.jar"); - this.jaz = new Junk("this.jaz"); - - this.tom = new Junk("this.tom"); - this.dick = new Junk("this.dick"); - this.harry = new Junk("this.harry"); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testCollectionSynchronization() { - SimpleCollectionValueModel<Junk> collectionHolder = this.buildCollectionHolder(); - ListValueModel<Junk> listValueModel = new ItemPropertyListValueModelAdapter<Junk>(collectionHolder, Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.add(this.tom); - collectionHolder.add(this.dick); - collectionHolder.add(this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.remove(this.foo); - collectionHolder.remove(this.jar); - collectionHolder.remove(this.harry); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.setValues(this.buildCollection()); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - public void testListSynchronization() { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemPropertyListValueModelAdapter<Junk>(listHolder, Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.add(6, this.tom); - listHolder.add(7, this.dick); - listHolder.add(8, this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.remove(8); - listHolder.remove(0); - listHolder.remove(4); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - // test concurrent modification exception - listHolder.setListValues(this.buildList()); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - private void compare(ListValueModel<Junk> listValueModel, List<Junk> list) { - assertEquals(listValueModel.size(), list.size()); - for (int i = 0; i < listValueModel.size(); i++) { - assertEquals(listValueModel.get(i), list.get(i)); - } - } - - public void testCollectionSort() { - this.verifyCollectionSort(null); - } - - public void testListSort() { - this.verifyListSort(null); - } - - public void testCustomCollectionSort() { - this.verifyCollectionSort(this.buildCustomComparator()); - } - - public void testCustomListSort() { - this.verifyListSort(this.buildCustomComparator()); - } - - private Comparator<Junk> buildCustomComparator() { - // sort with reverse order - return new Comparator<Junk>() { - public int compare(Junk o1, Junk o2) { - return o2.displayString().compareTo(o1.displayString()); - } - }; - } - - private void verifyCollectionSort(Comparator<Junk> comparator) { - SimpleCollectionValueModel<Junk> collectionHolder = this.buildCollectionHolder(); - ListValueModel<Junk> listValueModel = new ItemPropertyListValueModelAdapter<Junk>(new SortedListValueModelAdapter<Junk>(collectionHolder, comparator), Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - collectionHolder.add(this.tom); - collectionHolder.add(this.dick); - collectionHolder.add(this.harry); - assertEquals(9, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - collectionHolder.remove(this.foo); - collectionHolder.remove(this.jar); - collectionHolder.remove(this.harry); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - collectionHolder.setValues(this.buildCollection()); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - } - - private void verifyListSort(Comparator<Junk> comparator) { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemPropertyListValueModelAdapter<Junk>(new SortedListValueModelWrapper<Junk>(listHolder, comparator), Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - listHolder.add(0, this.tom); - listHolder.add(0, this.dick); - listHolder.add(0, this.harry); - assertEquals(9, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - listHolder.remove(8); - listHolder.remove(4); - listHolder.remove(0); - listHolder.remove(5); - assertEquals(5, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - listHolder.setListValues(this.buildList()); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - } - - private void compareSort(ListValueModel<Junk> listValueModel, List<Junk> list, Comparator<Junk> comparator) { - SortedSet<Junk> ss = new TreeSet<Junk>(comparator); - for (int i = 0; i < listValueModel.size(); i++) { - ss.add(listValueModel.get(i)); - } - assertEquals(ss.size(), list.size()); - for (Iterator<Junk> stream1 = ss.iterator(), stream2 = list.iterator(); stream1.hasNext(); ) { - assertEquals(stream1.next(), stream2.next()); - } - } - - public void testHasListeners() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertFalse(this.foo.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - assertFalse(this.jaz.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertFalse(this.jaz.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - - ListValueModel<Junk> listValueModel = new ItemPropertyListValueModelAdapter<Junk>(new SortedListValueModelWrapper<Junk>(listHolder), Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertFalse(this.foo.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - assertFalse(this.jaz.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertFalse(this.jaz.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - this.verifyHasNoListeners(listValueModel); - - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertTrue(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.foo.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertTrue(this.foo.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - assertTrue(this.jaz.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertTrue(this.jaz.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - this.verifyHasListeners(listValueModel); - - listValueModel.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertFalse(this.foo.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - assertFalse(this.jaz.hasAnyPropertyChangeListeners(Displayable.DISPLAY_STRING_PROPERTY)); - assertFalse(this.jaz.hasAnyPropertyChangeListeners(Displayable.ICON_PROPERTY)); - this.verifyHasNoListeners(listValueModel); - } - - public void testGetSize() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemPropertyListValueModelAdapter<Junk>(new SortedListValueModelWrapper<Junk>(listHolder), Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(6, listValueModel.size()); - assertEquals(6, synchList.size()); - } - - public void testGet() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new SortedListValueModelWrapper<Junk>(new ItemPropertyListValueModelAdapter<Junk>(listHolder, Displayable.DISPLAY_STRING_PROPERTY, Displayable.ICON_PROPERTY)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(this.bar, listValueModel.get(0)); - assertEquals(this.bar, synchList.get(0)); - this.bar.setName("zzz"); - assertEquals(this.bar, listValueModel.get(5)); - assertEquals(this.bar, synchList.get(5)); - this.bar.setName("this.bar"); - } - - private void verifyHasNoListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private void verifyHasListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private SimpleCollectionValueModel<Junk> buildCollectionHolder() { - return new SimpleCollectionValueModel<Junk>(this.buildCollection()); - } - - private Collection<Junk> buildCollection() { - Bag<Junk> bag = new HashBag<Junk>(); - this.populateCollection(bag); - return bag; - } - - private SimpleListValueModel<Junk> buildListHolder() { - return new SimpleListValueModel<Junk>(this.buildList()); - } - - private List<Junk> buildList() { - List<Junk> list = new ArrayList<Junk>(); - this.populateCollection(list); - return list; - } - - private void populateCollection(Collection<Junk> c) { - c.add(this.foo); - c.add(this.bar); - c.add(this.baz); - c.add(this.joo); - c.add(this.jar); - c.add(this.jaz); - } - - - // ********** Junk class ********** - - private class Junk extends AbstractModel implements Displayable, Comparable<Junk> { - private String name; - public Junk(String name) { - this.name = name; - } - public String displayString() { - return this.name; - } - public Icon icon() { - return null; - } - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(DISPLAY_STRING_PROPERTY, old, name); - } - public int compareTo(Junk o) { - return this.displayString().compareTo(o.displayString()); - } - @Override - public String toString() { - return "Junk(" + this.name + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemStateListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemStateListValueModelAdapterTests.java deleted file mode 100644 index 18730739e9..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ItemStateListValueModelAdapterTests.java +++ /dev/null @@ -1,306 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ItemStateListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ItemStateListValueModelAdapterTests extends TestCase { - private Junk foo; - private Junk bar; - private Junk baz; - private Junk joo; - private Junk jar; - private Junk jaz; - - private Junk tom; - private Junk dick; - private Junk harry; - - public ItemStateListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.foo = new Junk("this.foo"); - this.bar = new Junk("this.bar"); - this.baz = new Junk("this.baz"); - this.joo = new Junk("this.joo"); - this.jar = new Junk("this.jar"); - this.jaz = new Junk("this.jaz"); - - this.tom = new Junk("this.tom"); - this.dick = new Junk("this.dick"); - this.harry = new Junk("this.harry"); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testCollectionSynchronization() { - SimpleCollectionValueModel<Junk> collectionHolder = this.buildCollectionHolder(); - ListValueModel<Junk> listValueModel = new ItemStateListValueModelAdapter<Junk>(collectionHolder); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.add(this.tom); - collectionHolder.add(this.dick); - collectionHolder.add(this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - collectionHolder.remove(this.foo); - collectionHolder.remove(this.jar); - collectionHolder.remove(this.harry); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - public void testListSynchronization() { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemStateListValueModelAdapter<Junk>(listHolder); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.add(6, this.tom); - listHolder.add(7, this.dick); - listHolder.add(8, this.harry); - assertEquals(9, synchList.size()); - this.compare(listValueModel, synchList); - - listHolder.remove(8); - listHolder.remove(0); - listHolder.remove(4); - assertEquals(6, synchList.size()); - this.compare(listValueModel, synchList); - } - - private void compare(ListValueModel<Junk> listValueModel, List<Junk> list) { - assertEquals(listValueModel.size(), list.size()); - for (int i = 0; i < listValueModel.size(); i++) { - assertEquals(listValueModel.get(i), list.get(i)); - } - } - - public void testCollectionSort() { - this.verifyCollectionSort(null); - } - - public void testListSort() { - this.verifyListSort(null); - } - - public void testCustomCollectionSort() { - this.verifyCollectionSort(this.buildCustomComparator()); - } - - public void testCustomListSort() { - this.verifyListSort(this.buildCustomComparator()); - } - - private Comparator<Junk> buildCustomComparator() { - // sort with reverse order - return new Comparator<Junk>() { - public int compare(Junk o1, Junk o2) { - return o2.compareTo(o1); - } - }; - } - - private void verifyCollectionSort(Comparator<Junk> comparator) { - SimpleCollectionValueModel<Junk> collectionHolder = this.buildCollectionHolder(); - ListValueModel<Junk> listValueModel = new ItemStateListValueModelAdapter<Junk>(new SortedListValueModelAdapter<Junk>(collectionHolder, comparator)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - collectionHolder.add(this.tom); - collectionHolder.add(this.dick); - collectionHolder.add(this.harry); - assertEquals(9, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - collectionHolder.remove(this.foo); - collectionHolder.remove(this.jar); - collectionHolder.remove(this.harry); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - } - - private void verifyListSort(Comparator<Junk> comparator) { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemStateListValueModelAdapter<Junk>(new SortedListValueModelWrapper<Junk>(listHolder, comparator)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertEquals(6, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - listHolder.add(0, this.tom); - listHolder.add(0, this.dick); - listHolder.add(0, this.harry); - assertEquals(9, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - - listHolder.remove(8); - listHolder.remove(4); - listHolder.remove(0); - listHolder.remove(5); - assertEquals(5, synchList.size()); - this.compareSort(listValueModel, synchList, comparator); - } - - private void compareSort(ListValueModel<Junk> listValueModel, List<Junk> list, Comparator<Junk> comparator) { - SortedSet<Junk> ss = new TreeSet<Junk>(comparator); - for (int i = 0; i < listValueModel.size(); i++) { - ss.add(listValueModel.get(i)); - } - assertEquals(ss.size(), list.size()); - for (Iterator<Junk> stream1 = ss.iterator(), stream2 = list.iterator(); stream1.hasNext(); ) { - assertEquals(stream1.next(), stream2.next()); - } - } - - public void testHasListeners() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyStateChangeListeners()); - assertFalse(this.foo.hasAnyStateChangeListeners()); - assertFalse(this.jaz.hasAnyStateChangeListeners()); - assertFalse(this.jaz.hasAnyStateChangeListeners()); - - ListValueModel<Junk> listValueModel = new ItemStateListValueModelAdapter<Junk>(new SortedListValueModelWrapper<Junk>(listHolder)); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyStateChangeListeners()); - assertFalse(this.foo.hasAnyStateChangeListeners()); - assertFalse(this.jaz.hasAnyStateChangeListeners()); - assertFalse(this.jaz.hasAnyStateChangeListeners()); - this.verifyHasNoListeners(listValueModel); - - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - assertTrue(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.foo.hasAnyStateChangeListeners()); - assertTrue(this.foo.hasAnyStateChangeListeners()); - assertTrue(this.jaz.hasAnyStateChangeListeners()); - assertTrue(this.jaz.hasAnyStateChangeListeners()); - this.verifyHasListeners(listValueModel); - - listValueModel.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(this.foo.hasAnyStateChangeListeners()); - assertFalse(this.foo.hasAnyStateChangeListeners()); - assertFalse(this.jaz.hasAnyStateChangeListeners()); - assertFalse(this.jaz.hasAnyStateChangeListeners()); - this.verifyHasNoListeners(listValueModel); - } - - public void testGetSize() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new ItemStateListValueModelAdapter<Junk>(new SortedListValueModelWrapper<Junk>(listHolder)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(6, listValueModel.size()); - assertEquals(6, synchList.size()); - } - - public void testGet() throws Exception { - SimpleListValueModel<Junk> listHolder = this.buildListHolder(); - ListValueModel<Junk> listValueModel = new SortedListValueModelWrapper<Junk>(new ItemStateListValueModelAdapter<Junk>(listHolder)); - CoordinatedList<Junk> synchList = new CoordinatedList<Junk>(listValueModel); - this.verifyHasListeners(listValueModel); - assertEquals(this.bar, listValueModel.get(0)); - assertEquals(this.bar, synchList.get(0)); - this.bar.setName("zzz"); - assertEquals(this.bar, listValueModel.get(5)); - assertEquals(this.bar, synchList.get(5)); - this.bar.setName("this.bar"); - } - - private void verifyHasNoListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private void verifyHasListeners(ListValueModel<Junk> listValueModel) throws Exception { - assertTrue(((AbstractModel) listValueModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private SimpleCollectionValueModel<Junk> buildCollectionHolder() { - return new SimpleCollectionValueModel<Junk>(this.buildCollection()); - } - - private Collection<Junk> buildCollection() { - Bag<Junk> bag = new HashBag<Junk>(); - this.populateCollection(bag); - return bag; - } - - private SimpleListValueModel<Junk> buildListHolder() { - return new SimpleListValueModel<Junk>(this.buildList()); - } - - private List<Junk> buildList() { - List<Junk> list = new ArrayList<Junk>(); - this.populateCollection(list); - return list; - } - - private void populateCollection(Collection<Junk> c) { - c.add(this.foo); - c.add(this.bar); - c.add(this.baz); - c.add(this.joo); - c.add(this.jar); - c.add(this.jaz); - } - - // ********** Junk class ********** - private class Junk extends AbstractModel implements Comparable<Junk> { - private String name; - public Junk(String name) { - this.name = name; - } - public void setName(String name) { - this.name = name; - this.fireStateChanged(); - } - public int compareTo(Junk j) { - return this.name.compareTo(j.name); - } - @Override - public String toString() { - return "Junk(" + this.name + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/JptUtilityModelValueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/JptUtilityModelValueTests.java deleted file mode 100644 index 8f256b46f3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/JptUtilityModelValueTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.eclipse.jpt.common.utility.tests.internal.model.value.prefs.JptUtilityModelValuePrefsTests; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.JptUtilityModelValueSwingTests; - -public class JptUtilityModelValueTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityModelValueTests.class.getPackage().getName()); - - suite.addTest(JptUtilityModelValuePrefsTests.suite()); - suite.addTest(JptUtilityModelValueSwingTests.suite()); - - suite.addTestSuite(BufferedWritablePropertyValueModelTests.class); - suite.addTestSuite(CachingTransformationPropertyValueModelTests.class); - suite.addTestSuite(CachingTransformationWritablePropertyValueModelTests.class); - suite.addTestSuite(CollectionAspectAdapterTests.class); - suite.addTestSuite(CollectionListValueModelAdapterTests.class); - suite.addTestSuite(CollectionPropertyValueModelAdapterTests.class); - suite.addTestSuite(CompositeBooleanPropertyValueModelTests.class); - suite.addTestSuite(CompositeCollectionValueModelTests.class); - suite.addTestSuite(CompositeListValueModelTests.class); - suite.addTestSuite(CompositePropertyValueModelTests.class); - suite.addTestSuite(DoublePropertyValueModelTests.class); - suite.addTestSuite(DoubleModifiablePropertyValueModelTests.class); - suite.addTestSuite(ExtendedListValueModelWrapperTests.class); - suite.addTestSuite(FilteringCollectionValueModelTests.class); - suite.addTestSuite(FilteringPropertyValueModelTests.class); - suite.addTestSuite(ItemCollectionListValueModelAdapterTests.class); - suite.addTestSuite(ItemListListValueModelAdapterTests.class); - suite.addTestSuite(ItemPropertyListValueModelAdapterTests.class); - suite.addTestSuite(ItemStateListValueModelAdapterTests.class); - suite.addTestSuite(ListAspectAdapterTests.class); - suite.addTestSuite(ListCollectionValueModelAdapterTests.class); - suite.addTestSuite(ListCuratorTests.class); - suite.addTestSuite(NullCollectionValueModelTests.class); - suite.addTestSuite(NullListValueModelTests.class); - suite.addTestSuite(NullPropertyValueModelTests.class); - suite.addTestSuite(PropertyAspectAdapterTests.class); - suite.addTestSuite(PropertyCollectionValueModelAdapterTests.class); - suite.addTestSuite(PropertyListValueModelAdapterTests.class); - suite.addTestSuite(ReadOnlyWritablePropertyValueModelWrapperTests.class); - suite.addTestSuite(SetCollectionValueModelTests.class); - suite.addTestSuite(SimpleCollectionValueModelTests.class); - suite.addTestSuite(SimpleListValueModelTests.class); - suite.addTestSuite(SimplePropertyValueModelTests.class); - suite.addTestSuite(SortedListValueModelAdapterTests.class); - suite.addTestSuite(SortedListValueModelWrapperTests.class); - suite.addTestSuite(StaticCollectionValueModelTests.class); - suite.addTestSuite(StaticListValueModelTests.class); - suite.addTestSuite(StaticValueModelTests.class); - suite.addTestSuite(TransformationListValueModelTests.class); - suite.addTestSuite(TransformationListValueModelTests.TransformerTests.class); - suite.addTestSuite(TransformationPropertyValueModelTests.class); - suite.addTestSuite(ValueCollectionAdapterTests.class); - suite.addTestSuite(ValueListAdapterTests.class); - suite.addTestSuite(ValuePropertyAdapterTests.class); - suite.addTestSuite(ValueStateAdapterTests.class); - - return suite; - } - - private JptUtilityModelValueTests() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListAspectAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListAspectAdapterTests.java deleted file mode 100644 index 4d7850d4c3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListAspectAdapterTests.java +++ /dev/null @@ -1,475 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyListIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ListAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ListAspectAdapterTests extends TestCase { - private TestSubject subject1; - private ModifiablePropertyValueModel<TestSubject> subjectHolder1; - private LocalListAspectAdapter aa1; - private ListEvent event1; - private ListChangeListener listener1; - - private TestSubject subject2; - - public ListAspectAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.subject1 = new TestSubject(); - this.subject1.addNames(this.subject1Names()); - this.subject1.addDescriptions(this.subject1Descriptions()); - this.subjectHolder1 = new SimplePropertyValueModel<TestSubject>(this.subject1); - this.aa1 = this.buildAspectAdapter(this.subjectHolder1); - this.listener1 = this.buildValueChangeListener1(); - this.aa1.addListChangeListener(ListValueModel.LIST_VALUES, this.listener1); - this.event1 = null; - - this.subject2 = new TestSubject(); - this.subject2.addNames(this.subject2Names()); - this.subject2.addDescriptions(this.subject2Descriptions()); - } - - private List<String> subject1Names() { - List<String> result = new ArrayList<String>(); - result.add("foo"); - result.add("bar"); - result.add("baz"); - result.add("bam"); - return result; - } - - private List<String> subject1Descriptions() { - List<String> result = new ArrayList<String>(); - result.add("this.subject1 description1"); - result.add("this.subject1 description2"); - return result; - } - - private List<String> subject2Names() { - List<String> result = new ArrayList<String>(); - result.add("joo"); - result.add("jar"); - result.add("jaz"); - result.add("jam"); - return result; - } - - private List<String> subject2Descriptions() { - List<String> result = new ArrayList<String>(); - result.add("this.subject2 description1"); - result.add("this.subject2 description2"); - return result; - } - - private LocalListAspectAdapter buildAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - return new LocalListAspectAdapter(subjectHolder); - } - - private ListChangeListener buildValueChangeListener1() { - return new ListChangeListener() { - public void itemsAdded(ListAddEvent e) { - ListAspectAdapterTests.this.value1Changed(e); - } - public void itemsRemoved(ListRemoveEvent e) { - ListAspectAdapterTests.this.value1Changed(e); - } - public void itemsReplaced(ListReplaceEvent e) { - ListAspectAdapterTests.this.value1Changed(e); - } - public void itemsMoved(ListMoveEvent e) { - ListAspectAdapterTests.this.value1Changed(e); - } - public void listCleared(ListClearEvent e) { - ListAspectAdapterTests.this.value1Changed(e); - } - public void listChanged(ListChangeEvent e) { - ListAspectAdapterTests.this.value1Changed(e); - } - }; - } - - void value1Changed(ListEvent e) { - this.event1 = e; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSubjectHolder() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - this.subjectHolder1.setValue(this.subject2); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject2Names(), CollectionTools.list(this.aa1.listIterator())); - - this.event1 = null; - this.subjectHolder1.setValue(null); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertFalse(this.aa1.iterator().hasNext()); - - this.event1 = null; - this.subjectHolder1.setValue(this.subject1); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - } - - public void testAdd() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - this.subject1.addName("jam"); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject1Names().size(), ((ListAddEvent) this.event1).getIndex()); - assertEquals("jam", ((ListAddEvent) this.event1).getItems().iterator().next()); - List<String> namesPlus = this.subject1Names(); - namesPlus.add("jam"); - assertEquals(namesPlus, CollectionTools.list(this.aa1.listIterator())); - - this.event1 = null; - this.aa1.add(2, "jaz"); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(2, ((ListAddEvent) this.event1).getIndex()); - assertEquals("jaz", ((ListAddEvent) this.event1).getItems().iterator().next()); - namesPlus.add(2, "jaz"); - assertEquals(namesPlus, CollectionTools.list(this.aa1.listIterator())); - } - - public void testDefaultAdd() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - List<String> items = new ArrayList<String>(); - items.add("joo"); - items.add("jar"); - items.add("jaz"); - items.add("jam"); - - this.event1 = null; - this.aa1.addAll(2, items); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(5, ((ListAddEvent) this.event1).getIndex()); // only the last "add" event will still be there - assertEquals("jam", ((ListAddEvent) this.event1).getItems().iterator().next()); - List<String> namesPlus = this.subject1Names(); - namesPlus.addAll(2, items); - assertEquals(namesPlus, CollectionTools.list(this.aa1.listIterator())); - } - - public void testRemove() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - String removedName = this.subject1.removeName(0); // should be "foo" - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(0, ((ListRemoveEvent) this.event1).getIndex()); - assertEquals(removedName, ((ListRemoveEvent) this.event1).getItems().iterator().next()); - List<String> namesMinus = this.subject1Names(); - namesMinus.remove(0); - assertEquals(namesMinus, CollectionTools.list(this.aa1.listIterator())); - - this.event1 = null; - Object removedItem = this.aa1.remove(0); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(0, ((ListRemoveEvent) this.event1).getIndex()); - assertEquals(removedItem, ((ListRemoveEvent) this.event1).getItems().iterator().next()); - namesMinus.remove(0); - assertEquals(namesMinus, CollectionTools.list(this.aa1.listIterator())); - } - - public void testDefaultLength() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - List<String> items = new ArrayList<String>(); - items.add("bar"); - items.add("baz"); - - this.event1 = null; - this.aa1.remove(1, 2); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(1, ((ListRemoveEvent) this.event1).getIndex()); // only the last "remove" event will still be there - assertEquals("baz", ((ListRemoveEvent) this.event1).getItems().iterator().next()); - List<String> namesPlus = this.subject1Names(); - namesPlus.remove(1); - namesPlus.remove(1); - assertEquals(namesPlus, CollectionTools.list(this.aa1.listIterator())); - } - - public void testReplace() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - String replacedName = this.subject1.setName(0, "jelly"); // should be "foo" - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(0, ((ListReplaceEvent) this.event1).getIndex()); - assertEquals("jelly", ((ListReplaceEvent) this.event1).getNewItems().iterator().next()); - assertEquals(replacedName, ((ListReplaceEvent) this.event1).getOldItems().iterator().next()); - List<String> namesChanged = this.subject1Names(); - namesChanged.set(0, "jelly"); - assertEquals(namesChanged, CollectionTools.list(this.aa1.listIterator())); - - this.event1 = null; - replacedName = this.subject1.setName(1, "roll"); // should be "bar" - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(1, ((ListReplaceEvent) this.event1).getIndex()); - assertEquals("roll", ((ListReplaceEvent) this.event1).getNewItems().iterator().next()); - assertEquals(replacedName, ((ListReplaceEvent) this.event1).getOldItems().iterator().next()); - namesChanged = this.subject1Names(); - namesChanged.set(0, "jelly"); - namesChanged.set(1, "roll"); - assertEquals(namesChanged, CollectionTools.list(this.aa1.listIterator())); - } - - public void testListChange() { - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - assertNull(this.event1); - - this.subject1.addTwoNames("jam", "jaz"); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - List<String> namesPlus2 = this.subject1Names(); - namesPlus2.add(0, "jaz"); - namesPlus2.add(0, "jam"); - assertEquals(namesPlus2, CollectionTools.list(this.aa1.listIterator())); - } - - public void testIterator() { - assertEquals(this.subject1Names(), CollectionTools.list(this.subject1.names())); - assertEquals(this.subject1Names(), CollectionTools.list(this.aa1.listIterator())); - } - - public void testGet() { - assertEquals(this.subject1Names().get(0), this.subject1.getName(0)); - assertEquals(this.subject1Names().get(0), this.aa1.get(0)); - } - - public void testSize() { - assertEquals(this.subject1Names().size(), CollectionTools.size(this.subject1.names())); - assertEquals(this.subject1Names().size(), CollectionTools.size(this.aa1.listIterator())); - } - - public void testHasListeners() { - assertTrue(this.aa1.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.subject1.hasAnyListChangeListeners(TestSubject.NAMES_LIST)); - this.aa1.removeListChangeListener(ListValueModel.LIST_VALUES, this.listener1); - assertFalse(this.subject1.hasAnyListChangeListeners(TestSubject.NAMES_LIST)); - assertFalse(this.aa1.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener listener2 = new ChangeAdapter(); - this.aa1.addChangeListener(listener2); - assertTrue(this.aa1.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.subject1.hasAnyListChangeListeners(TestSubject.NAMES_LIST)); - this.aa1.removeChangeListener(listener2); - assertFalse(this.subject1.hasAnyListChangeListeners(TestSubject.NAMES_LIST)); - assertFalse(this.aa1.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - - // ********** inner class ********** - - class TestSubject extends AbstractModel { - private List<String> names; - public static final String NAMES_LIST = "names"; - private List<String> descriptions; - public static final String DESCRIPTIONS_LIST = "descriptions"; - - public TestSubject() { - this.names = new ArrayList<String>(); - this.descriptions = new ArrayList<String>(); - } - public ListIterator<String> names() { - return new ReadOnlyListIterator<String>(this.names); - } - public String getName(int index) { - return this.names.get(index); - } - public void addName(int index, String name) { - this.names.add(index, name); - this.fireItemAdded(NAMES_LIST, index, name); - } - public void addName(String name) { - this.addName(this.names.size(), name); - } - public void addNames(ListIterator<String> newNames) { - while (newNames.hasNext()) { - this.addName(newNames.next()); - } - } - public void addNames(List<String> newNames) { - this.addNames(newNames.listIterator()); - } - public void addTwoNames(String name1, String name2) { - this.names.add(0, name2); - this.names.add(0, name1); - this.fireListChanged(NAMES_LIST, this.names); - } - public String removeName(int index) { - String removedName = this.names.remove(index); - this.fireItemRemoved(NAMES_LIST, index, removedName); - return removedName; - } - public String setName(int index, String name) { - String replacedName = this.names.set(index, name); - this.fireItemReplaced(NAMES_LIST, index, name, replacedName); - return replacedName; - } - public ListIterator<String> descriptions() { - return new ReadOnlyListIterator<String>(this.descriptions); - } - public String getDescription(int index) { - return this.descriptions.get(index); - } - public void addDescription(int index, String description) { - this.descriptions.add(index, description); - this.fireItemAdded(DESCRIPTIONS_LIST, index, description); - } - public void addDescription(String description) { - this.addDescription(this.descriptions.size(), description); - } - public void addDescriptions(ListIterator<String> newDescriptions) { - while (newDescriptions.hasNext()) { - this.addDescription(newDescriptions.next()); - } - } - public void addDescriptions(List<String> newDescriptions) { - this.addDescriptions(newDescriptions.listIterator()); - } - public String removeDescription(int index) { - String removedDescription = this.descriptions.remove(index); - this.fireItemRemoved(DESCRIPTIONS_LIST, index, removedDescription); - return removedDescription; - } - public String setDescription(int index, String description) { - String replacedDescription = this.descriptions.set(index, description); - this.fireItemReplaced(DESCRIPTIONS_LIST, index, description, replacedDescription); - return replacedDescription; - } - } - - - // this is not a typical aspect adapter - the value is determined by the aspect name - class LocalListAspectAdapter extends ListAspectAdapter<TestSubject, String> { - - LocalListAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - super(subjectHolder, TestSubject.NAMES_LIST); - } - - @Override - protected ListIterator<String> listIterator_() { - if (this.aspectNames[0] == TestSubject.NAMES_LIST) { - return this.subject.names(); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_LIST) { - return this.subject.descriptions(); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - - public void add(int index, Object item) { - if (this.aspectNames[0] == TestSubject.NAMES_LIST) { - this.subject.addName(index, (String) item); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_LIST) { - this.subject.addDescription(index, (String) item); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - - public void addAll(int index, List<String> items) { - for (int i = 0; i < items.size(); i++) { - this.add(index + i, items.get(i)); - } - } - - public String remove(int index) { - if (this.aspectNames[0] == TestSubject.NAMES_LIST) { - return this.subject.removeName(index); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_LIST) { - return this.subject.removeDescription(index); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - - public List<String> remove(int index, int length) { - List<String> removedItems = new ArrayList<String>(length); - for (int i = 0; i < length; i++) { - removedItems.add(this.remove(index)); - } - return removedItems; - } - - public Object replace(int index, Object item) { - if (this.aspectNames[0] == TestSubject.NAMES_LIST) { - return this.subject.setName(index, (String) item); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTIONS_LIST) { - return this.subject.setDescription(index, (String) item); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListCollectionValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListCollectionValueModelAdapterTests.java deleted file mode 100644 index c499ad37ab..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListCollectionValueModelAdapterTests.java +++ /dev/null @@ -1,282 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.swing.JList; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ListCollectionValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ListCollectionValueModelAdapterTests extends TestCase { - CollectionValueModel<String> adapter; - private SimpleListValueModel<String> wrappedListHolder; - private List<String> wrappedList; - - public ListCollectionValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.wrappedList = new ArrayList<String>(); - this.wrappedListHolder = new SimpleListValueModel<String>(this.wrappedList); - this.adapter = new ListCollectionValueModelAdapter<String>(this.wrappedListHolder); - } - - private Collection<String> wrappedCollection() { - return CollectionTools.collection(this.wrappedList.iterator()); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) { - // override failure - } - }); - this.wrappedListHolder.add(0, "foo"); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - } - - public void testStaleValues() { - CollectionChangeListener listener = new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - }; - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - this.wrappedListHolder.add(0, "foo"); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - - this.adapter.removeCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(0, adapterCollection.size()); - assertEquals(new HashBag<String>(), adapterCollection); - - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - } - - public void testAdd() { - Bag<String> synchCollection = new CoordinatedBag<String>(this.adapter); - List<String> synchList = new CoordinatedList<String>(this.wrappedListHolder); - this.wrappedListHolder.add(0, "foo"); - assertTrue(this.wrappedList.contains("foo")); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - this.wrappedListHolder.add(3, "joo"); - this.wrappedListHolder.add(4, "jar"); - this.wrappedListHolder.add(5, "jaz"); - assertEquals(6, this.wrappedList.size()); - - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals(this.wrappedCollection(), CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection(), synchCollection); - } - - public void testRemove() { - Bag<String> synchCollection = new CoordinatedBag<String>(this.adapter); - List<String> synchList = new CoordinatedList<String>(this.wrappedListHolder); - this.wrappedListHolder.add(0, "foo"); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - this.wrappedListHolder.add(3, "joo"); - this.wrappedListHolder.add(4, "jar"); - this.wrappedListHolder.add(5, "jaz"); - assertEquals("jaz", this.wrappedListHolder.remove(5)); - assertFalse(this.wrappedList.contains("jaz")); - assertEquals("foo", this.wrappedListHolder.remove(0)); - assertFalse(this.wrappedList.contains("foo")); - assertEquals(4, this.wrappedList.size()); - - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals(this.wrappedCollection(), CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection(), synchCollection); - } - - public void testListSynch() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) { - // override failure - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - // override failure - } - }); - this.wrappedListHolder.add(0, "foo"); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - this.wrappedListHolder.add(3, "joo"); - this.wrappedListHolder.add(4, "jar"); - this.wrappedListHolder.add(5, "jaz"); - this.wrappedListHolder.remove(5); - assertFalse(this.wrappedList.contains("jaz")); - this.wrappedListHolder.remove(0); - assertFalse(this.wrappedList.contains("foo")); - assertEquals(4, this.wrappedList.size()); - - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(this.wrappedCollection(), adapterCollection); - } - - public void testReplace() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) { - // override failure - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - // override failure - } - }); - this.wrappedListHolder.add(0, "foo"); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(3, adapterCollection.size()); - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - assertEquals("foo", e.getItems().iterator().next()); - assertFalse(CollectionTools.contains(ListCollectionValueModelAdapterTests.this.adapter.iterator(), "joo")); - assertEquals(2, ListCollectionValueModelAdapterTests.this.adapter.size()); - } - @Override - public void itemsAdded(CollectionAddEvent e) { - assertEquals("joo", e.getItems().iterator().next()); - assertEquals(3, ListCollectionValueModelAdapterTests.this.adapter.size()); - } - }); - this.wrappedListHolder.set(0, "joo"); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(3, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - CoordinatedBag<String> synchCollection = new CoordinatedBag<String>(this.adapter); - assertTrue(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.adapter.removeCollectionChangeListener(CollectionValueModel.VALUES, synchCollection); - assertFalse(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - ChangeListener cl = new ChangeAdapter(); - this.adapter.addChangeListener(cl); - assertTrue(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.adapter.removeChangeListener(cl); - assertFalse(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - public void testListChangedToEmpty() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - @Override - public void collectionCleared(CollectionClearEvent e) {/* OK */} - }); - this.wrappedListHolder.add(0, "foo"); - this.wrappedListHolder.add(1, "bar"); - this.wrappedListHolder.add(2, "baz"); - JList jList = new JList(new ListModelAdapter(this.adapter)); - this.wrappedListHolder.setListValues(new ArrayList<String>()); - assertEquals(0, jList.getModel().getSize()); - } - - public void testCollectionChangedFromEmpty() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - @Override - public void itemsRemoved(CollectionRemoveEvent e) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - ArrayList<String> list = new ArrayList<String>(); - list.add("foo"); - list.add("bar"); - this.wrappedListHolder.setListValues(list); - assertEquals(2, jList.getModel().getSize()); - } - - public void testCollectionChangedFromEmptyToEmpty() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - @Override - public void itemsRemoved(CollectionRemoveEvent e) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - ArrayList<String> list = new ArrayList<String>(); - this.wrappedListHolder.setListValues(list); - assertEquals(0, jList.getModel().getSize()); - } - - - // ********** inner class ********** - - class TestListener implements CollectionChangeListener { - public void itemsAdded(CollectionAddEvent e) { - fail("unexpected event"); - } - public void itemsRemoved(CollectionRemoveEvent e) { - fail("unexpected event"); - } - public void collectionCleared(CollectionClearEvent e) { - fail("unexpected event"); - } - public void collectionChanged(CollectionChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListCuratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListCuratorTests.java deleted file mode 100644 index e4dc5f5507..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ListCuratorTests.java +++ /dev/null @@ -1,348 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyListIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ListCurator; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public final class ListCuratorTests - extends TestCase -{ - private TestSubject subject1; - private ModifiablePropertyValueModel<TestSubject> subjectHolder1; - - private ListCurator<TestSubject, String> curator; - private ListChangeListener listener1; - private ListEvent event1; - - private TestSubject subject2; - - public ListCuratorTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.subject1 = new TestSubject(this.subject1Names()); - this.subjectHolder1 = new SimplePropertyValueModel<TestSubject>(this.subject1); - this.curator = this.buildListCurator(this.subjectHolder1); - this.listener1 = this.buildListChangeListener1(); - this.curator.addListChangeListener(ListValueModel.LIST_VALUES, this.listener1); - this.event1 = null; - - this.subject2 = new TestSubject(this.subject2Names()); - } - - private List<String> subject1Names() { - ArrayList<String> list = new ArrayList<String>(); - list.add("alpha"); - list.add("bravo"); - list.add("charlie"); - list.add("delta"); - return list; - } - - private List<String> subject2Names() { - ArrayList<String> list = new ArrayList<String>(); - list.add("echo"); - list.add("foxtrot"); - list.add("glove"); - list.add("hotel"); - return list; - } - - private ListCurator<TestSubject, String> buildListCurator(PropertyValueModel<TestSubject> subjectHolder) { - return new ListCurator<TestSubject, String>(subjectHolder) { - @Override - public Iterator<String> iteratorForRecord() { - return this.subject.strings(); - } - }; - } - - private ListChangeListener buildListChangeListener1() { - return new ListChangeListener() { - public void itemsAdded(ListAddEvent e) { - ListCuratorTests.this.value1Changed(e); - } - public void itemsRemoved(ListRemoveEvent e) { - ListCuratorTests.this.value1Changed(e); - } - public void itemsReplaced(ListReplaceEvent e) { - ListCuratorTests.this.value1Changed(e); - } - public void itemsMoved(ListMoveEvent e) { - ListCuratorTests.this.value1Changed(e); - } - public void listCleared(ListClearEvent e) { - ListCuratorTests.this.value1Changed(e); - } - public void listChanged(ListChangeEvent e) { - ListCuratorTests.this.value1Changed(e); - } - }; - } - - void value1Changed(ListEvent e) { - this.event1 = e; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSubjectHolder() { - assertEquals(this.subject1Names(), CollectionTools.list(this.curator.listIterator())); - assertNull(this.event1); - - this.subjectHolder1.setValue(this.subject2); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject2Names(), CollectionTools.list(this.curator.listIterator())); - - this.event1 = null; - this.subjectHolder1.setValue(null); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertFalse(this.curator.iterator().hasNext()); - - this.event1 = null; - this.subjectHolder1.setValue(this.subject1); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject1Names(), CollectionTools.list(this.curator.listIterator())); - } - - public void testAdd() { - assertEquals(this.subject1Names(), CollectionTools.list(this.curator.listIterator())); - assertNull(this.event1); - - this.subject1.addString("echo"); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject1Names().size(), ((ListAddEvent) this.event1).getIndex()); - assertEquals("echo", ((ListAddEvent) this.event1).getItems().iterator().next()); - List<String> stringsPlus = this.subject1Names(); - stringsPlus.add("echo"); - assertEquals(stringsPlus, CollectionTools.list(this.curator.listIterator())); - - this.event1 = null; - this.subject1.addString(0, "zulu"); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(0, ((ListAddEvent) this.event1).getIndex()); - assertEquals("zulu", ((ListAddEvent) this.event1).getItems().iterator().next()); - stringsPlus.add(0, "zulu"); - assertEquals(stringsPlus, CollectionTools.list(this.curator.listIterator())); - } - - public void testRemove() { - assertEquals(this.subject1Names(), CollectionTools.list(this.curator.listIterator())); - assertNull(this.event1); - - String removedString = this.subject1.removeString(0); // should be "alpha" - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(0, ((ListRemoveEvent) this.event1).getIndex()); - assertEquals(removedString, ((ListRemoveEvent) this.event1).getItems().iterator().next()); - List<String> stringsMinus = this.subject1Names(); - stringsMinus.remove(0); - assertEquals(stringsMinus, CollectionTools.list(this.curator.listIterator())); - - removedString = this.subject1.removeString(2); // should be "delta" - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(2, ((ListRemoveEvent) this.event1).getIndex()); - assertEquals(removedString, ((ListRemoveEvent) this.event1).getItems().iterator().next()); - stringsMinus.remove(2); - assertEquals(stringsMinus, CollectionTools.list(this.curator.listIterator())); - } - - public void testCompleteListChange() { - assertEquals(this.subject1Names(), CollectionTools.list(this.curator.listIterator())); - assertNull(this.event1); - - this.subject1.setStrings(this.subject2Names()); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - List<String> newStrings = this.subject2Names(); - assertEquals(newStrings, CollectionTools.list(this.curator.listIterator())); - } - - public void testPartialListChange() { - List<String> startingList = CollectionTools.list(this.curator.listIterator()); - assertEquals(this.subject1Names(), startingList); - assertNull(this.event1); - - String identicalString = startingList.get(1); // should be "bravo" - String nonidenticalString = startingList.get(0); // should be "alpha" - List<String> newStrings = CollectionTools.list(new String[] {new String("bravo"), new String("alpha"), "echo", "delta", "foxtrot"}); - this.subject1.setStrings(newStrings); - - List<String> finalList = CollectionTools.list(this.curator.listIterator()); - assertNotNull(this.event1); - assertEquals(this.curator, this.event1.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(newStrings, finalList); - assertTrue(identicalString == finalList.get(0)); - assertTrue(nonidenticalString != finalList.get(1)); - } - - public void testIterator() { - assertEquals(this.subject1Names(), CollectionTools.list(this.subject1.strings())); - assertEquals(this.subject1Names(), CollectionTools.list(this.curator.listIterator())); - } - - public void testGet() { - assertEquals(this.subject1Names().get(0), this.subject1.getString(0)); - assertEquals(this.subject1Names().get(0), this.curator.get(0)); - } - - public void testSize() { - assertEquals(this.subject1Names().size(), CollectionTools.size(this.subject1.strings())); - assertEquals(this.subject1Names().size(), CollectionTools.size(this.curator.listIterator())); - assertEquals(this.subject1Names().size(), this.curator.size()); - } - - public void testHasListeners() { - assertTrue(this.curator.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.subject1.hasAnyStateChangeListeners()); - this.curator.removeListChangeListener(ListValueModel.LIST_VALUES, this.listener1); - assertFalse(this.subject1.hasAnyStateChangeListeners()); - assertFalse(this.curator.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener listener2 = this.buildChangeListener(); - this.curator.addChangeListener(listener2); - assertTrue(this.curator.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(this.subject1.hasAnyStateChangeListeners()); - this.curator.removeChangeListener(listener2); - assertFalse(this.subject1.hasAnyStateChangeListeners()); - assertFalse(this.curator.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(ListAddEvent e) { - ListCuratorTests.this.value1Changed(e); - } - @Override - public void itemsRemoved(ListRemoveEvent e) { - ListCuratorTests.this.value1Changed(e); - } - @Override - public void itemsReplaced(ListReplaceEvent e) { - ListCuratorTests.this.value1Changed(e); - } - @Override - public void itemsMoved(ListMoveEvent e) { - ListCuratorTests.this.value1Changed(e); - } - @Override - public void listCleared(ListClearEvent e) { - ListCuratorTests.this.value1Changed(e); - } - @Override - public void listChanged(ListChangeEvent e) { - ListCuratorTests.this.value1Changed(e); - } - }; - } - - - // **************** Inner Class ******************************************* - - class TestSubject extends AbstractModel { - private List<String> strings; - - public TestSubject() { - this.strings = new ArrayList<String>(); - } - - public TestSubject(List<String> strings) { - this(); - this.setStrings(strings); - } - - public String getString(int index) { - return this.strings.get(index); - } - - public ListIterator<String> strings() { - return new ReadOnlyListIterator<String>(this.strings); - } - - public void addString(int index, String string) { - this.strings.add(index, string); - this.fireStateChanged(); - } - - public void addString(String string) { - this.addString(this.strings.size(), string); - } - - public String removeString(int index) { - String string = this.strings.get(index); - this.removeString(string); - return string; - } - - public void removeString(String string) { - this.strings.remove(string); - this.fireStateChanged(); - } - - public void setStrings(List<String> strings) { - this.strings = new ArrayList<String>(strings); - this.fireStateChanged(); - } - - public void setStrings(String[] strings) { - this.strings = CollectionTools.list(strings); - this.fireStateChanged(); - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullCollectionValueModelTests.java deleted file mode 100644 index 786bd931eb..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullCollectionValueModelTests.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.NullCollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class NullCollectionValueModelTests extends TestCase { - private CollectionValueModel<Object> collectionHolder; - - public NullCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.collectionHolder = new NullCollectionValueModel<Object>(); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSize() { - assertEquals(0, this.collectionHolder.size()); - } - - public void testIterator() { - assertFalse(this.collectionHolder.iterator().hasNext()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullListValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullListValueModelTests.java deleted file mode 100644 index 63ba4ac5cf..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullListValueModelTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.NullListValueModel; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class NullListValueModelTests extends TestCase { - private ListValueModel<Object> listHolder; - - public NullListValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.listHolder = new NullListValueModel<Object>(); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGet() { - boolean exCaught = false; - try { - this.listHolder.get(0); - } catch (IndexOutOfBoundsException ex) { - exCaught = true; - } - assertTrue(exCaught); - } - - public void testSize() { - assertEquals(0, this.listHolder.size()); - } - - public void testIterator() { - assertFalse(this.listHolder.iterator().hasNext()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullPropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullPropertyValueModelTests.java deleted file mode 100644 index eaf6422b9b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/NullPropertyValueModelTests.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.NullPropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -public class NullPropertyValueModelTests extends TestCase { - private PropertyValueModel<Object> valueHolder; - - public NullPropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.valueHolder = new NullPropertyValueModel<Object>(); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - assertNull(this.valueHolder.getValue()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyAspectAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyAspectAdapterTests.java deleted file mode 100644 index 6f5eaca4ba..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyAspectAdapterTests.java +++ /dev/null @@ -1,343 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class PropertyAspectAdapterTests extends TestCase { - private TestSubject subject1; - private ModifiablePropertyValueModel<TestSubject> subjectHolder1; - private PropertyAspectAdapter<TestSubject, String> aa1; - private PropertyChangeEvent event1; - private PropertyChangeListener listener1; - - private TestSubject subject2; - - private PropertyChangeEvent multipleValueEvent; - - private PropertyChangeEvent customValueEvent; - - - public PropertyAspectAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.subject1 = new TestSubject("foo", "test subject 1"); - this.subjectHolder1 = new SimplePropertyValueModel<TestSubject> (this.subject1); - this.aa1 = this.buildAspectAdapter(this.subjectHolder1); - this.listener1 = this.buildValueChangeListener1(); - this.aa1.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener1); - this.event1 = null; - - this.subject2 = new TestSubject("bar", "test subject 2"); - } - - private PropertyAspectAdapter<TestSubject, String> buildAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - return new PropertyAspectAdapter<TestSubject, String>(subjectHolder, TestSubject.NAME_PROPERTY) { - // this is not a aspect adapter - the value is determined by the aspect name - @Override - protected String buildValue_() { - if (this.aspectNames[0] == TestSubject.NAME_PROPERTY) { - return this.subject.getName(); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTION_PROPERTY) { - return this.subject.getDescription(); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - @Override - protected void setValue_(String value) { - if (this.aspectNames[0] == TestSubject.NAME_PROPERTY) { - this.subject.setName(value); - } else if (this.aspectNames[0] == TestSubject.DESCRIPTION_PROPERTY) { - this.subject.setDescription(value); - } else { - throw new IllegalStateException("invalid aspect name: " + this.aspectNames[0]); - } - } - }; - } - - private ChangeListener buildValueChangeListener1() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - PropertyAspectAdapterTests.this.value1Changed(e); - } - }; - } - - void value1Changed(PropertyChangeEvent e) { - this.event1 = e; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSubjectHolder() { - assertEquals("foo", this.aa1.getValue()); - assertNull(this.event1); - - this.subjectHolder1.setValue(this.subject2); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event1.getPropertyName()); - assertEquals("foo", this.event1.getOldValue()); - assertEquals("bar", this.event1.getNewValue()); - assertEquals("bar", this.aa1.getValue()); - - this.event1 = null; - this.subjectHolder1.setValue(null); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event1.getPropertyName()); - assertEquals("bar", this.event1.getOldValue()); - assertNull(this.event1.getNewValue()); - assertNull(this.aa1.getValue()); - - this.event1 = null; - this.subjectHolder1.setValue(this.subject1); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event1.getPropertyName()); - assertEquals(null, this.event1.getOldValue()); - assertEquals("foo", this.event1.getNewValue()); - assertEquals("foo", this.aa1.getValue()); - } - - public void testPropertyChange() { - assertEquals("foo", this.aa1.getValue()); - assertNull(this.event1); - - this.subject1.setName("baz"); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event1.getPropertyName()); - assertEquals("foo", this.event1.getOldValue()); - assertEquals("baz", this.event1.getNewValue()); - assertEquals("baz", this.aa1.getValue()); - - this.event1 = null; - this.subject1.setName(null); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event1.getPropertyName()); - assertEquals("baz", this.event1.getOldValue()); - assertEquals(null, this.event1.getNewValue()); - assertEquals(null, this.aa1.getValue()); - - this.event1 = null; - this.subject1.setName("foo"); - assertNotNull(this.event1); - assertEquals(this.aa1, this.event1.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event1.getPropertyName()); - assertEquals(null, this.event1.getOldValue()); - assertEquals("foo", this.event1.getNewValue()); - assertEquals("foo", this.aa1.getValue()); - } - - public void testValue() { - assertEquals("foo", this.subject1.getName()); - assertEquals("foo", this.aa1.getValue()); - } - - public void testStaleValue() { - assertEquals("foo", this.subject1.getName()); - assertEquals("foo", this.aa1.getValue()); - - this.aa1.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener1); - assertEquals(null, this.aa1.getValue()); - - this.aa1.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener1); - assertEquals("foo", this.aa1.getValue()); - - this.aa1.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener1); - this.subjectHolder1.setValue(this.subject2); - assertEquals(null, this.aa1.getValue()); - - this.aa1.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener1); - assertEquals("bar", this.aa1.getValue()); - } - - public void testSetValue() { - this.aa1.setValue("baz"); - assertEquals("baz", this.aa1.getValue()); - assertEquals("baz", this.subject1.getName()); - } - - public void testHasListeners() { - assertTrue(this.aa1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.subject1.hasAnyPropertyChangeListeners(TestSubject.NAME_PROPERTY)); - this.aa1.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener1); - assertFalse(this.subject1.hasAnyPropertyChangeListeners(TestSubject.NAME_PROPERTY)); - assertFalse(this.aa1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - ChangeListener listener2 = this.buildValueChangeListener1(); - this.aa1.addChangeListener(listener2); - assertTrue(this.aa1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.subject1.hasAnyPropertyChangeListeners(TestSubject.NAME_PROPERTY)); - this.aa1.removeChangeListener(listener2); - assertFalse(this.subject1.hasAnyPropertyChangeListeners(TestSubject.NAME_PROPERTY)); - assertFalse(this.aa1.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testMultipleAspectAdapter() { - TestSubject testSubject = new TestSubject("fred", "husband"); - ModifiablePropertyValueModel<TestSubject> testSubjectHolder = new SimplePropertyValueModel<TestSubject>(testSubject); - ModifiablePropertyValueModel<String> testAA = this.buildMultipleAspectAdapter(testSubjectHolder); - PropertyChangeListener testListener = this.buildMultipleValueChangeListener(); - testAA.addPropertyChangeListener(PropertyValueModel.VALUE, testListener); - assertEquals("fred:husband", testAA.getValue()); - - this.multipleValueEvent = null; - testSubject.setName("wilma"); - assertEquals("wilma:husband", testAA.getValue()); - assertEquals("fred:husband", this.multipleValueEvent.getOldValue()); - assertEquals("wilma:husband", this.multipleValueEvent.getNewValue()); - - this.multipleValueEvent = null; - testSubject.setDescription("wife"); - assertEquals("wilma:wife", testAA.getValue()); - assertEquals("wilma:husband", this.multipleValueEvent.getOldValue()); - assertEquals("wilma:wife", this.multipleValueEvent.getNewValue()); - } - - private ModifiablePropertyValueModel<String> buildMultipleAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - return new PropertyAspectAdapter<TestSubject, String>(subjectHolder, TestSubject.NAME_PROPERTY, TestSubject.DESCRIPTION_PROPERTY) { - @Override - protected String buildValue_() { - return this.subject.getName() + ":" + this.subject.getDescription(); - } - }; - } - - private PropertyChangeListener buildMultipleValueChangeListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - PropertyAspectAdapterTests.this.multipleValueChanged(e); - } - }; - } - - void multipleValueChanged(PropertyChangeEvent e) { - this.multipleValueEvent = e; - } - - /** - * test a bug where we would call #buildValue() in - * #engageNonNullSubject(), when we needed to call - * it in #engageSubject(), so the cached value would - * be rebuilt when the this.subject was set to null - */ - public void testCustomBuildValueWithNullSubject() { - TestSubject customSubject = new TestSubject("fred", "laborer"); - ModifiablePropertyValueModel<TestSubject> customSubjectHolder = new SimplePropertyValueModel<TestSubject>(customSubject); - ModifiablePropertyValueModel<String> customAA = this.buildCustomAspectAdapter(customSubjectHolder); - PropertyChangeListener customListener = this.buildCustomValueChangeListener(); - customAA.addPropertyChangeListener(PropertyValueModel.VALUE, customListener); - assertEquals("fred", customAA.getValue()); - - this.customValueEvent = null; - customSubject.setName("wilma"); - assertEquals("wilma", customAA.getValue()); - assertEquals("fred", this.customValueEvent.getOldValue()); - assertEquals("wilma", this.customValueEvent.getNewValue()); - - this.customValueEvent = null; - customSubjectHolder.setValue(null); - // this would fail - the value would be null... - assertEquals("<unnamed>", customAA.getValue()); - assertEquals("wilma", this.customValueEvent.getOldValue()); - assertEquals("<unnamed>", this.customValueEvent.getNewValue()); - } - - /** - * Test a bug: - * If two listeners were added to an aspect adapter, one with an - * aspect name and one without, the aspect adapter would add its - * 'subjectChangeListener' to its 'subjectHolder' twice. As a result, - * the following code will trigger an IllegalArgumentException - * if the bug is present; otherwise, it completes silently. - */ - public void testDuplicateListener() { - ChangeListener listener2 = new ChangeAdapter(); - this.aa1.addChangeListener(listener2); - } - - private ModifiablePropertyValueModel<String> buildCustomAspectAdapter(PropertyValueModel<TestSubject> subjectHolder) { - return new PropertyAspectAdapter<TestSubject, String>(subjectHolder, TestSubject.NAME_PROPERTY) { - @Override - protected String buildValue() { - return (this.subject == null) ? "<unnamed>" : this.subject.getName(); - } - }; - } - - private PropertyChangeListener buildCustomValueChangeListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - PropertyAspectAdapterTests.this.customValueChanged(e); - } - }; - } - - void customValueChanged(PropertyChangeEvent e) { - this.customValueEvent = e; - } - - - // ********** test model ********** - - private static class TestSubject extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - private String description; - public static final String DESCRIPTION_PROPERTY = "description"; - - public TestSubject(String name, String description) { - this.name = name; - this.description = description; - } - public String getName() { - return this.name; - } - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - public String getDescription() { - return this.description; - } - public void setDescription(String description) { - Object old = this.description; - this.description = description; - this.firePropertyChanged(DESCRIPTION_PROPERTY, old, description); - } - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyCollectionValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyCollectionValueModelAdapterTests.java deleted file mode 100644 index aacfa746c7..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyCollectionValueModelAdapterTests.java +++ /dev/null @@ -1,162 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; - -import javax.swing.JList; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.iterators.SingleElementIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyCollectionValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class PropertyCollectionValueModelAdapterTests extends TestCase { - private CollectionValueModel<String> adapter; - private ModifiablePropertyValueModel<String> wrappedValueHolder; - - public PropertyCollectionValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.wrappedValueHolder = new SimplePropertyValueModel<String>(); - this.adapter = new PropertyCollectionValueModelAdapter<String>(this.wrappedValueHolder); - } - - private Collection<String> wrappedCollection() { - return CollectionTools.collection(new SingleElementIterator<String>(this.wrappedValueHolder.getValue())); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - }); - this.wrappedValueHolder.setValue("foo"); - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(1, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals("foo", adapterCollection.iterator().next()); - } - - public void testStaleValue() { - CollectionChangeListener listener = new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - }; - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - this.wrappedValueHolder.setValue("foo"); - Collection<String> adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(1, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals("foo", adapterCollection.iterator().next()); - - this.adapter.removeCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(0, adapterCollection.size()); - assertEquals(new HashBag<String>(), adapterCollection); - - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); - assertEquals(1, adapterCollection.size()); - assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals("foo", adapterCollection.iterator().next()); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - CoordinatedBag<String> synchCollection = new CoordinatedBag<String>(this.adapter); - assertTrue(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.adapter.removeCollectionChangeListener(CollectionValueModel.VALUES, synchCollection); - assertFalse(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - ChangeListener cl = new ChangeAdapter(); - this.adapter.addChangeListener(cl); - assertTrue(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.adapter.removeChangeListener(cl); - assertFalse(((AbstractModel) this.adapter).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - public void testListChangedToEmpty() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - @Override - public void itemsRemoved(CollectionRemoveEvent e) {/* OK */} - }); - this.wrappedValueHolder.setValue("foo"); - JList jList = new JList(new ListModelAdapter(this.adapter)); - this.wrappedValueHolder.setValue(null); - assertEquals(0, jList.getModel().getSize()); - } - - public void testCollectionChangedFromEmpty() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { - @Override - public void itemsAdded(CollectionAddEvent e) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - this.wrappedValueHolder.setValue("foo"); - assertEquals(1, jList.getModel().getSize()); - } - - public void testCollectionChangedFromEmptyToEmpty() { - this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener()); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - this.wrappedValueHolder.setValue(null); - assertEquals(0, jList.getModel().getSize()); - } - - - // ********** member class ********** - - static class TestListener implements CollectionChangeListener { - public void collectionChanged(CollectionChangeEvent event) { - fail("unexpected event"); - } - public void collectionCleared(CollectionClearEvent event) { - fail("unexpected event"); - } - public void itemsAdded(CollectionAddEvent event) { - fail("unexpected event"); - } - public void itemsRemoved(CollectionRemoveEvent event) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyListValueModelAdapterTests.java deleted file mode 100644 index e39091c262..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/PropertyListValueModelAdapterTests.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.swing.JList; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.SingleElementIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class PropertyListValueModelAdapterTests extends TestCase { - private ListValueModel<String> adapter; - private ModifiablePropertyValueModel<String> wrappedValueHolder; - - public PropertyListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.wrappedValueHolder = new SimplePropertyValueModel<String>(); - this.adapter = new PropertyListValueModelAdapter<String>(this.wrappedValueHolder); - } - - private Collection<String> wrappedList() { - return CollectionTools.list(new SingleElementIterator<String>(this.wrappedValueHolder.getValue())); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener() { - @Override - public void itemsAdded(ListAddEvent event) {/* OK */} - }); - assertFalse(this.adapter.iterator().hasNext()); - this.wrappedValueHolder.setValue("foo"); - List<String> adapterList = CollectionTools.list(this.adapter.iterator()); - assertEquals(1, adapterList.size()); - assertEquals(this.wrappedList(), adapterList); - assertEquals("foo", adapterList.iterator().next()); - } - - public void testGetInt() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener() { - @Override - public void itemsAdded(ListAddEvent event) {/* OK */} - }); - this.wrappedValueHolder.setValue("foo"); - assertEquals("foo", this.adapter.get(0)); - } - - public void testToArray1() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener() { - @Override - public void itemsAdded(ListAddEvent event) {/* OK */} - }); - this.wrappedValueHolder.setValue("foo"); - Object[] array = this.adapter.toArray(); - assertEquals("foo", array[0]); - assertEquals(1, array.length); - } - - public void testToArray2() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener()); - Object[] array = this.adapter.toArray(); - assertEquals(0, array.length); - } - - public void testStaleValue() { - ListChangeListener listener = new TestListener() { - @Override - public void itemsAdded(ListAddEvent event) {/* OK */} - }; - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, listener); - this.wrappedValueHolder.setValue("foo"); - List<String> adapterList = CollectionTools.list(this.adapter.iterator()); - assertEquals(1, adapterList.size()); - assertEquals(this.wrappedList(), adapterList); - assertEquals("foo", adapterList.iterator().next()); - - this.adapter.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - adapterList = CollectionTools.list(this.adapter.iterator()); - assertEquals(0, adapterList.size()); - assertEquals(new ArrayList<String>(), adapterList); - - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, listener); - adapterList = CollectionTools.list(this.adapter.iterator()); - assertEquals(1, adapterList.size()); - assertEquals(this.wrappedList(), adapterList); - assertEquals("foo", adapterList.iterator().next()); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - CoordinatedList<String> synchList = new CoordinatedList<String>(this.adapter); - assertTrue(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.adapter.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener cl = new ChangeAdapter(); - this.adapter.addChangeListener(cl); - assertTrue(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.adapter.removeChangeListener(cl); - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - public void testListChangedToEmpty() { - this.wrappedValueHolder.setValue("foo"); - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener() { - @Override - public void itemsRemoved(ListRemoveEvent event) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - this.wrappedValueHolder.setValue(null); - assertEquals(0, jList.getModel().getSize()); - } - - public void testListChangedFromEmpty() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener() { - @Override - public void itemsAdded(ListAddEvent event) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - this.wrappedValueHolder.setValue("foo"); - assertEquals(1, jList.getModel().getSize()); - } - - public void testListItemChanged() { - this.wrappedValueHolder.setValue("foo"); - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener() { - @Override - public void itemsReplaced(ListReplaceEvent event) {/* OK */} - }); - JList jList = new JList(new ListModelAdapter(this.adapter)); - assertEquals(1, jList.getModel().getSize()); - assertEquals("foo", jList.getModel().getElementAt(0)); - - this.wrappedValueHolder.setValue("bar"); - assertEquals(1, jList.getModel().getSize()); - assertEquals("bar", jList.getModel().getElementAt(0)); - } - - public void testListChangedFromEmptyToEmpty() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListener()); - JList jList = new JList(new ListModelAdapter(this.adapter)); - - this.wrappedValueHolder.setValue(null); - assertEquals(0, jList.getModel().getSize()); - } - - - // ********** member class ********** - - static class TestListener implements ListChangeListener { - public void listChanged(ListChangeEvent event) { - fail("unexpected event"); - } - public void listCleared(ListClearEvent event) { - fail("unexpected event"); - } - public void itemsAdded(ListAddEvent event) { - fail("unexpected event"); - } - public void itemsRemoved(ListRemoveEvent event) { - fail("unexpected event"); - } - public void itemsMoved(ListMoveEvent event) { - fail("unexpected event"); - } - public void itemsReplaced(ListReplaceEvent event) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ReadOnlyWritablePropertyValueModelWrapperTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ReadOnlyWritablePropertyValueModelWrapperTests.java deleted file mode 100644 index b25ede951c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ReadOnlyWritablePropertyValueModelWrapperTests.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ReadOnlyWritablePropertyValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ReadOnlyWritablePropertyValueModelWrapperTests - extends TestCase -{ - private ModifiablePropertyValueModel<String> objectHolder; - - PropertyChangeEvent event; - - private ModifiablePropertyValueModel<String> wrapperObjectHolder; - - PropertyChangeEvent wrapperEvent; - - - public ReadOnlyWritablePropertyValueModelWrapperTests(String name) { - super(name); - } - - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = new SimplePropertyValueModel<String>("foo"); - this.wrapperObjectHolder = new ReadOnlyWritablePropertyValueModelWrapper<String>(this.objectHolder); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - - public void testValue() { - assertEquals("foo", this.objectHolder.getValue()); - assertEquals("foo", this.wrapperObjectHolder.getValue()); - - this.objectHolder.setValue("bar"); - assertEquals("bar", this.objectHolder.getValue()); - assertEquals("bar", this.wrapperObjectHolder.getValue()); - - this.objectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.wrapperObjectHolder.getValue()); - - this.objectHolder.setValue("foo"); - assertEquals("foo", this.objectHolder.getValue()); - assertEquals("foo", this.wrapperObjectHolder.getValue()); - } - - public void testSetValue() { - boolean exceptionOccurred = false; - try { - this.wrapperObjectHolder.setValue("bar"); - } - catch (UnsupportedOperationException uoe) { - exceptionOccurred = true; - } - - assertTrue(exceptionOccurred); - assertEquals("foo", this.objectHolder.getValue()); - assertEquals("foo", this.wrapperObjectHolder.getValue()); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = buildWrapperListener(); - this.wrapperObjectHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.wrapperObjectHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.wrapperObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.wrapperObjectHolder.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testPropertyChange1() { - this.objectHolder.addChangeListener(this.buildListener()); - this.wrapperObjectHolder.addChangeListener(this.buildWrapperListener()); - this.verifyPropertyChanges(); - } - - public void testPropertyChange2() { - this.objectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.wrapperObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildWrapperListener()); - this.verifyPropertyChanges(); - } - - private void verifyPropertyChanges() { - this.event = null; - this.wrapperEvent = null; - this.objectHolder.setValue("bar"); - verifyEvent(this.event, this.objectHolder, "foo", "bar"); - verifyEvent(this.wrapperEvent, this.wrapperObjectHolder, "foo", "bar"); - - this.event = null; - this.wrapperEvent = null; - this.objectHolder.setValue(null); - verifyEvent(this.event, this.objectHolder, "bar", null); - verifyEvent(this.wrapperEvent, this.wrapperObjectHolder, "bar", null); - - this.event = null; - this.wrapperEvent = null; - this.objectHolder.setValue("foo"); - verifyEvent(this.event, this.objectHolder, null, "foo"); - verifyEvent(this.wrapperEvent, this.wrapperObjectHolder, null, "foo"); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - ReadOnlyWritablePropertyValueModelWrapperTests.this.event = e; - } - }; - } - - private ChangeListener buildWrapperListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - ReadOnlyWritablePropertyValueModelWrapperTests.this.wrapperEvent = e; - } - }; - } - - private void verifyEvent(PropertyChangeEvent e, Object source, Object oldValue, Object newValue) { - assertEquals(source, e.getSource()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - assertEquals(oldValue, e.getOldValue()); - assertEquals(newValue, e.getNewValue()); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SetCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SetCollectionValueModelTests.java deleted file mode 100644 index cddfb7d38b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SetCollectionValueModelTests.java +++ /dev/null @@ -1,328 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SetCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SetCollectionValueModelTests extends TestCase { - private SimpleCollectionValueModel<String> collectionHolder; - CollectionAddEvent addEvent; - CollectionRemoveEvent removeEvent; - CollectionClearEvent collectionClearedEvent; - CollectionChangeEvent collectionChangedEvent; - - private CollectionValueModel<String> setHolder; - CollectionAddEvent setAddEvent; - CollectionRemoveEvent setRemoveEvent; - CollectionClearEvent setClearedEvent; - CollectionChangeEvent setChangedEvent; - - public SetCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.collectionHolder = new SimpleCollectionValueModel<String>(this.buildCollection()); - this.setHolder = new SetCollectionValueModel<String>(this.collectionHolder); - } - - private Collection<String> buildCollection() { - Collection<String> collection = new ArrayList<String>(); - collection.add("foo"); - collection.add("foo"); - return collection; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - // add a listener to "activate" the wrapper - this.setHolder.addChangeListener(this.buildSetChangeListener()); - - this.verify(this.collectionHolder, "foo", "foo"); - this.verify(this.setHolder, "foo"); - - this.collectionHolder.add("bar"); - this.collectionHolder.add("bar"); - this.verify(this.collectionHolder, "foo", "foo", "bar", "bar"); - this.verify(this.setHolder, "foo", "bar"); - - this.collectionHolder.remove("bar"); - this.verify(this.collectionHolder, "foo", "foo", "bar"); - this.verify(this.setHolder, "foo", "bar"); - - this.collectionHolder.remove("bar"); - this.verify(this.collectionHolder, "foo", "foo"); - this.verify(this.setHolder, "foo"); - - this.collectionHolder.remove("foo"); - this.verify(this.collectionHolder, "foo"); - this.verify(this.setHolder, "foo"); - - this.collectionHolder.remove("foo"); - assertFalse(this.collectionHolder.iterator().hasNext()); - assertFalse(this.setHolder.iterator().hasNext()); - } - - public void testSize() { - // add a listener to "activate" the wrapper - this.setHolder.addChangeListener(this.buildSetChangeListener()); - - assertEquals(2, this.collectionHolder.size()); - assertEquals(1, this.setHolder.size()); - - this.collectionHolder.add("bar"); - this.collectionHolder.add("bar"); - assertEquals(4, this.collectionHolder.size()); - assertEquals(2, this.setHolder.size()); - - this.collectionHolder.remove("bar"); - assertEquals(3, this.collectionHolder.size()); - assertEquals(2, this.setHolder.size()); - - this.collectionHolder.remove("bar"); - assertEquals(2, this.collectionHolder.size()); - assertEquals(1, this.setHolder.size()); - - this.collectionHolder.remove("foo"); - assertEquals(1, this.collectionHolder.size()); - assertEquals(1, this.setHolder.size()); - - this.collectionHolder.remove("foo"); - assertEquals(0, this.collectionHolder.size()); - assertEquals(0, this.setHolder.size()); - } - - public void testBulkChange() { - // add a listener to "activate" the wrapper - this.setHolder.addChangeListener(this.buildSetChangeListener()); - - Collection<String> newCollection = new ArrayList<String>(); - newCollection.add("fox"); - newCollection.add("fox"); - newCollection.add("bat"); - - this.collectionHolder.setValues(newCollection); - this.verify(this.collectionHolder, "fox", "fox", "bat"); - this.verify(this.setHolder, "fox", "bat"); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.collectionHolder).hasNoCollectionChangeListeners(CollectionValueModel.VALUES)); - ChangeListener listener = this.buildSetChangeListener(); - this.setHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.collectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.setHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.collectionHolder).hasNoCollectionChangeListeners(CollectionValueModel.VALUES)); - - this.setHolder.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - assertTrue(((AbstractModel) this.collectionHolder).hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - this.setHolder.removeCollectionChangeListener(CollectionValueModel.VALUES, listener); - assertTrue(((AbstractModel) this.collectionHolder).hasNoCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - public void testEvents1() { - this.collectionHolder.addChangeListener(this.buildChangeListener()); - this.setHolder.addChangeListener(this.buildSetChangeListener()); - this.verifyEvents(); - } - - public void testEvents2() { - this.collectionHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildCollectionChangeListener()); - this.setHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildSetCollectionChangeListener()); - this.verifyEvents(); - } - - private void clearEvents() { - this.addEvent = null; - this.removeEvent = null; - this.collectionClearedEvent = null; - this.collectionChangedEvent = null; - this.setAddEvent = null; - this.setRemoveEvent = null; - this.setClearedEvent = null; - this.setChangedEvent = null; - } - - private void verifyEvents() { - this.clearEvents(); - this.collectionHolder.add("bar"); - this.verifyEvent(this.addEvent, this.collectionHolder, "bar"); - this.verifyEvent(this.setAddEvent, this.setHolder, "bar"); - - this.clearEvents(); - this.collectionHolder.remove("foo"); - this.verifyEvent(this.removeEvent, this.collectionHolder, "foo"); - assertNull(this.setRemoveEvent); - - this.clearEvents(); - this.collectionHolder.add("bar"); - this.verifyEvent(this.addEvent, this.collectionHolder, "bar"); - assertNull(this.setAddEvent); - - this.clearEvents(); - this.collectionHolder.remove("foo"); - this.verifyEvent(this.removeEvent, this.collectionHolder, "foo"); - this.verifyEvent(this.setRemoveEvent, this.setHolder, "foo"); - - this.clearEvents(); - this.collectionHolder.add("foo"); - this.verifyEvent(this.addEvent, this.collectionHolder, "foo"); - this.verifyEvent(this.setAddEvent, this.setHolder, "foo"); - - this.clearEvents(); - this.collectionHolder.clear(); - this.verifyEvent(this.collectionClearedEvent, this.collectionHolder); - this.verifyEvent(this.setClearedEvent, this.setHolder); - - this.clearEvents(); - Collection<String> newCollection = new ArrayList<String>(); - newCollection.add("fox"); - newCollection.add("fox"); - newCollection.add("bat"); - newCollection.add("bat"); - newCollection.add("bat"); - this.collectionHolder.setValues(newCollection); - this.verifyEvent(this.collectionChangedEvent, this.collectionHolder, "fox", "fox", "bat", "bat", "bat"); - this.verifyEvent(this.setChangedEvent, this.setHolder, "fox", "bat"); - - } - - private CollectionChangeListener buildCollectionChangeListener() { - return new CollectionChangeListener() { - public void itemsAdded(CollectionAddEvent event) { - SetCollectionValueModelTests.this.addEvent = event; - } - public void itemsRemoved(CollectionRemoveEvent event) { - SetCollectionValueModelTests.this.removeEvent = event; - } - public void collectionCleared(CollectionClearEvent event) { - SetCollectionValueModelTests.this.collectionClearedEvent = event; - } - public void collectionChanged(CollectionChangeEvent event) { - SetCollectionValueModelTests.this.collectionChangedEvent = event; - } - }; - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(CollectionAddEvent event) { - SetCollectionValueModelTests.this.addEvent = event; - } - @Override - public void itemsRemoved(CollectionRemoveEvent event) { - SetCollectionValueModelTests.this.removeEvent = event; - } - @Override - public void collectionCleared(CollectionClearEvent event) { - SetCollectionValueModelTests.this.collectionClearedEvent = event; - } - @Override - public void collectionChanged(CollectionChangeEvent event) { - SetCollectionValueModelTests.this.collectionChangedEvent = event; - } - }; - } - - private CollectionChangeListener buildSetCollectionChangeListener() { - return new CollectionChangeListener() { - public void itemsAdded(CollectionAddEvent event) { - SetCollectionValueModelTests.this.setAddEvent = event; - } - public void itemsRemoved(CollectionRemoveEvent event) { - SetCollectionValueModelTests.this.setRemoveEvent = event; - } - public void collectionCleared(CollectionClearEvent event) { - SetCollectionValueModelTests.this.setClearedEvent = event; - } - public void collectionChanged(CollectionChangeEvent event) { - SetCollectionValueModelTests.this.setChangedEvent = event; - } - }; - } - - private ChangeListener buildSetChangeListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(CollectionAddEvent event) { - SetCollectionValueModelTests.this.setAddEvent = event; - } - @Override - public void itemsRemoved(CollectionRemoveEvent event) { - SetCollectionValueModelTests.this.setRemoveEvent = event; - } - @Override - public void collectionCleared(CollectionClearEvent event) { - SetCollectionValueModelTests.this.setClearedEvent = event; - } - @Override - public void collectionChanged(CollectionChangeEvent event) { - SetCollectionValueModelTests.this.setChangedEvent = event; - } - }; - } - - private void verify(CollectionValueModel<String> cvm, String... expectedItems) { - Bag<String> actual = CollectionTools.bag(cvm); - Bag<String> expected = CollectionTools.bag(expectedItems); - assertEquals(expected, actual); - } - - private void verifyEvent(CollectionAddEvent event, Object source, Object... expectedItems) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - assertEquals(CollectionTools.bag(expectedItems), CollectionTools.bag(event.getItems())); - } - - private void verifyEvent(CollectionRemoveEvent event, Object source, Object... expectedItems) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - assertEquals(CollectionTools.bag(expectedItems), CollectionTools.bag(event.getItems())); - } - - private void verifyEvent(CollectionClearEvent event, Object source) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - } - - private void verifyEvent(CollectionChangeEvent event, Object source, Object... expectedItems) { - assertEquals(source, event.getSource()); - assertEquals(CollectionValueModel.VALUES, event.getCollectionName()); - assertEquals(CollectionTools.bag(expectedItems), CollectionTools.bag(event.getCollection())); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimpleCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimpleCollectionValueModelTests.java deleted file mode 100644 index e3e4a70a58..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimpleCollectionValueModelTests.java +++ /dev/null @@ -1,443 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SimpleCollectionValueModelTests extends TestCase { - private SimpleCollectionValueModel<String> bagHolder; - CollectionEvent bagEvent; - String bagEventType; - - private SimpleCollectionValueModel<String> setHolder; - CollectionEvent setEvent; - String setEventType; - - private static final String ADD = "add"; - private static final String REMOVE = "remove"; - private static final String CHANGE = "change"; - private static final String CLEAR = "clear"; - - - public SimpleCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.bagHolder = new SimpleCollectionValueModel<String>(this.buildBag()); - this.setHolder = new SimpleCollectionValueModel<String>(this.buildSet()); - } - - private Bag<String> buildBag() { - Bag<String> result = new HashBag<String>(); - this.addItemsTo(result); - return result; - } - - private Set<String> buildSet() { - Set<String> result = new HashSet<String>(); - this.addItemsTo(result); - return result; - } - - private void addItemsTo(Collection<String> c) { - c.add("foo"); - c.add("bar"); - c.add("baz"); - } - - private Bag<String> buildAddItems() { - Bag<String> result = new HashBag<String>(); - result.add("joo"); - result.add("jar"); - result.add("jaz"); - return result; - } - - private Bag<String> buildRemoveItems() { - Bag<String> result = new HashBag<String>(); - result.add("foo"); - result.add("baz"); - return result; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - assertEquals(this.buildBag(), CollectionTools.bag(this.bagHolder.iterator())); - assertEquals(this.buildSet(), CollectionTools.set(this.setHolder.iterator())); - } - - public void testSize() { - assertEquals(this.buildBag().size(), CollectionTools.size(this.bagHolder.iterator())); - assertEquals(this.buildSet().size(), CollectionTools.size(this.setHolder.iterator())); - } - - private boolean bagHolderContains(Object item) { - return CollectionTools.contains(this.bagHolder.iterator(), item); - } - - private boolean setHolderContains(Object item) { - return CollectionTools.contains(this.setHolder.iterator(), item); - } - - private boolean bagHolderContainsAll(Collection<String> items) { - return CollectionTools.containsAll(this.bagHolder.iterator(), items); - } - - private boolean setHolderContainsAll(Collection<String> items) { - return CollectionTools.containsAll(this.setHolder.iterator(), items); - } - - private boolean bagHolderContainsAny(Collection<String> items) { - Bag<String> bag = CollectionTools.bag(this.bagHolder.iterator()); - for (String string : items) { - if (bag.contains(string)) { - return true; - } - } - return false; - } - - private boolean setHolderContainsAny(Collection<String> items) { - Set<String> set = CollectionTools.set(this.setHolder.iterator()); - for (String string : items) { - if (set.contains(string)) { - return true; - } - } - return false; - } - - public void testAdd() { - assertFalse(this.bagHolderContains("joo")); - this.bagHolder.add("joo"); - assertTrue(this.bagHolderContains("joo")); - - assertFalse(this.bagHolderContains(null)); - this.bagHolder.add(null); - assertTrue(this.bagHolderContains(null)); - - assertFalse(this.setHolderContains("joo")); - this.setHolder.add("joo"); - assertTrue(this.setHolderContains("joo")); - - assertFalse(this.setHolderContains(null)); - this.setHolder.add(null); - assertTrue(this.setHolderContains(null)); - } - - public void testAddAll() { - assertFalse(this.bagHolderContainsAny(this.buildAddItems())); - this.bagHolder.addAll(this.buildAddItems()); - assertTrue(this.bagHolderContainsAll(this.buildAddItems())); - - assertFalse(this.setHolderContainsAny(this.buildAddItems())); - this.setHolder.addAll(this.buildAddItems()); - assertTrue(this.setHolderContainsAll(this.buildAddItems())); - } - - public void testRemove() { - assertTrue(this.bagHolderContains("bar")); - this.bagHolder.remove("bar"); - assertFalse(this.bagHolderContains("bar")); - - this.bagHolder.add(null); - assertTrue(this.bagHolderContains(null)); - this.bagHolder.remove(null); - assertFalse(this.bagHolderContains(null)); - - assertTrue(this.setHolderContains("bar")); - this.setHolder.remove("bar"); - assertFalse(this.setHolderContains("bar")); - - this.setHolder.add(null); - assertTrue(this.setHolderContains(null)); - this.setHolder.remove(null); - assertFalse(this.setHolderContains(null)); - } - - public void testRemoveAll() { - assertTrue(this.bagHolderContainsAll(this.buildRemoveItems())); - this.bagHolder.removeAll(this.buildRemoveItems()); - assertFalse(this.bagHolderContainsAny(this.buildRemoveItems())); - - assertTrue(this.setHolderContainsAll(this.buildRemoveItems())); - this.setHolder.removeAll(this.buildRemoveItems()); - assertFalse(this.setHolderContainsAny(this.buildRemoveItems())); - } - - public void testSetValues() { - assertTrue(this.bagHolderContains("bar")); - assertFalse(this.bagHolderContains("jar")); - this.bagHolder.setValues(this.buildAddItems()); - assertFalse(this.bagHolderContains("bar")); - assertTrue(this.bagHolderContains("jar")); - - this.bagHolder.add(null); - assertTrue(this.bagHolderContains(null)); - this.bagHolder.remove(null); - assertFalse(this.bagHolderContains(null)); - - this.bagHolder.setValues(new HashBag<String>()); - assertFalse(this.bagHolderContains("jar")); - - assertTrue(this.setHolderContains("bar")); - assertFalse(this.setHolderContains("jar")); - this.setHolder.setValues(this.buildAddItems()); - assertFalse(this.setHolderContains("bar")); - assertTrue(this.setHolderContains("jar")); - - this.setHolder.add(null); - assertTrue(this.setHolderContains(null)); - this.setHolder.remove(null); - assertFalse(this.setHolderContains(null)); - - this.setHolder.setValues(new HashBag<String>()); - assertFalse(this.setHolderContains("jar")); - } - - public void testCollectionChange1() { - this.bagHolder.addChangeListener(this.buildBagListener()); - this.verifyBagChange(); - - this.setHolder.addChangeListener(this.buildSetListener()); - this.verifySetChange(); - } - - public void testCollectionChange2() { - this.bagHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildBagListener()); - this.verifyBagChange(); - - this.setHolder.addCollectionChangeListener(CollectionValueModel.VALUES, this.buildSetListener()); - this.verifySetChange(); - } - - private void verifyBagChange() { - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.add("foo"); - this.verifyBagEvent(ADD, "foo"); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.add("foo"); - this.verifyBagEvent(ADD, "foo"); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.add("joo"); - this.verifyBagEvent(ADD, "joo"); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.add(null); - this.verifyBagEvent(ADD, null); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.add(null); - this.verifyBagEvent(ADD, null); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.remove("joo"); - this.verifyBagEvent(REMOVE, "joo"); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.remove(null); - this.verifyBagEvent(REMOVE, null); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.setValues(this.buildBag()); - this.verifyBagEvent(CHANGE); - - this.bagEvent = null; - this.bagEventType = null; - this.bagHolder.addAll(this.buildBag()); - this.verifyBagEvent(ADD); - assertEquals(this.buildBag(), CollectionTools.bag(((CollectionAddEvent) this.bagEvent).getItems())); - } - - private void verifySetChange() { - this.setEvent = null; - this.setEventType = null; - this.setHolder.add("foo"); - assertNull(this.setEvent); - assertNull(this.setEventType); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.add("joo"); - this.verifySetEvent(ADD, "joo"); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.add("joo"); - assertNull(this.setEvent); - assertNull(this.setEventType); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.add(null); - this.verifySetEvent(ADD, null); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.add(null); - assertNull(this.setEvent); - assertNull(this.setEventType); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.remove("joo"); - this.verifySetEvent(REMOVE, "joo"); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.remove("joo"); - assertNull(this.setEvent); - assertNull(this.setEventType); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.remove(null); - this.verifySetEvent(REMOVE, null); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.setValues(this.buildSet()); - this.verifySetEvent(CHANGE); - - this.setEvent = null; - this.setEventType = null; - this.setHolder.addAll(this.buildSet()); - assertNull(this.setEvent); - assertNull(this.setEventType); - } - - private ChangeListener buildBagListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(CollectionAddEvent e) { - SimpleCollectionValueModelTests.this.bagEventType = ADD; - SimpleCollectionValueModelTests.this.bagEvent = e; - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - SimpleCollectionValueModelTests.this.bagEventType = REMOVE; - SimpleCollectionValueModelTests.this.bagEvent = e; - } - @Override - public void collectionCleared(CollectionClearEvent e) { - SimpleCollectionValueModelTests.this.bagEventType = CLEAR; - SimpleCollectionValueModelTests.this.bagEvent = e; - } - @Override - public void collectionChanged(CollectionChangeEvent e) { - SimpleCollectionValueModelTests.this.bagEventType = CHANGE; - SimpleCollectionValueModelTests.this.bagEvent = e; - } - }; - } - - private ChangeListener buildSetListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(CollectionAddEvent e) { - SimpleCollectionValueModelTests.this.setEventType = ADD; - SimpleCollectionValueModelTests.this.setEvent = e; - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - SimpleCollectionValueModelTests.this.setEventType = REMOVE; - SimpleCollectionValueModelTests.this.setEvent = e; - } - @Override - public void collectionCleared(CollectionClearEvent e) { - SimpleCollectionValueModelTests.this.setEventType = CLEAR; - SimpleCollectionValueModelTests.this.setEvent = e; - } - @Override - public void collectionChanged(CollectionChangeEvent e) { - SimpleCollectionValueModelTests.this.setEventType = CHANGE; - SimpleCollectionValueModelTests.this.setEvent = e; - } - }; - } - - private void verifyBagEvent(String eventType) { - assertEquals(eventType, this.bagEventType); - assertEquals(this.bagHolder, this.bagEvent.getSource()); - assertEquals(CollectionValueModel.VALUES, this.bagEvent.getCollectionName()); - } - - private void verifyBagEvent(String eventType, Object item) { - this.verifyBagEvent(eventType); - assertEquals(item, this.getBagEventItems().iterator().next()); - } - - private Iterable<?> getBagEventItems() { - if (this.bagEvent instanceof CollectionAddEvent) { - return ((CollectionAddEvent) this.bagEvent).getItems(); - } else if (this.bagEvent instanceof CollectionRemoveEvent) { - return ((CollectionRemoveEvent) this.bagEvent).getItems(); - } - throw new IllegalStateException(); - } - - private void verifySetEvent(String eventType) { - assertEquals(eventType, this.setEventType); - assertEquals(this.setHolder, this.setEvent.getSource()); - assertEquals(CollectionValueModel.VALUES, this.setEvent.getCollectionName()); - } - - private void verifySetEvent(String eventType, Object item) { - this.verifySetEvent(eventType); - assertEquals(item, this.getSetEventItems().iterator().next()); - } - - private Iterable<?> getSetEventItems() { - if (this.setEvent instanceof CollectionAddEvent) { - return ((CollectionAddEvent) this.setEvent).getItems(); - } else if (this.setEvent instanceof CollectionRemoveEvent) { - return ((CollectionRemoveEvent) this.setEvent).getItems(); - } - throw new IllegalStateException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimpleListValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimpleListValueModelTests.java deleted file mode 100644 index 50db81128b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimpleListValueModelTests.java +++ /dev/null @@ -1,378 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SimpleListValueModelTests extends TestCase { - private SimpleListValueModel<String> listHolder; - ListEvent event; - String eventType; - - private static final String ADD = "add"; - private static final String REMOVE = "remove"; - private static final String REPLACE = "replace"; - private static final String MOVE = "move"; - private static final String CLEAR = "clear"; - private static final String CHANGE = "change"; - - - public SimpleListValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.listHolder = new SimpleListValueModel<String>(this.buildList()); - } - - private List<String> buildList() { - List<String> result = new ArrayList<String>(); - result.add("foo"); - result.add("bar"); - result.add("baz"); - return result; - } - - private List<String> buildAddList() { - List<String> result = new ArrayList<String>(); - result.add("joo"); - result.add("jar"); - result.add("jaz"); - return result; - } - -// private List<String> buildRemoveList() { -// List<String> result = new ArrayList<String>(); -// result.add("foo"); -// result.add("bar"); -// return result; -// } -// - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - assertEquals(this.buildList(), CollectionTools.list(this.listHolder.iterator())); - } - - public void testListIterator() { - assertEquals(this.buildList(), CollectionTools.list(this.listHolder.listIterator())); - } - - public void testListIteratorInt() { - assertEquals(CollectionTools.list(this.buildList().listIterator(1)), CollectionTools.list(this.listHolder.listIterator(1))); - } - - public void testSize() { - assertEquals(this.buildList().size(), this.listHolder.size()); - } - - private boolean listContains(Object item) { - return CollectionTools.contains(this.listHolder.listIterator(), item); - } - - private boolean listContainsAll(Collection<String> items) { - return CollectionTools.containsAll(this.listHolder.listIterator(), items); - } - - private boolean listContainsAny(Collection<String> items) { - Set<String> set = CollectionTools.set(this.listHolder.iterator()); - for (Iterator<String> stream = items.iterator(); stream.hasNext(); ) { - if (set.contains(stream.next())) { - return true; - } - } - return false; - } - - public void testAddObject() { - assertFalse(this.listContains("joo")); - this.listHolder.add("joo"); - assertTrue(this.listContains("joo")); - - assertFalse(this.listContains(null)); - this.listHolder.add(null); - assertTrue(this.listContains(null)); - } - - public void testAddIntObject() { - assertFalse(this.listContains("joo")); - this.listHolder.add(2, "joo"); - assertTrue(this.listContains("joo")); - - assertFalse(this.listContains(null)); - this.listHolder.add(0, null); - assertTrue(this.listContains(null)); - } - - public void testAddAllCollection() { - assertFalse(this.listContainsAny(this.buildAddList())); - this.listHolder.addAll(this.buildAddList()); - assertTrue(this.listContainsAll(this.buildAddList())); - } - - public void testAddAllIntCollection() { - assertFalse(this.listContainsAny(this.buildAddList())); - this.listHolder.addAll(2, this.buildAddList()); - assertTrue(this.listContainsAll(this.buildAddList())); - } - - public void testClear() { - assertFalse(this.listHolder.isEmpty()); - this.listHolder.clear(); - assertTrue(this.listHolder.isEmpty()); - } - - public void testContainsObject() { - assertTrue(this.listHolder.contains("foo")); - assertFalse(this.listHolder.contains("joo")); - } - - public void testContainsAllCollection() { - Collection<String> c = new ArrayList<String>(); - c.add("foo"); - c.add("bar"); - assertTrue(this.listHolder.containsAll(c)); - - c.add("joo"); - assertFalse(this.listHolder.containsAll(c)); - } - - public void testEquals() { - assertEquals(new SimpleListValueModel<String>(this.buildList()), this.listHolder); - assertFalse(this.listHolder.equals(new SimpleListValueModel<String>(this.buildAddList()))); - assertFalse(this.listHolder.equals(this.buildList())); - assertFalse(this.listHolder.equals(new SimpleListValueModel<String>())); - } - - public void testGetInt() { - assertEquals("foo", this.listHolder.get(0)); - assertEquals("bar", this.listHolder.get(1)); - assertEquals("baz", this.listHolder.get(2)); - } - - public void testHashCode() { - assertEquals(new SimpleListValueModel<String>(this.buildList()).hashCode(), this.listHolder.hashCode()); - } - - public void testIndexOfObject() { - assertEquals(0, this.listHolder.indexOf("foo")); - assertEquals(1, this.listHolder.indexOf("bar")); - assertEquals(2, this.listHolder.indexOf("baz")); - assertEquals(-1, this.listHolder.indexOf("joo")); - } - - public void testLastIndexOfObject() { - assertEquals(0, this.listHolder.lastIndexOf("foo")); - assertEquals(1, this.listHolder.lastIndexOf("bar")); - assertEquals(2, this.listHolder.lastIndexOf("baz")); - assertEquals(-1, this.listHolder.lastIndexOf("joo")); - - this.listHolder.add("foo"); - assertEquals(3, this.listHolder.lastIndexOf("foo")); - } - - public void testIsEmpty() { - assertFalse(this.listHolder.isEmpty()); - this.listHolder.clear(); - assertTrue(this.listHolder.isEmpty()); - } - - public void testRemove() { - assertTrue(this.listContains("bar")); - this.listHolder.remove(this.buildList().indexOf("bar")); - assertFalse(this.listContains("bar")); - - this.listHolder.add(1, null); - assertTrue(this.listContains(null)); - this.listHolder.remove(1); - assertFalse(this.listContains(null)); - } - - public void testSetValues() { - List<String> newList = new ArrayList<String>(); - newList.add("joo"); - newList.add("jar"); - newList.add("jaz"); - - assertTrue(this.listContains("bar")); - assertFalse(this.listContains("jar")); - this.listHolder.setListValues(newList); - assertFalse(this.listContains("bar")); - assertTrue(this.listContains("jar")); - - this.listHolder.add(1, null); - assertTrue(this.listContains(null)); - this.listHolder.remove(1); - assertFalse(this.listContains(null)); - - this.listHolder.setListValues(new ArrayList<String>()); - assertFalse(this.listContains("jar")); - } - - public void testListChange1() { - this.listHolder.addChangeListener(this.buildChangeListener()); - this.verifyListChange(); - } - - public void testListChange2() { - this.listHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - this.verifyListChange(); - } - - private void verifyListChange() { - this.event = null; - this.eventType = null; - this.listHolder.add(1, "joo"); - this.verifyEvent(ADD, 1, "joo"); - - this.event = null; - this.eventType = null; - this.listHolder.add(1, null); - this.verifyEvent(ADD, 1, null); - - this.event = null; - this.eventType = null; - this.listHolder.remove(1); - this.verifyEvent(REMOVE, 1, null); - - this.event = null; - this.eventType = null; - this.listHolder.remove(1); - this.verifyEvent(REMOVE, 1, "joo"); - - this.event = null; - this.eventType = null; - this.listHolder.setListValues(this.buildList()); - this.verifyEvent(CHANGE); - - this.event = null; - this.eventType = null; - this.listHolder.addAll(0, this.buildList()); - this.verifyEvent(ADD); - assertEquals(this.buildList(), CollectionTools.list(((ListAddEvent) this.event).getItems())); - - this.event = null; - this.eventType = null; - this.listHolder.set(0, "joo"); - this.verifyEvent(REPLACE); - assertFalse(CollectionTools.contains(((ListReplaceEvent) this.event).getNewItems(), "foo")); - assertTrue(CollectionTools.contains(((ListReplaceEvent) this.event).getNewItems(), "joo")); - } - - private ListChangeListener buildListener() { - return new ListChangeListener() { - public void itemsAdded(ListAddEvent e) { - SimpleListValueModelTests.this.eventType = ADD; - SimpleListValueModelTests.this.event = e; - } - public void itemsRemoved(ListRemoveEvent e) { - SimpleListValueModelTests.this.eventType = REMOVE; - SimpleListValueModelTests.this.event = e; - } - public void itemsReplaced(ListReplaceEvent e) { - SimpleListValueModelTests.this.eventType = REPLACE; - SimpleListValueModelTests.this.event = e; - } - public void itemsMoved(ListMoveEvent e) { - SimpleListValueModelTests.this.eventType = MOVE; - SimpleListValueModelTests.this.event = e; - } - public void listCleared(ListClearEvent e) { - SimpleListValueModelTests.this.eventType = CLEAR; - SimpleListValueModelTests.this.event = e; - } - public void listChanged(ListChangeEvent e) { - SimpleListValueModelTests.this.eventType = CHANGE; - SimpleListValueModelTests.this.event = e; - } - }; - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(ListAddEvent e) { - SimpleListValueModelTests.this.eventType = ADD; - SimpleListValueModelTests.this.event = e; - } - @Override - public void itemsRemoved(ListRemoveEvent e) { - SimpleListValueModelTests.this.eventType = REMOVE; - SimpleListValueModelTests.this.event = e; - } - @Override - public void itemsReplaced(ListReplaceEvent e) { - SimpleListValueModelTests.this.eventType = REPLACE; - SimpleListValueModelTests.this.event = e; - } - @Override - public void itemsMoved(ListMoveEvent e) { - SimpleListValueModelTests.this.eventType = MOVE; - SimpleListValueModelTests.this.event = e; - } - @Override - public void listCleared(ListClearEvent e) { - SimpleListValueModelTests.this.eventType = CLEAR; - SimpleListValueModelTests.this.event = e; - } - @Override - public void listChanged(ListChangeEvent e) { - SimpleListValueModelTests.this.eventType = CHANGE; - SimpleListValueModelTests.this.event = e; - } - }; - } - - private void verifyEvent(String e) { - assertEquals(e, this.eventType); - assertEquals(this.listHolder, this.event.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event.getListName()); - } - - private void verifyEvent(String e, int index, Object item) { - this.verifyEvent(e); - if (e == ADD) { - assertEquals(index, ((ListAddEvent) this.event).getIndex()); - assertEquals(item, ((ListAddEvent) this.event).getItems().iterator().next()); - } else if (e == REMOVE) { - assertEquals(index, ((ListRemoveEvent) this.event).getIndex()); - assertEquals(item, ((ListRemoveEvent) this.event).getItems().iterator().next()); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimplePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimplePropertyValueModelTests.java deleted file mode 100644 index 07dbebea72..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SimplePropertyValueModelTests.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SimplePropertyValueModelTests extends TestCase { - private ModifiablePropertyValueModel<String> objectHolder; - PropertyChangeEvent event; - - - public SimplePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = new SimplePropertyValueModel<String>("foo"); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - assertEquals("foo", this.objectHolder.getValue()); - } - - public void testSetValue() { - this.objectHolder.setValue("bar"); - assertEquals("bar", this.objectHolder.getValue()); - this.objectHolder.setValue(null); - assertEquals(null, this.objectHolder.getValue()); - this.objectHolder.setValue("baz"); - assertEquals("baz", this.objectHolder.getValue()); - } - - public void testPropertyChange1() { - this.objectHolder.addChangeListener(this.buildListener()); - this.verifyPropertyChange(); - } - - public void testPropertyChange2() { - this.objectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.verifyPropertyChange(); - } - - private void verifyPropertyChange() { - this.event = null; - this.objectHolder.setValue("bar"); - this.verifyEvent("foo", "bar"); - - this.event = null; - this.objectHolder.setValue(null); - this.verifyEvent("bar", null); - - this.event = null; - this.objectHolder.setValue("baz"); - this.verifyEvent(null, "baz"); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - SimplePropertyValueModelTests.this.event = e; - } - }; - } - - private void verifyEvent(Object oldValue, Object newValue) { - assertEquals(this.objectHolder, this.event.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event.getPropertyName()); - assertEquals(oldValue, this.event.getOldValue()); - assertEquals(newValue, this.event.getNewValue()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SortedListValueModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SortedListValueModelAdapterTests.java deleted file mode 100644 index 46607e8921..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SortedListValueModelAdapterTests.java +++ /dev/null @@ -1,222 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.TreeSet; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.ReverseComparator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelAdapter; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SortedListValueModelAdapterTests extends TestCase { - private SortedListValueModelAdapter<String> adapter; - private SimpleCollectionValueModel<String> wrappedCollectionHolder; - private Collection<String> wrappedCollection; - - - public SortedListValueModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.wrappedCollection = new HashBag<String>(); - this.wrappedCollectionHolder = new SimpleCollectionValueModel<String>(this.wrappedCollection); - this.adapter = new SortedListValueModelAdapter<String>(this.wrappedCollectionHolder); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - private void verifyList(Collection<String> expected, ListValueModel<String> actual) { - this.verifyList(expected, actual, null); - } - - private void verifyList(Collection<String> expected, ListValueModel<String> actual, Comparator<String> comparator) { - Collection<String> sortedSet = new TreeSet<String>(comparator); - sortedSet.addAll(expected); - List<String> expectedList = new ArrayList<String>(sortedSet); - List<String> actualList = CollectionTools.list(actual.iterator()); - assertEquals(expectedList, actualList); - } - - public void testAdd() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsReplaced(ListReplaceEvent e) {/* OK */} - }); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - assertEquals(3, this.adapter.size()); - this.verifyList(this.wrappedCollection, this.adapter); - } - - public void testAddItem() { - List<String> synchList = new CoordinatedList<String>(this.adapter); - Bag<String> synchCollection = new CoordinatedBag<String>(this.wrappedCollectionHolder); - this.wrappedCollectionHolder.add("foo"); - assertTrue(this.wrappedCollection.contains("foo")); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - assertEquals(6, this.wrappedCollection.size()); - - this.verifyList(this.wrappedCollection, this.adapter); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection, synchCollection); - } - - public void testRemoveItem() { - List<String> synchList = new CoordinatedList<String>(this.adapter); - Bag<String> synchCollection = new CoordinatedBag<String>(this.wrappedCollectionHolder); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - this.wrappedCollectionHolder.remove("jaz"); - assertFalse(this.wrappedCollection.contains("jaz")); - this.wrappedCollectionHolder.remove("foo"); - assertFalse(this.wrappedCollection.contains("foo")); - assertEquals(4, this.wrappedCollection.size()); - - this.verifyList(this.wrappedCollection, this.adapter); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection, synchCollection); - } - - public void testListSynch() { - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsRemoved(ListRemoveEvent e) {/* OK */} - @Override - public void itemsReplaced(ListReplaceEvent e) {/* OK */} - }); - this.wrappedCollectionHolder.add("foo"); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - this.wrappedCollectionHolder.remove("jaz"); - assertFalse(this.wrappedCollection.contains("jaz")); - this.wrappedCollectionHolder.remove("foo"); - assertFalse(this.wrappedCollection.contains("foo")); - assertEquals(4, this.wrappedCollection.size()); - - this.verifyList(this.wrappedCollection, this.adapter); - } - - public void testSetComparator() { - List<String> synchList = new CoordinatedList<String>(this.adapter); - Bag<String> synchCollection = new CoordinatedBag<String>(this.wrappedCollectionHolder); - this.wrappedCollectionHolder.add("foo"); - assertTrue(this.wrappedCollection.contains("foo")); - this.wrappedCollectionHolder.add("bar"); - this.wrappedCollectionHolder.add("baz"); - this.wrappedCollectionHolder.add("joo"); - this.wrappedCollectionHolder.add("jar"); - this.wrappedCollectionHolder.add("jaz"); - assertEquals(6, this.wrappedCollection.size()); - - this.verifyList(this.wrappedCollection, this.adapter); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection, synchCollection); - - this.adapter.setComparator(new ReverseComparator<String>()); - this.verifyList(this.wrappedCollection, this.adapter, new ReverseComparator<String>()); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); - assertEquals(this.wrappedCollection, synchCollection); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - CoordinatedList<String> synchList = new CoordinatedList<String>(this.adapter); - assertTrue(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.adapter.removeListChangeListener(ListValueModel.LIST_VALUES, synchList); - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener cl = new ChangeAdapter(); - this.adapter.addChangeListener(cl); - assertTrue(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.adapter.removeChangeListener(cl); - assertFalse(((AbstractModel) this.adapter).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - public void testCollectionChange() { - this.wrappedCollectionHolder.add("fred"); - this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsReplaced(ListReplaceEvent e) {/* OK */} - }); - this.wrappedCollectionHolder.setValues(Arrays.asList(new String[] {"foo", "bar", "baz"})); - assertEquals(3, this.adapter.size()); - this.verifyList(this.wrappedCollection, this.adapter); - } - - class TestListChangeListener implements ListChangeListener { - public void itemsAdded(ListAddEvent e) { - fail("unexpected event"); - } - public void itemsRemoved(ListRemoveEvent e) { - fail("unexpected event"); - } - public void itemsReplaced(ListReplaceEvent e) { - fail("unexpected event"); - } - public void itemsMoved(ListMoveEvent e) { - fail("unexpected event"); - } - public void listCleared(ListClearEvent e) { - fail("unexpected event"); - } - public void listChanged(ListChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SortedListValueModelWrapperTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SortedListValueModelWrapperTests.java deleted file mode 100644 index 0f4f945eec..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/SortedListValueModelWrapperTests.java +++ /dev/null @@ -1,237 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.TreeSet; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.ReverseComparator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SortedListValueModelWrapperTests extends TestCase { - private List<String> list; - private SimpleListValueModel<String> listModel; - private SortedListValueModelWrapper<String> sortedListModel; - - - public SortedListValueModelWrapperTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.list = new ArrayList<String>(); - this.listModel = new SimpleListValueModel<String>(this.list); - this.sortedListModel = new SortedListValueModelWrapper<String>(this.listModel); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - private void verifyList(Collection<String> expected, ListValueModel<String> actual) { - this.verifyList(expected, actual, null); - } - - private void verifyList(Collection<String> expected, ListValueModel<String> actual, Comparator<String> comparator) { - Collection<String> sortedSet = new TreeSet<String>(comparator); - sortedSet.addAll(expected); - List<String> expectedList = new ArrayList<String>(sortedSet); - List<String> actualList = CollectionTools.list(actual); - assertEquals(expectedList, actualList); - } - - public void testAdd() { - this.sortedListModel.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsReplaced(ListReplaceEvent e) {/* OK */} - }); - this.listModel.add("foo"); - this.listModel.add("bar"); - this.listModel.add("baz"); - assertEquals(3, this.sortedListModel.size()); - this.verifyList(this.list, this.sortedListModel); - } - - public void testAddItem() { - List<String> sortedSynchList = new CoordinatedList<String>(this.sortedListModel); - List<String> synchList = new CoordinatedList<String>(this.listModel); - this.listModel.add("foo"); - assertTrue(this.list.contains("foo")); - this.listModel.add("bar"); - this.listModel.add("baz"); - this.listModel.add("joo"); - this.listModel.add("jar"); - this.listModel.add("jaz"); - assertEquals(6, this.list.size()); - - this.verifyList(this.list, this.sortedListModel); - assertEquals(this.list, synchList); - assertEquals(CollectionTools.list(this.sortedListModel), sortedSynchList); - } - - public void testRemoveItem() { - List<String> sortedSynchList = new CoordinatedList<String>(this.sortedListModel); - List<String> synchList = new CoordinatedList<String>(this.listModel); - this.listModel.add("foo"); - this.listModel.add("bar"); - this.listModel.add("baz"); - this.listModel.add("joo"); - this.listModel.add("jar"); - this.listModel.add("jaz"); - this.listModel.remove("jaz"); - assertFalse(this.list.contains("jaz")); - this.listModel.remove("foo"); - assertFalse(this.list.contains("foo")); - assertEquals(4, this.list.size()); - - this.verifyList(this.list, this.sortedListModel); - assertEquals(this.list, synchList); - assertEquals(CollectionTools.list(this.sortedListModel), sortedSynchList); - } - - public void testReplaceItem() { - List<String> sortedSynchList = new CoordinatedList<String>(this.sortedListModel); - List<String> synchList = new CoordinatedList<String>(this.listModel); - this.listModel.add("foo"); - assertTrue(this.list.contains("foo")); - this.listModel.add("bar"); - this.listModel.add("baz"); - this.listModel.add("joo"); - this.listModel.add("jar"); - this.listModel.add("jaz"); - assertEquals(6, this.list.size()); - this.listModel.set(3, "ttt"); - this.listModel.set(4, "xxx"); - assertTrue(this.list.contains("xxx")); - - this.verifyList(this.list, this.sortedListModel); - assertEquals(this.list, synchList); - assertEquals(CollectionTools.list(this.sortedListModel), sortedSynchList); - } - - public void testListSynch() { - this.sortedListModel.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void itemsAdded(ListAddEvent e) {/* OK */} - @Override - public void itemsRemoved(ListRemoveEvent e) {/* OK */} - @Override - public void itemsReplaced(ListReplaceEvent e) {/* OK */} - }); - this.listModel.add("foo"); - this.listModel.add("bar"); - this.listModel.add("baz"); - this.listModel.add("joo"); - this.listModel.add("jar"); - this.listModel.add("jaz"); - this.listModel.remove("jaz"); - assertFalse(this.list.contains("jaz")); - this.listModel.remove("foo"); - assertFalse(this.list.contains("foo")); - assertEquals(4, this.list.size()); - - this.verifyList(this.list, this.sortedListModel); - } - - public void testSetComparator() { - List<String> sortedSynchList = new CoordinatedList<String>(this.sortedListModel); - List<String> synchList = new CoordinatedList<String>(this.listModel); - this.listModel.add("foo"); - assertTrue(this.list.contains("foo")); - this.listModel.add("bar"); - this.listModel.add("baz"); - this.listModel.add("joo"); - this.listModel.add("jar"); - this.listModel.add("jaz"); - assertEquals(6, this.list.size()); - - this.verifyList(this.list, this.sortedListModel); - assertEquals(this.list, synchList); - assertEquals(CollectionTools.list(this.sortedListModel), sortedSynchList); - - this.sortedListModel.setComparator(new ReverseComparator<String>()); - this.verifyList(this.list, this.sortedListModel, new ReverseComparator<String>()); - assertEquals(this.list, synchList); - } - - public void testHasListeners() { - assertFalse(((AbstractModel) this.sortedListModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - CoordinatedList<String> sortedSynchList = new CoordinatedList<String>(this.sortedListModel); - assertTrue(((AbstractModel) this.sortedListModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.sortedListModel.removeListChangeListener(ListValueModel.LIST_VALUES, sortedSynchList); - assertFalse(((AbstractModel) this.sortedListModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener cl = new ChangeAdapter(); - this.sortedListModel.addChangeListener(cl); - assertTrue(((AbstractModel) this.sortedListModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.sortedListModel.removeChangeListener(cl); - assertFalse(((AbstractModel) this.sortedListModel).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - public void testListChange() { - this.listModel.add("fred"); - this.sortedListModel.addListChangeListener(ListValueModel.LIST_VALUES, new TestListChangeListener() { - @Override - public void listChanged(ListChangeEvent e) {/* OK */} - }); - this.listModel.setListValues(Arrays.asList(new String[] {"foo", "bar", "baz"})); - assertEquals(3, this.sortedListModel.size()); - this.verifyList(this.list, this.sortedListModel); - } - - class TestListChangeListener implements ListChangeListener { - public void itemsAdded(ListAddEvent e) { - fail("unexpected event"); - } - public void itemsRemoved(ListRemoveEvent e) { - fail("unexpected event"); - } - public void itemsReplaced(ListReplaceEvent e) { - fail("unexpected event"); - } - public void itemsMoved(ListMoveEvent e) { - fail("unexpected event"); - } - public void listCleared(ListClearEvent e) { - fail("unexpected event"); - } - public void listChanged(ListChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticCollectionValueModelTests.java deleted file mode 100644 index 920f57d506..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticCollectionValueModelTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.Collection; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.model.value.StaticCollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class StaticCollectionValueModelTests extends TestCase { - - private static final Collection<String> COLLECTION = buildCollection(); - private static Collection<String> buildCollection() { - Collection<String> result = new HashBag<String>(); - result.add("foo"); - result.add("bar"); - return result; - } - - private CollectionValueModel<String> collectionHolder; - - - public StaticCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.collectionHolder = this.buildCollectionHolder(); - } - - private CollectionValueModel<String> buildCollectionHolder() { - return new StaticCollectionValueModel<String>(COLLECTION); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - assertEquals(buildCollection(), CollectionTools.bag(this.collectionHolder.iterator())); - } - - public void testSize() { - assertEquals(buildCollection().size(), this.collectionHolder.size()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticListValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticListValueModelTests.java deleted file mode 100644 index 620a4ab071..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticListValueModelTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.List; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.StaticListValueModel; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class StaticListValueModelTests extends TestCase { - - private static final List<String> LIST = buildList(); - private static List<String> buildList() { - List<String> result = new ArrayList<String>(); - result.add("foo"); - result.add("bar"); - return result; - } - - private ListValueModel<String> listHolder; - - - public StaticListValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.listHolder = new StaticListValueModel<String>(LIST); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGet() { - List<String> expected = buildList(); - for (int i = 0; i < this.listHolder.size(); i++) { - assertEquals(expected.get(i), this.listHolder.get(i)); - } - } - - public void testIterator() { - assertEquals(buildList(), CollectionTools.list(this.listHolder.listIterator())); - } - - public void testSize() { - assertEquals(buildList().size(), this.listHolder.size()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticValueModelTests.java deleted file mode 100644 index 535a700f52..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/StaticValueModelTests.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.StaticPropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class StaticValueModelTests extends TestCase { - private PropertyValueModel<String> objectHolder; - private static final PropertyValueModel<String> OBJECT_HOLDER = new StaticPropertyValueModel<String>("foo"); - - - public StaticValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = OBJECT_HOLDER; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - assertEquals("foo", this.objectHolder.getValue()); - } - - public void testToString() { - assertTrue(this.objectHolder.toString().indexOf("foo") >= 0); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/TransformationListValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/TransformationListValueModelTests.java deleted file mode 100644 index 78963bc685..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/TransformationListValueModelTests.java +++ /dev/null @@ -1,339 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.TransformationListValueModel; -import org.eclipse.jpt.common.utility.model.event.ListAddEvent; -import org.eclipse.jpt.common.utility.model.event.ListChangeEvent; -import org.eclipse.jpt.common.utility.model.event.ListClearEvent; -import org.eclipse.jpt.common.utility.model.event.ListEvent; -import org.eclipse.jpt.common.utility.model.event.ListMoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.ListReplaceEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class TransformationListValueModelTests extends TestCase { - private SimpleListValueModel<String> listHolder; - private ListValueModel<String> transformedListHolder; - ListEvent event; - String eventType; - - private static final String ADD = "add"; - private static final String REMOVE = "remove"; - private static final String REPLACE = "replace"; - private static final String MOVE = "move"; - private static final String CLEAR = "clear"; - private static final String CHANGE = "change"; - - - public TransformationListValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.listHolder = new SimpleListValueModel<String>(this.buildList()); - this.transformedListHolder = this.buildTransformedListHolder(this.listHolder); - } - - private List<String> buildList() { - List<String> result = new ArrayList<String>(); - result.add("foo"); - result.add("bar"); - result.add("baz"); - return result; - } - - private List<String> buildTransformedList() { - return this.transform(this.buildList()); - } - - private List<String> transform(List<String> list) { - List<String> result = new ArrayList<String>(list.size()); - for (String string : list) { - if (string == null) { - result.add(null); - } else { - result.add(string.toUpperCase()); - } - } - return result; - } - - private List<String> buildAddList() { - List<String> result = new ArrayList<String>(); - result.add("joo"); - result.add("jar"); - result.add("jaz"); - return result; - } - - private List<String> buildTransformedAddList() { - return this.transform(this.buildAddList()); - } - -// private List<String> buildRemoveList() { -// List<String> result = new ArrayList<String>(); -// result.add("foo"); -// result.add("bar"); -// return result; -// } -// -// private List<String> buildTransformedRemoveList() { -// return this.transform(this.buildRemoveList()); -// } -// - ListValueModel<String> buildTransformedListHolder(ListValueModel<String> lvm) { - return new TransformationListValueModel<String, String>(lvm) { - @Override - protected String transformItem_(String s) { - return s.toUpperCase(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testIterator() { - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - assertEquals(this.buildTransformedList(), CollectionTools.list(this.transformedListHolder.iterator())); - } - - public void testStaleValues() { - ListChangeListener listener = this.buildListener(); - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, listener); - assertEquals(this.buildTransformedList(), CollectionTools.list(this.transformedListHolder.iterator())); - - this.transformedListHolder.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - assertEquals(Collections.EMPTY_LIST, CollectionTools.list(this.transformedListHolder.iterator())); - } - - public void testSize() { - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - assertEquals(this.buildTransformedList().size(), CollectionTools.size(this.transformedListHolder.iterator())); - } - - private boolean transformedListContains(Object item) { - return CollectionTools.contains(this.transformedListHolder.iterator(), item); - } - - private boolean transformedListContainsAll(Collection<String> items) { - return CollectionTools.containsAll(this.transformedListHolder.iterator(), items); - } - - private boolean transformedListContainsAny(Collection<String> items) { - List<String> transformedList = CollectionTools.list(this.transformedListHolder.iterator()); - for (Iterator<String> stream = items.iterator(); stream.hasNext(); ) { - if (transformedList.contains(stream.next())) { - return true; - } - } - return false; - } - - public void testAdd() { - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertFalse(this.transformedListContains("JOO")); - this.listHolder.add(2, "joo"); - assertTrue(this.transformedListContains("JOO")); - - assertFalse(this.transformedListContains(null)); - this.listHolder.add(0, null); - assertTrue(this.transformedListContains(null)); - } - - public void testAddAll() { - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertFalse(this.transformedListContainsAny(this.buildTransformedAddList())); - this.listHolder.addAll(2, this.buildAddList()); - assertTrue(this.transformedListContainsAll(this.buildTransformedAddList())); - } - - public void testRemove() { - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - - assertTrue(this.transformedListContains("BAR")); - this.listHolder.remove(this.buildList().indexOf("bar")); - assertFalse(this.transformedListContains("BAR")); - - this.listHolder.add(1, null); - assertTrue(this.transformedListContains(null)); - this.listHolder.remove(1); - assertFalse(this.transformedListContains(null)); - } - - public void testListChangeGeneric() { - this.transformedListHolder.addChangeListener(this.buildListener()); - this.verifyListChange(); - } - - public void testListChangeNamed() { - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - this.verifyListChange(); - } - - private void verifyListChange() { - this.event = null; - this.eventType = null; - this.listHolder.add(1, "joo"); - this.verifyEvent(ADD, 1, "JOO"); - - this.event = null; - this.eventType = null; - this.listHolder.add(1, null); - this.verifyEvent(ADD, 1, null); - - this.event = null; - this.eventType = null; - this.listHolder.remove(1); - this.verifyEvent(REMOVE, 1, null); - - this.event = null; - this.eventType = null; - this.listHolder.remove(1); - this.verifyEvent(REMOVE, 1, "JOO"); - - this.event = null; - this.eventType = null; - this.listHolder.addAll(0, this.buildList()); - this.verifyEvent(ADD); - assertEquals(this.buildTransformedList(), CollectionTools.list(((ListAddEvent) this.event).getItems())); - - this.event = null; - this.eventType = null; - this.listHolder.set(0, "joo"); - this.verifyEvent(REPLACE); - assertFalse(CollectionTools.contains(((ListReplaceEvent) this.event).getNewItems(), "FOO")); - assertTrue(CollectionTools.contains(((ListReplaceEvent) this.event).getNewItems(), "JOO")); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void itemsAdded(ListAddEvent e) { - TransformationListValueModelTests.this.eventType = ADD; - TransformationListValueModelTests.this.event = e; - } - @Override - public void itemsRemoved(ListRemoveEvent e) { - TransformationListValueModelTests.this.eventType = REMOVE; - TransformationListValueModelTests.this.event = e; - } - @Override - public void itemsReplaced(ListReplaceEvent e) { - TransformationListValueModelTests.this.eventType = REPLACE; - TransformationListValueModelTests.this.event = e; - } - @Override - public void itemsMoved(ListMoveEvent e) { - TransformationListValueModelTests.this.eventType = MOVE; - TransformationListValueModelTests.this.event = e; - } - @Override - public void listCleared(ListClearEvent e) { - TransformationListValueModelTests.this.eventType = CLEAR; - TransformationListValueModelTests.this.event = e; - } - @Override - public void listChanged(ListChangeEvent e) { - TransformationListValueModelTests.this.eventType = CHANGE; - TransformationListValueModelTests.this.event = e; - } - }; - } - - private void verifyEvent(String type) { - assertEquals(type, this.eventType); - assertEquals(this.transformedListHolder, this.event.getSource()); - assertEquals(ListValueModel.LIST_VALUES, this.event.getListName()); - } - - private void verifyEvent(String type, int index, Object item) { - this.verifyEvent(type); - if (type == ADD) { - assertEquals(index, ((ListAddEvent) this.event).getIndex()); - assertEquals(item, ((ListAddEvent) this.event).getItems().iterator().next()); - } else if (type == REMOVE) { - assertEquals(index, ((ListRemoveEvent) this.event).getIndex()); - assertEquals(item, ((ListRemoveEvent) this.event).getItems().iterator().next()); - } - } - - public void testHasListeners() { - /* - * adding listeners to the transformed list will cause listeners - * to be added to the wrapped list; - * likewise, removing listeners from the transformed list will - * cause listeners to be removed from the wrapped list - */ - assertFalse(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ChangeListener listener = this.buildListener(); - - this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, listener); - assertTrue(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.transformedListHolder.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - assertFalse(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.transformedListHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - this.transformedListHolder.removeChangeListener(listener); - assertFalse(((AbstractModel) this.listHolder).hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - } - - - /** - * execute the same set of tests again, but by passing a Transformer to the adapter - * (as opposed to overriding #transformItem(Object)) - */ - public static class TransformerTests extends TransformationListValueModelTests { - public TransformerTests(String name) { - super(name); - } - @Override - ListValueModel<String> buildTransformedListHolder(ListValueModel<String> lvm) { - return new TransformationListValueModel<String, String>(lvm, this.buildTransformer()); - } - private Transformer<String, String> buildTransformer() { - return new Transformer<String, String>() { - public String transform(String s) { - return (s == null) ? null : s.toUpperCase(); - } - }; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/TransformationPropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/TransformationPropertyValueModelTests.java deleted file mode 100644 index 4c72608454..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/TransformationPropertyValueModelTests.java +++ /dev/null @@ -1,206 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.Transformer; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.TransformationWritablePropertyValueModel; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class TransformationPropertyValueModelTests - extends TestCase -{ - private ModifiablePropertyValueModel<String> objectHolder; - PropertyChangeEvent event; - - private ModifiablePropertyValueModel<String> transformationObjectHolder; - PropertyChangeEvent transformationEvent; - - public TransformationPropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.objectHolder = new SimplePropertyValueModel<String>("foo"); - this.transformationObjectHolder = new TransformationWritablePropertyValueModel<String, String>(this.objectHolder, this.buildTransformer(), this.buildReverseTransformer()); - } - - private Transformer<String, String> buildTransformer() { - return new Transformer<String, String>() { - public String transform(String s) { - return (s == null) ? null : s.toUpperCase(); - } - }; - } - - private Transformer<String, String> buildReverseTransformer() { - return new Transformer<String, String>() { - public String transform(String s) { - return (s == null) ? null : s.toLowerCase(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testValue() { - assertEquals("foo", this.objectHolder.getValue()); - assertNull(this.transformationObjectHolder.getValue()); - ChangeListener listener = this.buildTransformationListener(); - this.transformationObjectHolder.addChangeListener(listener); - assertEquals("FOO", this.transformationObjectHolder.getValue()); - - this.objectHolder.setValue("bar"); - assertEquals("bar", this.objectHolder.getValue()); - assertEquals("BAR", this.transformationObjectHolder.getValue()); - - this.objectHolder.setValue("baz"); - assertEquals("baz", this.objectHolder.getValue()); - assertEquals("BAZ", this.transformationObjectHolder.getValue()); - - this.objectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.transformationObjectHolder.getValue()); - - this.objectHolder.setValue("foo"); - assertEquals("foo", this.objectHolder.getValue()); - assertEquals("FOO", this.transformationObjectHolder.getValue()); - } - - public void testSetValue() { - this.transformationObjectHolder.setValue("BAR"); - assertEquals("bar", this.objectHolder.getValue()); - assertEquals("BAR", this.transformationObjectHolder.getValue()); - - // NB: odd behavior(!) - this.transformationObjectHolder.setValue("Foo"); - assertEquals("foo", this.objectHolder.getValue()); - assertEquals("Foo", this.transformationObjectHolder.getValue()); - ChangeListener listener = this.buildTransformationListener(); - this.transformationObjectHolder.addChangeListener(listener); - assertEquals("FOO", this.transformationObjectHolder.getValue()); - this.transformationObjectHolder.removeChangeListener(listener); - - this.transformationObjectHolder.setValue(null); - assertNull(this.objectHolder.getValue()); - assertNull(this.transformationObjectHolder.getValue()); - - // NB: odd behavior(!) - this.transformationObjectHolder.setValue("baz"); - assertEquals("baz", this.objectHolder.getValue()); - assertEquals("baz", this.transformationObjectHolder.getValue()); - this.transformationObjectHolder.addChangeListener(listener); - assertEquals("BAZ", this.transformationObjectHolder.getValue()); - this.transformationObjectHolder.removeChangeListener(listener); - } - - public void testLazyListening() { - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - ChangeListener listener = this.buildTransformationListener(); - this.transformationObjectHolder.addChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.transformationObjectHolder.removeChangeListener(listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.transformationObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.transformationObjectHolder.removePropertyChangeListener(PropertyValueModel.VALUE, listener); - assertTrue(((AbstractModel) this.objectHolder).hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testPropertyChange1() { - this.objectHolder.addChangeListener(this.buildListener()); - this.transformationObjectHolder.addChangeListener(this.buildTransformationListener()); - this.verifyPropertyChanges(); - } - - public void testPropertyChange2() { - this.objectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildListener()); - this.transformationObjectHolder.addPropertyChangeListener(PropertyValueModel.VALUE, this.buildTransformationListener()); - this.verifyPropertyChanges(); - } - - private void verifyPropertyChanges() { - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue("bar"); - this.verifyEvent(this.event, this.objectHolder, "foo", "bar"); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, "FOO", "BAR"); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue("baz"); - this.verifyEvent(this.event, this.objectHolder, "bar", "baz"); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, "BAR", "BAZ"); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue("Foo"); - this.verifyEvent(this.event, this.objectHolder, "baz", "Foo"); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, "BAZ", "FOO"); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue("FOO"); - this.verifyEvent(this.event, this.objectHolder, "Foo", "FOO"); - assertNull(this.transformationEvent); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue(null); - this.verifyEvent(this.event, this.objectHolder, "FOO", null); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, "FOO", null); - - this.event = null; - this.transformationEvent = null; - this.objectHolder.setValue("bar"); - this.verifyEvent(this.event, this.objectHolder, null, "bar"); - this.verifyEvent(this.transformationEvent, this.transformationObjectHolder, null, "BAR"); - } - - private ChangeListener buildListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - TransformationPropertyValueModelTests.this.event = e; - } - }; - } - - private ChangeListener buildTransformationListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - TransformationPropertyValueModelTests.this.transformationEvent = e; - } - }; - } - - private void verifyEvent(PropertyChangeEvent e, Object source, Object oldValue, Object newValue) { - assertEquals(source, e.getSource()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - assertEquals(oldValue, e.getOldValue()); - assertEquals(newValue, e.getNewValue()); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueCollectionAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueCollectionAdapterTests.java deleted file mode 100644 index 316c2c4812..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueCollectionAdapterTests.java +++ /dev/null @@ -1,159 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.ValueCollectionAdapter; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ValueCollectionAdapterTests extends TestCase { - private Junk junk; - private SimplePropertyValueModel<Junk> junkHolder; - private ValueCollectionAdapter<Junk> junkHolder2; - - - public ValueCollectionAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.junk = new Junk("foo"); - this.junkHolder = new SimplePropertyValueModel<Junk>(this.junk); - this.junkHolder2 = new ValueCollectionAdapter<Junk>(this.junkHolder, Junk.STUFF_COLLECTION); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testWrappedPVM() { - Junk junk2 = new Junk("bar"); - LocalListener l = new LocalListener(this.junkHolder2, this.junk, junk2); - this.junkHolder2.addChangeListener(l); - this.junkHolder.setValue(junk2); - assertTrue(l.eventReceived()); - } - - public void testHasPropertyChangeListeners() throws Exception { - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addChangeListener(l); - assertTrue(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.junkHolder2.removeChangeListener(l); - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testHasStateChangeListeners() throws Exception { - assertFalse(this.junk.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - assertTrue(this.junk.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - assertTrue(this.junkHolder2.hasAnyStateChangeListeners()); - - this.junkHolder2.removeStateChangeListener(l); - assertFalse(this.junk.hasAnyCollectionChangeListeners(Junk.STUFF_COLLECTION)); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - } - - public void testCollectionAdd() { - LocalListener l = new LocalListener(this.junkHolder2); - this.junkHolder2.addStateChangeListener(l); - this.junk.addStuff("bar"); - assertTrue(l.eventReceived()); - } - - public void testCollectionRemove() { - LocalListener l = new LocalListener(this.junkHolder2); - this.junkHolder2.addStateChangeListener(l); - this.junk.removeStuff("foo"); - assertTrue(l.eventReceived()); - } - - - class LocalListener extends ChangeAdapter { - private boolean eventReceived = false; - private final Object source; - private final Object oldValue; - private final Object newValue; - LocalListener(Object source) { - this(source, null, null); - } - LocalListener(Object source, Object oldValue, Object newValue) { - super(); - this.source = source; - this.oldValue = oldValue; - this.newValue = newValue; - } - @Override - public void propertyChanged(PropertyChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - assertEquals(this.oldValue, e.getOldValue()); - assertEquals(this.newValue, e.getNewValue()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - } - @Override - public void stateChanged(StateChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - } - boolean eventReceived() { - return this.eventReceived; - } - } - - - private class Junk extends AbstractModel { - private Collection<String> stuff; - public static final String STUFF_COLLECTION = "stuff"; - - public Junk(String stuffItem) { - this.stuff = new ArrayList<String>(); - this.stuff.add(stuffItem); - } - - public void addStuff(String stuffItem) { - this.addItemToCollection(stuffItem, this.stuff, STUFF_COLLECTION); - } - - public void removeStuff(String stuffItem) { - this.removeItemFromCollection(stuffItem, this.stuff, STUFF_COLLECTION); - } - - @Override - public String toString() { - return "Junk(" + this.stuff + ")"; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueListAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueListAdapterTests.java deleted file mode 100644 index 4a447a431c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueListAdapterTests.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.ValueListAdapter; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ValueListAdapterTests extends TestCase { - private Junk junk; - private SimplePropertyValueModel<Junk> junkHolder; - private ValueListAdapter<Junk> junkHolder2; - - - public ValueListAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.junk = new Junk("foo"); - this.junkHolder = new SimplePropertyValueModel<Junk>(this.junk); - this.junkHolder2 = new ValueListAdapter<Junk>(this.junkHolder, Junk.STUFF_LIST); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testWrappedPVM() { - Junk junk2 = new Junk("bar"); - LocalListener l = new LocalListener(this.junkHolder2, this.junk, junk2); - this.junkHolder2.addChangeListener(l); - this.junkHolder.setValue(junk2); - assertTrue(l.eventReceived()); - } - - public void testHasPropertyChangeListeners() throws Exception { - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addChangeListener(l); - assertTrue(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.junkHolder2.removeChangeListener(l); - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testHasStateChangeListeners() throws Exception { - assertFalse(this.junk.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - assertTrue(this.junk.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertTrue(this.junkHolder2.hasAnyStateChangeListeners()); - - this.junkHolder2.removeStateChangeListener(l); - assertFalse(this.junk.hasAnyListChangeListeners(Junk.STUFF_LIST)); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - } - - public void testListAdd() { - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - this.junk.addStuff("bar"); - assertTrue(l.eventReceived()); - } - - public void testListRemove() { - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - this.junk.removeStuff("foo"); - assertTrue(l.eventReceived()); - } - - public void testListReplace() { - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - this.junk.replaceStuff("foo", "bar"); - assertTrue(l.eventReceived()); - } - - - class LocalListener extends ChangeAdapter { - private boolean eventReceived = false; - private final Object source; - private final Object oldValue; - private final Object newValue; - LocalListener(Object source) { - this(source, null, null); - } - LocalListener(Object source, Object oldValue, Object newValue) { - super(); - this.source = source; - this.oldValue = oldValue; - this.newValue = newValue; - } - @Override - public void propertyChanged(PropertyChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - assertEquals(this.oldValue, e.getOldValue()); - assertEquals(this.newValue, e.getNewValue()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - } - @Override - public void stateChanged(StateChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - } - boolean eventReceived() { - return this.eventReceived; - } - } - - private class Junk extends AbstractModel { - private List<String> stuff; - public static final String STUFF_LIST = "stuff"; - - public Junk(String stuffItem) { - this.stuff = new ArrayList<String>(); - this.stuff.add(stuffItem); - } - - public void addStuff(String stuffItem) { - this.addItemToList(stuffItem, this.stuff, STUFF_LIST); - } - - public void removeStuff(String stuffItem) { - this.removeItemFromList(stuffItem, this.stuff, STUFF_LIST); - } - - public void replaceStuff(String oldStuffItem, String newStuffItem) { - this.replaceItemInList(oldStuffItem, newStuffItem, this.stuff, STUFF_LIST); - } - - @Override - public String toString() { - return "Junk(" + this.stuff + ")"; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValuePropertyAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValuePropertyAdapterTests.java deleted file mode 100644 index c3f5be6675..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValuePropertyAdapterTests.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.ValuePropertyAdapter; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ValuePropertyAdapterTests extends TestCase { - private Junk junk; - private SimplePropertyValueModel<Junk> junkHolder; - private ValuePropertyAdapter<Junk> junkHolder2; - - - public ValuePropertyAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.junk = new Junk("foo"); - this.junkHolder = new SimplePropertyValueModel<Junk>(this.junk); - this.junkHolder2 = new ValuePropertyAdapter<Junk>(this.junkHolder, Junk.NAME_PROPERTY); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testWrappedPVM() { - Junk junk2 = new Junk("bar"); - LocalListener l = new LocalListener(this.junkHolder2, this.junk, junk2); - this.junkHolder2.addChangeListener(l); - this.junkHolder.setValue(junk2); - assertTrue(l.eventReceived()); - } - - public void testHasPropertyChangeListeners() throws Exception { - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addChangeListener(l); - assertTrue(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.junkHolder2.removeChangeListener(l); - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testHasStateChangeListeners() throws Exception { - assertFalse(this.junk.hasAnyPropertyChangeListeners(Junk.NAME_PROPERTY)); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - assertTrue(this.junk.hasAnyPropertyChangeListeners(Junk.NAME_PROPERTY)); - assertTrue(this.junkHolder2.hasAnyStateChangeListeners()); - - this.junkHolder2.removeStateChangeListener(l); - assertFalse(this.junk.hasAnyPropertyChangeListeners(Junk.NAME_PROPERTY)); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - } - - public void testChangeProperty() { - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - this.junk.setName("bar"); - assertTrue(l.eventReceived()); - } - - - class LocalListener extends ChangeAdapter { - private boolean eventReceived = false; - private final Object source; - private final Object oldValue; - private final Object newValue; - LocalListener(Object source) { - this(source, null, null); - } - LocalListener(Object source, Object oldValue, Object newValue) { - super(); - this.source = source; - this.oldValue = oldValue; - this.newValue = newValue; - } - @Override - public void propertyChanged(PropertyChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - assertEquals(this.oldValue, e.getOldValue()); - assertEquals(this.newValue, e.getNewValue()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - } - @Override - public void stateChanged(StateChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - } - boolean eventReceived() { - return this.eventReceived; - } - } - - class Junk extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - - public Junk(String name) { - this.name = name; - } - - public void setName(String name) { - String old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - @Override - public String toString() { - return "Junk(" + this.name + ")"; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueStateAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueStateAdapterTests.java deleted file mode 100644 index d23581257a..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/ValueStateAdapterTests.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.ValueStateAdapter; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ValueStateAdapterTests extends TestCase { - private Junk junk; - private SimplePropertyValueModel<Junk> junkHolder; - private ValueStateAdapter<Junk> junkHolder2; - - - public ValueStateAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.junk = new Junk("foo"); - this.junkHolder = new SimplePropertyValueModel<Junk>(this.junk); - this.junkHolder2 = new ValueStateAdapter<Junk>(this.junkHolder); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testWrappedPVM() { - Junk junk2 = new Junk("bar"); - LocalListener l = new LocalListener(this.junkHolder2, this.junk, junk2); - this.junkHolder2.addChangeListener(l); - this.junkHolder.setValue(junk2); - assertTrue(l.eventReceived()); - } - - public void testHasPropertyChangeListeners() throws Exception { - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addChangeListener(l); - assertTrue(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - this.junkHolder2.removeChangeListener(l); - assertFalse(this.junkHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertFalse(this.junkHolder2.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - public void testHasStateChangeListeners() throws Exception { - assertFalse(this.junk.hasAnyStateChangeListeners()); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addStateChangeListener(l); - assertTrue(this.junk.hasAnyStateChangeListeners()); - assertTrue(this.junkHolder2.hasAnyStateChangeListeners()); - - this.junkHolder2.removeStateChangeListener(l); - assertFalse(this.junk.hasAnyStateChangeListeners()); - assertFalse(this.junkHolder2.hasAnyStateChangeListeners()); - } - - public void testChangeState() { - LocalListener l = new LocalListener(this.junkHolder2, null, this.junk); - this.junkHolder2.addChangeListener(l); - this.junkHolder2.addStateChangeListener(l); - this.junk.setName("bar"); - assertTrue(l.eventReceived()); - } - - - class LocalListener extends ChangeAdapter { - private boolean eventReceived = false; - private final Object source; - private final Object oldValue; - private final Object newValue; - LocalListener(Object source) { - this(source, null, null); - } - LocalListener(Object source, Object oldValue, Object newValue) { - super(); - this.source = source; - this.oldValue = oldValue; - this.newValue = newValue; - } - @Override - public void propertyChanged(PropertyChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - assertEquals(this.oldValue, e.getOldValue()); - assertEquals(this.newValue, e.getNewValue()); - assertEquals(PropertyValueModel.VALUE, e.getPropertyName()); - } - @Override - public void stateChanged(StateChangeEvent e) { - this.eventReceived = true; - assertEquals(this.source, e.getSource()); - } - boolean eventReceived() { - return this.eventReceived; - } - } - - class Junk extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - - public Junk(String name) { - this.name = name; - } - - public void setName(String name) { - this.name = name; - this.fireStateChanged(); - } - - @Override - public String toString() { - return "Junk(" + this.name + ")"; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/JptUtilityModelValuePrefsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/JptUtilityModelValuePrefsTests.java deleted file mode 100644 index ad966a9607..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/JptUtilityModelValuePrefsTests.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.prefs; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class JptUtilityModelValuePrefsTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityModelValuePrefsTests.class.getPackage().getName()); - - suite.addTestSuite(PreferencesCollectionValueModelTests.class); - suite.addTestSuite(PreferencePropertyValueModelTests.class); - - return suite; - } - - private JptUtilityModelValuePrefsTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencePropertyValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencePropertyValueModelTests.java deleted file mode 100644 index d332feda79..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencePropertyValueModelTests.java +++ /dev/null @@ -1,398 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.prefs; - -import java.util.prefs.NodeChangeEvent; -import java.util.prefs.NodeChangeListener; -import java.util.prefs.PreferenceChangeEvent; -import java.util.prefs.PreferenceChangeListener; -import java.util.prefs.Preferences; - -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.prefs.PreferencePropertyValueModel; -import org.eclipse.jpt.common.utility.model.Model; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -@SuppressWarnings("nls") -public class PreferencePropertyValueModelTests extends PreferencesTestCase { - private ModifiablePropertyValueModel<Preferences> nodeHolder; - PreferencePropertyValueModel<String> preferenceAdapter; - PropertyChangeEvent event; - PropertyChangeListener listener; - boolean listenerRemoved = false; - PreferenceChangeEvent preferenceEvent; - private static final String KEY_NAME = "foo"; - private static final String STRING_VALUE = "original string value"; - - public PreferencePropertyValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.testNode.put(KEY_NAME, STRING_VALUE); - - this.nodeHolder = new SimplePropertyValueModel<Preferences>(this.testNode); - this.preferenceAdapter = new PreferencePropertyValueModel<String>(this.nodeHolder, KEY_NAME); - this.listener = this.buildValueChangeListener(); - this.preferenceAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener); - this.event = null; - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - private PropertyChangeListener buildValueChangeListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - if (PreferencePropertyValueModelTests.this.event != null) { - throw new IllegalStateException("unexpected this.event: " + e); - } - PreferencePropertyValueModelTests.this.event = e; - } - }; - } - - public void testSubjectHolder() throws Exception { - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - assertNull(this.event); - - String ANOTHER_STRING_VALUE = "some other value"; - Preferences anotherNode = this.classNode.node("another test node"); - anotherNode.put(KEY_NAME, ANOTHER_STRING_VALUE); - - this.nodeHolder.setValue(anotherNode); - this.verifyEvent(STRING_VALUE, ANOTHER_STRING_VALUE); - assertEquals(ANOTHER_STRING_VALUE, this.preferenceAdapter.getValue()); - - this.event = null; - this.nodeHolder.setValue(null); - this.verifyEvent(ANOTHER_STRING_VALUE, null); - assertNull(this.preferenceAdapter.getValue()); - - this.event = null; - this.nodeHolder.setValue(this.testNode); - this.verifyEvent(null, STRING_VALUE); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - } - - public void testPreferenceChange() throws Exception { - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - assertNull(this.event); - - this.testNode.put(KEY_NAME, STRING_VALUE + STRING_VALUE); - this.waitForEventQueueToClear(); - this.verifyEvent(STRING_VALUE, STRING_VALUE + STRING_VALUE); - assertEquals(STRING_VALUE + STRING_VALUE, this.preferenceAdapter.getValue()); - - this.event = null; - this.testNode.remove(KEY_NAME); - this.waitForEventQueueToClear(); - this.verifyEvent(STRING_VALUE + STRING_VALUE, null); - assertNull(this.preferenceAdapter.getValue()); - - this.event = null; - this.testNode.put(KEY_NAME, STRING_VALUE); - this.waitForEventQueueToClear(); - this.verifyEvent(null, STRING_VALUE); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - } - - public void testValue() throws Exception { - assertEquals(STRING_VALUE, this.testNode.get(KEY_NAME, "<missing preference>")); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - } - - public void testSetValue() throws Exception { - String ANOTHER_STRING_VALUE = "some other value"; - this.preferenceAdapter.setValue(ANOTHER_STRING_VALUE); - assertEquals(ANOTHER_STRING_VALUE, this.preferenceAdapter.getValue()); - assertEquals(ANOTHER_STRING_VALUE, this.testNode.get(KEY_NAME, "<missing preference>")); - } - - public void testHasListeners() throws Exception { - assertTrue(this.preferenceAdapter.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.nodeHasAnyPrefListeners(this.testNode)); - this.preferenceAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener); - assertFalse(this.nodeHasAnyPrefListeners(this.testNode)); - assertFalse(this.preferenceAdapter.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - ChangeListener listener2 = this.buildChangeListener(); - this.preferenceAdapter.addChangeListener(listener2); - assertTrue(this.preferenceAdapter.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - assertTrue(this.nodeHasAnyPrefListeners(this.testNode)); - this.preferenceAdapter.removeChangeListener(listener2); - assertFalse(this.nodeHasAnyPrefListeners(this.testNode)); - assertFalse(this.preferenceAdapter.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void propertyChanged(PropertyChangeEvent e) { - if (PreferencePropertyValueModelTests.this.event != null) { - throw new IllegalStateException("unexpected this.event: " + e); - } - PreferencePropertyValueModelTests.this.event = e; - } - }; - } - - public void testRemoveAndReAddPreference() throws Exception { - assertEquals(STRING_VALUE, this.testNode.get(KEY_NAME, null)); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - assertNull(this.event); - - // remove the preference entirely... - this.testNode.remove(KEY_NAME); - this.waitForEventQueueToClear(); - assertNull(this.testNode.get(KEY_NAME, null)); - this.verifyEvent(STRING_VALUE, null); - assertNull(this.preferenceAdapter.getValue()); - - // ...then re-add it with the same key - this.event = null; - this.testNode.put(KEY_NAME, STRING_VALUE); - this.waitForEventQueueToClear(); - assertEquals(STRING_VALUE, this.testNode.get(KEY_NAME, null)); - this.verifyEvent(null, STRING_VALUE); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - } - - public void testDefaultValue() throws Exception { - // rebuild the adapter with a default value - String DEFAULT_VALUE = "default value"; - this.preferenceAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener); - this.preferenceAdapter = new PreferencePropertyValueModel<String>(this.nodeHolder, KEY_NAME, DEFAULT_VALUE); - this.preferenceAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener); - - assertEquals(STRING_VALUE, this.testNode.get(KEY_NAME, null)); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - assertNull(this.event); - - // remove the preference entirely... - this.testNode.remove(KEY_NAME); - this.waitForEventQueueToClear(); - assertNull(this.testNode.get(KEY_NAME, null)); - this.verifyEvent(STRING_VALUE, DEFAULT_VALUE); - assertEquals(DEFAULT_VALUE, this.preferenceAdapter.getValue()); - - // ...then re-add it with the same key - this.event = null; - this.testNode.put(KEY_NAME, STRING_VALUE); - this.waitForEventQueueToClear(); - assertEquals(STRING_VALUE, this.testNode.get(KEY_NAME, null)); - this.verifyEvent(DEFAULT_VALUE, STRING_VALUE); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - } - - public void testUnsynchronizedValue() throws Exception { - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - assertNull(this.event); - - // remove the this.listener so the adapter no longer listens to the preference - this.preferenceAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener); - - this.testNode.put(KEY_NAME, STRING_VALUE + STRING_VALUE); - this.waitForEventQueueToClear(); - // no this.event should have been fired... - assertNull(this.event); - // ...and the adapter's value should be null - assertNull(this.preferenceAdapter.getValue()); - - this.testNode.remove(KEY_NAME); - this.waitForEventQueueToClear(); - assertNull(this.event); - assertNull(this.preferenceAdapter.getValue()); - - this.testNode.put(KEY_NAME, STRING_VALUE); - this.waitForEventQueueToClear(); - assertNull(this.event); - assertNull(this.preferenceAdapter.getValue()); - - // add the this.listener so the adapter synchs - this.preferenceAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener); - assertEquals(STRING_VALUE, this.preferenceAdapter.getValue()); - } - - public void testIntegerPreference() throws Exception { - // stop listening to the node and convert it to an integer - this.preferenceAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener); - - PreferencePropertyValueModel<Integer> integerPreferenceAdapter = new PreferencePropertyValueModel<Integer>(this.nodeHolder, KEY_NAME); - this.testNode.putInt(KEY_NAME, 123); - integerPreferenceAdapter = PreferencePropertyValueModel.forInteger(this.testNode, KEY_NAME, 0); - integerPreferenceAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener); - assertEquals(new Integer(123), integerPreferenceAdapter.getValue()); - assertNull(this.event); - - this.testNode.putInt(KEY_NAME, 246); - this.waitForEventQueueToClear(); - this.verifyEvent(integerPreferenceAdapter, new Integer(123), new Integer(246)); - assertEquals(new Integer(246), integerPreferenceAdapter.getValue()); - - this.event = null; - this.testNode.remove(KEY_NAME); - this.waitForEventQueueToClear(); - this.verifyEvent(integerPreferenceAdapter, new Integer(246), new Integer(0)); - assertEquals(new Integer(0), integerPreferenceAdapter.getValue()); - - this.event = null; - this.testNode.putInt(KEY_NAME, 123); - this.waitForEventQueueToClear(); - this.verifyEvent(integerPreferenceAdapter, new Integer(0), new Integer(123)); - assertEquals(new Integer(123), integerPreferenceAdapter.getValue()); - } - - /** - * test a situation where - * - we are listening to the node when it gets removed from the preferences "repository" - * - we get notification that it has been removed - * - we try to remove our this.listener - * - the node will throw an IllegalStateException - the adapter should handle it OK... - */ - public void testRemoveNode() throws Exception { - assertTrue(this.preferenceAdapter.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - Preferences parent = this.testNode.parent(); - parent.addNodeChangeListener(this.buildParentNodeChangeListener()); - this.testNode.removeNode(); - this.testNode.flush(); // this seems to be required for the this.event to trigger... - this.waitForEventQueueToClear(); - - assertTrue(this.listenerRemoved); - assertTrue(this.preferenceAdapter.hasNoPropertyChangeListeners(PropertyValueModel.VALUE)); - } - - private NodeChangeListener buildParentNodeChangeListener() { - return new NodeChangeListener() { - public void childAdded(NodeChangeEvent e) { - throw new IllegalStateException("unexpected this.event: " + e); - } - public void childRemoved(NodeChangeEvent e) { - if (e.getChild() == PreferencePropertyValueModelTests.this.testNode) { - PreferencePropertyValueModelTests.this.preferenceAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, PreferencePropertyValueModelTests.this.listener); - // this line of code will not execute if the line above triggers an exception - PreferencePropertyValueModelTests.this.listenerRemoved = true; - } - } - }; - } - - public void testSetSameValue() { - assertNull(this.event); - assertNull(this.preferenceEvent); - this.testNode.addPreferenceChangeListener(this.buildPreferenceChangeListener()); - - String ANOTHER_STRING_VALUE = "some other value"; - this.preferenceAdapter.setValue(ANOTHER_STRING_VALUE); - - this.verifyEvent(STRING_VALUE, ANOTHER_STRING_VALUE); - this.waitForEventQueueToClear(); - this.verifyPreferenceEvent(ANOTHER_STRING_VALUE); - - // now set to *same* value - nothing should happen... - this.event = null; - this.preferenceEvent = null; - this.preferenceAdapter.setValue(ANOTHER_STRING_VALUE); - - assertNull(this.event); - assertNull(this.preferenceEvent); - } - - public void testSetSameValueForcePassThrough() throws Exception { - assertNull(this.event); - assertNull(this.preferenceEvent); - - this.preferenceAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, this.listener); - this.preferenceAdapter = new AlwaysUpdatePreferencePropertyValueModel<String>(this.nodeHolder, KEY_NAME); - this.preferenceAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, this.listener); - - this.testNode.addPreferenceChangeListener(this.buildPreferenceChangeListener()); - - String ANOTHER_STRING_VALUE = "some other value"; - this.preferenceAdapter.setValue(ANOTHER_STRING_VALUE); - - this.verifyEvent(STRING_VALUE, ANOTHER_STRING_VALUE); - this.waitForEventQueueToClear(); - this.verifyPreferenceEvent(ANOTHER_STRING_VALUE); - - // now set to *same* value - only one this.event should fire - this.event = null; - this.preferenceEvent = null; - this.preferenceAdapter.setValue(ANOTHER_STRING_VALUE); - - assertNull(this.event); - this.waitForEventQueueToClear(); - this.verifyPreferenceEvent(ANOTHER_STRING_VALUE); - assertNull(this.event); - } - - private PreferenceChangeListener buildPreferenceChangeListener() { - return new PreferenceChangeListener() { - public void preferenceChange(PreferenceChangeEvent evt) { - PreferencePropertyValueModelTests.this.preferenceEvent = evt; - } - }; - } - - private void verifyEvent(Model source, Object oldValue, Object newValue) { - assertNotNull(this.event); - assertEquals(source, this.event.getSource()); - assertEquals(PropertyValueModel.VALUE, this.event.getPropertyName()); - assertEquals(oldValue, this.event.getOldValue()); - assertEquals(newValue, this.event.getNewValue()); - } - - private void verifyEvent(Object oldValue, Object newValue) { - this.verifyEvent(this.preferenceAdapter, oldValue, newValue); - } - - private void verifyPreferenceEvent(Object newValue) { - assertNotNull(this.preferenceEvent); - assertEquals(this.testNode, this.preferenceEvent.getSource()); - assertEquals(KEY_NAME, this.preferenceEvent.getKey()); - assertEquals(newValue, this.preferenceEvent.getNewValue()); - assertEquals(newValue, this.testNode.get(KEY_NAME, "<missing preference>")); - } - - private boolean nodeHasAnyPrefListeners(Preferences node) throws Exception { - PreferenceChangeListener[] prefListeners = (PreferenceChangeListener[]) ReflectionTools.getFieldValue(node, "prefListeners"); - return prefListeners.length > 0; - } - - - /** - * Use this adapter to test out always passing through the new value - * to the preference. - */ - private class AlwaysUpdatePreferencePropertyValueModel<P> extends PreferencePropertyValueModel<P> { - - AlwaysUpdatePreferencePropertyValueModel(PropertyValueModel<Preferences> preferencesHolder, String key) { - super(preferencesHolder, key); - } - - @Override - protected boolean preferenceIsToBeSet(Object oldValue, Object newValue) { - return true; - } - - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencesCollectionValueModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencesCollectionValueModelTests.java deleted file mode 100644 index fe5349da73..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencesCollectionValueModelTests.java +++ /dev/null @@ -1,312 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.prefs; - -import java.util.HashMap; -import java.util.Map; -import java.util.prefs.NodeChangeEvent; -import java.util.prefs.NodeChangeListener; -import java.util.prefs.PreferenceChangeListener; -import java.util.prefs.Preferences; - -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.prefs.PreferencePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.prefs.PreferencesCollectionValueModel; -import org.eclipse.jpt.common.utility.model.event.CollectionAddEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionChangeEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionClearEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionEvent; -import org.eclipse.jpt.common.utility.model.event.CollectionRemoveEvent; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ChangeAdapter; -import org.eclipse.jpt.common.utility.model.listener.ChangeListener; -import org.eclipse.jpt.common.utility.model.listener.CollectionChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -@SuppressWarnings("nls") -public class PreferencesCollectionValueModelTests extends PreferencesTestCase { - private Map<String, String> expectedValues; - private ModifiablePropertyValueModel<Preferences> nodeHolder; - PreferencesCollectionValueModel<String> preferencesAdapter; - CollectionEvent event; - CollectionChangeListener listener; - private PropertyChangeListener itemListener; - boolean listenerRemoved = false; - private static final String KEY_NAME_1 = "foo 1"; - private static final String KEY_NAME_2 = "foo 2"; - private static final String KEY_NAME_3 = "foo 3"; - private static final String STRING_VALUE_1 = "original string value 1"; - private static final String STRING_VALUE_2 = "original string value 2"; - private static final String STRING_VALUE_3 = "original string value 3"; - - public PreferencesCollectionValueModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.expectedValues = new HashMap<String, String>(); - this.testNode.put(KEY_NAME_1, STRING_VALUE_1); this.expectedValues.put(KEY_NAME_1, STRING_VALUE_1); - this.testNode.put(KEY_NAME_2, STRING_VALUE_2); this.expectedValues.put(KEY_NAME_2, STRING_VALUE_2); - this.testNode.put(KEY_NAME_3, STRING_VALUE_3); this.expectedValues.put(KEY_NAME_3, STRING_VALUE_3); - - this.nodeHolder = new SimplePropertyValueModel<Preferences>(this.testNode); - this.preferencesAdapter = new PreferencesCollectionValueModel<String>(this.nodeHolder); - this.listener = this.buildCollectionChangeListener(); - this.itemListener = this.buildItemListener(); - this.preferencesAdapter.addCollectionChangeListener(CollectionValueModel.VALUES, this.listener); - this.event = null; - } - - private CollectionChangeListener buildCollectionChangeListener() { - return new CollectionChangeListener() { - public void collectionChanged(CollectionChangeEvent e) { - this.logEvent(e); - } - public void collectionCleared(CollectionClearEvent e) { - this.logEvent(e); - } - public void itemsAdded(CollectionAddEvent e) { - this.logEvent(e); - } - public void itemsRemoved(CollectionRemoveEvent e) { - this.logEvent(e); - } - private void logEvent(CollectionEvent e) { - if (PreferencesCollectionValueModelTests.this.event != null) { - throw new IllegalStateException("unexpected this.event: " + e); - } - PreferencesCollectionValueModelTests.this.event = e; - } - }; - } - - private PropertyChangeListener buildItemListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - throw new IllegalStateException("unexpected this.event: " + e); - } - }; - } - - public void testSubjectHolder() throws Exception { - this.verifyAdapter(this.preferencesAdapter); - assertNull(this.event); - - String ANOTHER_KEY_NAME_1 = "another key 1"; - String ANOTHER_KEY_NAME_2 = "another key 2"; - String ANOTHER_KEY_NAME_3 = "another key 3"; - String ANOTHER_STRING_VALUE_1 = "another string value 1"; - String ANOTHER_STRING_VALUE_2 = "another string value 2"; - String ANOTHER_STRING_VALUE_3 = "another string value 3"; - Preferences anotherNode = this.classNode.node("another test node"); - this.expectedValues.clear(); - anotherNode.put(ANOTHER_KEY_NAME_1, ANOTHER_STRING_VALUE_1); this.expectedValues.put(ANOTHER_KEY_NAME_1, ANOTHER_STRING_VALUE_1); - anotherNode.put(ANOTHER_KEY_NAME_2, ANOTHER_STRING_VALUE_2); this.expectedValues.put(ANOTHER_KEY_NAME_2, ANOTHER_STRING_VALUE_2); - anotherNode.put(ANOTHER_KEY_NAME_3, ANOTHER_STRING_VALUE_3); this.expectedValues.put(ANOTHER_KEY_NAME_3, ANOTHER_STRING_VALUE_3); - - this.nodeHolder.setValue(anotherNode); - // collectionChanged does not pass any items in the this.event - this.verifyEvent(); - this.verifyAdapter(this.preferencesAdapter); - - this.event = null; - this.expectedValues.clear(); - this.nodeHolder.setValue(null); - this.verifyEvent(); - assertFalse(this.preferencesAdapter.iterator().hasNext()); - - this.event = null; - this.nodeHolder.setValue(this.testNode); - this.verifyEvent(); - this.expectedValues.clear(); - this.expectedValues.put(KEY_NAME_1, STRING_VALUE_1); - this.expectedValues.put(KEY_NAME_2, STRING_VALUE_2); - this.expectedValues.put(KEY_NAME_3, STRING_VALUE_3); - this.verifyAdapter(this.preferencesAdapter); - } - - public void testAddPreference() throws Exception { - this.verifyAdapter(this.preferencesAdapter); - assertNull(this.event); - - String ANOTHER_KEY_NAME = "another key"; - String ANOTHER_STRING_VALUE = "another string value"; - this.testNode.put(ANOTHER_KEY_NAME, ANOTHER_STRING_VALUE); - this.waitForEventQueueToClear(); - Map<String, String> expectedItems = new HashMap<String, String>(); - expectedItems.put(ANOTHER_KEY_NAME, ANOTHER_STRING_VALUE); - this.verifyEvent(expectedItems); - this.expectedValues.put(ANOTHER_KEY_NAME, ANOTHER_STRING_VALUE); - this.verifyAdapter(this.preferencesAdapter); - } - - public void testRemovePreference() throws Exception { - this.verifyAdapter(this.preferencesAdapter); - assertNull(this.event); - - this.testNode.remove(KEY_NAME_2); - this.waitForEventQueueToClear(); - - assertNotNull(this.event); - assertEquals(this.preferencesAdapter, this.event.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event.getCollectionName()); - assertEquals(1, ((CollectionRemoveEvent) this.event).getItemsSize()); - @SuppressWarnings("unchecked") - String key = ((PreferencePropertyValueModel<String>) ((CollectionRemoveEvent) this.event).getItems().iterator().next()).getKey(); - assertEquals(KEY_NAME_2, key); - - this.expectedValues.remove(KEY_NAME_2); - this.verifyAdapter(this.preferencesAdapter); - } - - public void testChangePreference() throws Exception { - this.verifyAdapter(this.preferencesAdapter); - assertNull(this.event); - - String DIFFERENT = "something completely different"; - this.testNode.put(KEY_NAME_2, DIFFERENT); - this.waitForEventQueueToClear(); - - assertNull(this.event); - - this.expectedValues.put(KEY_NAME_2, DIFFERENT); - this.verifyAdapter(this.preferencesAdapter); - } - - public void testValues() throws Exception { - this.verifyNode(this.testNode); - this.verifyAdapter(this.preferencesAdapter); - } - - /** - * test a situation where - * - we are listening to the node when it gets removed from the preferences "repository" - * - we get notification that it has been removed - * - we try to remove our this.listener - * - the node will throw an IllegalStateException - the adapter should handle it OK... - */ - public void testRemoveNode() throws Exception { - assertTrue(this.preferencesAdapter.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - Preferences parent = this.testNode.parent(); - parent.addNodeChangeListener(this.buildParentNodeChangeListener()); - this.testNode.removeNode(); - this.testNode.flush(); // this seems to be required for the this.event to trigger... - this.waitForEventQueueToClear(); - - assertTrue(this.listenerRemoved); - assertFalse(this.preferencesAdapter.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - private NodeChangeListener buildParentNodeChangeListener() { - return new NodeChangeListener() { - public void childAdded(NodeChangeEvent e) { - throw new IllegalStateException("unexpected this.event: " + e); - } - public void childRemoved(NodeChangeEvent e) { - if (e.getChild() == PreferencesCollectionValueModelTests.this.testNode) { - PreferencesCollectionValueModelTests.this.preferencesAdapter.removeCollectionChangeListener(CollectionValueModel.VALUES, PreferencesCollectionValueModelTests.this.listener); - // this line of code will not execute if the line above triggers an exception - PreferencesCollectionValueModelTests.this.listenerRemoved = true; - } - } - }; - } - - public void testHasListeners() throws Exception { - assertTrue(this.preferencesAdapter.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertTrue(this.nodeHasAnyPrefListeners(this.testNode)); - this.preferencesAdapter.removeCollectionChangeListener(CollectionValueModel.VALUES, this.listener); - assertFalse(this.nodeHasAnyPrefListeners(this.testNode)); - assertFalse(this.preferencesAdapter.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - - ChangeListener listener2 = this.buildChangeListener(); - this.preferencesAdapter.addChangeListener(listener2); - assertTrue(this.preferencesAdapter.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - assertTrue(this.nodeHasAnyPrefListeners(this.testNode)); - this.preferencesAdapter.removeChangeListener(listener2); - assertFalse(this.nodeHasAnyPrefListeners(this.testNode)); - assertFalse(this.preferencesAdapter.hasAnyCollectionChangeListeners(CollectionValueModel.VALUES)); - } - - private ChangeListener buildChangeListener() { - return new ChangeAdapter() { - @Override - public void collectionChanged(CollectionChangeEvent e) { - this.logEvent(e); - } - @Override - public void collectionCleared(CollectionClearEvent e) { - this.logEvent(e); - } - @Override - public void itemsAdded(CollectionAddEvent e) { - this.logEvent(e); - } - @Override - public void itemsRemoved(CollectionRemoveEvent e) { - this.logEvent(e); - } - private void logEvent(CollectionEvent e) { - if (PreferencesCollectionValueModelTests.this.event != null) { - throw new IllegalStateException("unexpected this.event: " + e); - } - PreferencesCollectionValueModelTests.this.event = e; - } - }; - } - - private void verifyEvent(Map<String, String> items) { - this.verifyEvent(); - assertEquals(items.size(), ((CollectionAddEvent) this.event).getItemsSize()); - @SuppressWarnings("unchecked") - Iterable<PreferencePropertyValueModel<String>> eventItems = (Iterable<PreferencePropertyValueModel<String>>) ((CollectionAddEvent) this.event).getItems(); - this.verifyItems(items, eventItems); - } - - private void verifyEvent() { - assertNotNull(this.event); - assertEquals(this.preferencesAdapter, this.event.getSource()); - assertEquals(CollectionValueModel.VALUES, this.event.getCollectionName()); - } - - private void verifyNode(Preferences node) throws Exception { - String[] keys = node.keys(); - assertEquals(this.expectedValues.size(), keys.length); - for (int i = 0; i < keys.length; i++) { - assertEquals(this.expectedValues.get(keys[i]), node.get(keys[i], "<missing preference>")); - } - } - - private void verifyAdapter(PreferencesCollectionValueModel<String> cvm) { - assertEquals(this.expectedValues.size(), cvm.size()); - this.verifyItems(this.expectedValues, cvm); - } - - private void verifyItems(Map<String, String> expected, Iterable<PreferencePropertyValueModel<String>> actual) { - for (PreferencePropertyValueModel<String> model : actual) { - model.addPropertyChangeListener(PropertyValueModel.VALUE, this.itemListener); - assertEquals(expected.get(model.getKey()), model.getValue()); - model.removePropertyChangeListener(PropertyValueModel.VALUE, this.itemListener); - } - } - - private boolean nodeHasAnyPrefListeners(Preferences node) throws Exception { - PreferenceChangeListener[] prefListeners = (PreferenceChangeListener[]) ReflectionTools.getFieldValue(node, "prefListeners"); - return prefListeners.length > 0; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencesTestCase.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencesTestCase.java deleted file mode 100644 index 3ae2c74db7..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/prefs/PreferencesTestCase.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.prefs; - -import java.util.EventObject; -import java.util.List; -import java.util.prefs.AbstractPreferences; -import java.util.prefs.Preferences; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -/** - * set up and tear down a test node for any subclass that - * needs to test preferences-related stuff - */ -@SuppressWarnings("nls") -public abstract class PreferencesTestCase extends TestCase { - protected Preferences classNode; - public Preferences testNode; - protected static final String TEST_NODE_NAME = "test node"; - - public PreferencesTestCase(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - Preferences packageNode = Preferences.userNodeForPackage(this.getClass()); - this.classNode = packageNode.node(this.getClass().getSimpleName()); - // clean out any leftover crap... - if ((this.classNode.keys().length > 0) || (this.classNode.childrenNames().length > 0)) { - this.classNode.removeNode(); - // ...and re-create the node - this.classNode = packageNode.node(this.getClass().getSimpleName()); - } - this.testNode = this.classNode.node(TEST_NODE_NAME); - } - - @Override - protected void tearDown() throws Exception { - // wait for all the events to be delivered before tearing down - this.waitForEventQueueToClear(); - Preferences node = this.classNode.parent(); - this.classNode.removeNode(); - while (this.nodeIsVestigial(node)) { - Preferences parent = node.parent(); - node.removeNode(); - node = parent; - } - TestTools.clear(this); - super.tearDown(); - } - - private boolean nodeIsVestigial(Preferences node) throws Exception { - return (node != null) - && (node.keys().length == 0) - && (node.childrenNames().length == 0) - && (node != Preferences.userRoot()); - } - - protected void waitForEventQueueToClear() { - while ( ! this.preferencesEventQueue().isEmpty()) { - TestTools.sleep(100); - } - TestTools.sleep(100); - } - - @SuppressWarnings("unchecked") - private List<EventObject> preferencesEventQueue() { - return (List<EventObject>) ReflectionTools.getStaticFieldValue(AbstractPreferences.class, "eventQueue"); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/CheckBoxModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/CheckBoxModelAdapterTests.java deleted file mode 100644 index ded9a0334c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/CheckBoxModelAdapterTests.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.ButtonModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.EventListenerList; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.CheckBoxModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class CheckBoxModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Boolean> booleanHolder; - private ButtonModel buttonModelAdapter; - boolean eventFired; - - public CheckBoxModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.booleanHolder = new SimplePropertyValueModel<Boolean>(Boolean.TRUE); - this.buttonModelAdapter = new CheckBoxModelAdapter(this.booleanHolder) { - @Override - protected PropertyChangeListener buildBooleanChangeListener() { - return this.buildBooleanChangeListener_(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSetSelected() throws Exception { - this.eventFired = false; - this.buttonModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - CheckBoxModelAdapterTests.this.eventFired = true; - } - }); - this.buttonModelAdapter.setSelected(false); - assertTrue(this.eventFired); - assertEquals(Boolean.FALSE, this.booleanHolder.getValue()); - } - - public void testSetValue() throws Exception { - this.eventFired = false; - this.buttonModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - CheckBoxModelAdapterTests.this.eventFired = true; - } - }); - assertTrue(this.buttonModelAdapter.isSelected()); - this.booleanHolder.setValue(Boolean.FALSE); - assertTrue(this.eventFired); - assertFalse(this.buttonModelAdapter.isSelected()); - } - - public void testDefaultValue() throws Exception { - this.eventFired = false; - this.buttonModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - CheckBoxModelAdapterTests.this.eventFired = true; - } - }); - assertTrue(this.buttonModelAdapter.isSelected()); - this.booleanHolder.setValue(null); - assertTrue(this.eventFired); - assertFalse(this.buttonModelAdapter.isSelected()); - - this.eventFired = false; - this.booleanHolder.setValue(Boolean.FALSE); - assertFalse(this.eventFired); - assertFalse(this.buttonModelAdapter.isSelected()); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<Boolean> localBooleanHolder = (SimplePropertyValueModel<Boolean>) this.booleanHolder; - assertFalse(localBooleanHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.buttonModelAdapter); - - ChangeListener listener = new TestChangeListener(); - this.buttonModelAdapter.addChangeListener(listener); - assertTrue(localBooleanHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.buttonModelAdapter); - - this.buttonModelAdapter.removeChangeListener(listener); - assertFalse(localBooleanHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.buttonModelAdapter); - } - - private void verifyHasNoListeners(Object model) throws Exception { - EventListenerList listenerList = (EventListenerList) ReflectionTools.getFieldValue(model, "listenerList"); - assertEquals(0, listenerList.getListenerList().length); - } - - private void verifyHasListeners(Object model) throws Exception { - EventListenerList listenerList = (EventListenerList) ReflectionTools.getFieldValue(model, "listenerList"); - assertFalse(listenerList.getListenerList().length == 0); - } - - - // ********** member class ********** - private class TestChangeListener implements ChangeListener { - TestChangeListener() { - super(); - } - public void stateChanged(ChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/CheckBoxModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/CheckBoxModelAdapterUITest.java deleted file mode 100644 index 91faa42d64..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/CheckBoxModelAdapterUITest.java +++ /dev/null @@ -1,314 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ButtonModel; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.WindowConstants; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.CheckBoxModelAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -/** - * Play around with a set of check boxes. - */ -@SuppressWarnings("nls") -public class CheckBoxModelAdapterUITest { - - private TestModel testModel; - private ModifiablePropertyValueModel<TestModel> testModelHolder; - private ModifiablePropertyValueModel<Boolean> flag1Holder; - private ModifiablePropertyValueModel<Boolean> flag2Holder; - private ModifiablePropertyValueModel<Boolean> notFlag2Holder; - private ButtonModel flag1ButtonModel; - private ButtonModel flag2ButtonModel; - private ButtonModel notFlag2ButtonModel; - - public static void main(String[] args) throws Exception { - new CheckBoxModelAdapterUITest().exec(); - } - - private CheckBoxModelAdapterUITest() { - super(); - } - - private void exec() throws Exception { - this.testModel = new TestModel(true, true); - this.testModelHolder = new SimplePropertyValueModel<TestModel>(this.testModel); - this.flag1Holder = this.buildFlag1Holder(this.testModelHolder); - this.flag1ButtonModel = this.buildCheckBoxModelAdapter(this.flag1Holder); - this.flag2Holder = this.buildFlag2Holder(this.testModelHolder); - this.flag2ButtonModel = this.buildCheckBoxModelAdapter(this.flag2Holder); - this.notFlag2Holder = this.buildNotFlag2Holder(this.testModelHolder); - this.notFlag2ButtonModel = this.buildCheckBoxModelAdapter(this.notFlag2Holder); - this.openWindow(); - } - - private ModifiablePropertyValueModel<Boolean> buildFlag1Holder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Boolean>(vm, TestModel.FLAG1_PROPERTY) { - @Override - protected Boolean buildValue_() { - return Boolean.valueOf(this.subject.isFlag1()); - } - @Override - protected void setValue_(Boolean value) { - this.subject.setFlag1(value.booleanValue()); - } - }; - } - - private ModifiablePropertyValueModel<Boolean> buildFlag2Holder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Boolean>(vm, TestModel.FLAG2_PROPERTY) { - @Override - protected Boolean buildValue_() { - return Boolean.valueOf(this.subject.isFlag2()); - } - @Override - protected void setValue_(Boolean value) { - this.subject.setFlag2(value.booleanValue()); - } - }; - } - - private ModifiablePropertyValueModel<Boolean> buildNotFlag2Holder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Boolean>(vm, TestModel.NOT_FLAG2_PROPERTY) { - @Override - protected Boolean buildValue_() { - return Boolean.valueOf(this.subject.isNotFlag2()); - } - @Override - protected void setValue_(Boolean value) { - this.subject.setNotFlag2(value.booleanValue()); - } - }; - } - - private ButtonModel buildCheckBoxModelAdapter(ModifiablePropertyValueModel<Boolean> booleanHolder) { - return new CheckBoxModelAdapter(booleanHolder); - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setSize(400, 100); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildCheckBoxPanel(), BorderLayout.NORTH); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildCheckBoxPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(1, 0)); - taskListPanel.add(this.buildFlag1CheckBox()); - taskListPanel.add(this.buildFlag2CheckBox()); - taskListPanel.add(this.buildNotFlag2CheckBox()); - taskListPanel.add(this.buildUnattachedCheckBox()); - return taskListPanel; - } - - private JCheckBox buildFlag1CheckBox() { - JCheckBox checkBox = new JCheckBox(); - checkBox.setText("flag 1"); - checkBox.setModel(this.flag1ButtonModel); - return checkBox; - } - - private JCheckBox buildFlag2CheckBox() { - JCheckBox checkBox = new JCheckBox(); - checkBox.setText("flag 2"); - checkBox.setModel(this.flag2ButtonModel); - return checkBox; - } - - private JCheckBox buildNotFlag2CheckBox() { - JCheckBox checkBox = new JCheckBox(); - checkBox.setText("not flag 2"); - checkBox.setModel(this.notFlag2ButtonModel); - return checkBox; - } - - private JCheckBox buildUnattachedCheckBox() { - JCheckBox checkBox = new JCheckBox("unattached"); - checkBox.getModel().addItemListener(this.buildUnattachedItemListener()); - return checkBox; - } - - private ItemListener buildUnattachedItemListener() { - return new ItemListener() { - public void itemStateChanged(ItemEvent e) { - System.out.println("unattached state changed: " + e); - } - }; - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(1, 0)); - controlPanel.add(this.buildFlipFlag1Button()); - controlPanel.add(this.buildClearModelButton()); - controlPanel.add(this.buildRestoreModelButton()); - controlPanel.add(this.buildPrintModelButton()); - return controlPanel; - } - - private JButton buildFlipFlag1Button() { - return new JButton(this.buildFlipFlag1Action()); - } - - private Action buildFlipFlag1Action() { - Action action = new AbstractAction("flip flag 1") { - public void actionPerformed(ActionEvent event) { - CheckBoxModelAdapterUITest.this.flipFlag1(); - } - }; - action.setEnabled(true); - return action; - } - - void flipFlag1() { - this.testModel.setFlag1( ! this.testModel.isFlag1()); - } - - private JButton buildClearModelButton() { - return new JButton(this.buildClearModelAction()); - } - - private Action buildClearModelAction() { - Action action = new AbstractAction("clear model") { - public void actionPerformed(ActionEvent event) { - CheckBoxModelAdapterUITest.this.clearModel(); - } - }; - action.setEnabled(true); - return action; - } - - void clearModel() { - this.testModelHolder.setValue(null); - } - - private JButton buildRestoreModelButton() { - return new JButton(this.buildRestoreModelAction()); - } - - private Action buildRestoreModelAction() { - Action action = new AbstractAction("restore model") { - public void actionPerformed(ActionEvent event) { - CheckBoxModelAdapterUITest.this.restoreModel(); - } - }; - action.setEnabled(true); - return action; - } - - void restoreModel() { - this.testModelHolder.setValue(this.testModel); - } - - private JButton buildPrintModelButton() { - return new JButton(this.buildPrintModelAction()); - } - - private Action buildPrintModelAction() { - Action action = new AbstractAction("print model") { - public void actionPerformed(ActionEvent event) { - CheckBoxModelAdapterUITest.this.printModel(); - } - }; - action.setEnabled(true); - return action; - } - - void printModel() { - System.out.println("flag 1: " + this.testModel.isFlag1()); - System.out.println("flag 2: " + this.testModel.isFlag2()); - System.out.println("not flag 2: " + this.testModel.isNotFlag2()); - System.out.println("***"); - } - - - private class TestModel extends AbstractModel { - private boolean flag1; - public static final String FLAG1_PROPERTY = "flag1"; - private boolean flag2; - public static final String FLAG2_PROPERTY = "flag2"; - private boolean notFlag2; - public static final String NOT_FLAG2_PROPERTY = "notFlag2"; - - public TestModel(boolean flag1, boolean flag2) { - this.flag1 = flag1; - this.flag2 = flag2; - this.notFlag2 = ! flag2; - } - public boolean isFlag1() { - return this.flag1; - } - public void setFlag1(boolean flag1) { - boolean old = this.flag1; - this.flag1 = flag1; - this.firePropertyChanged(FLAG1_PROPERTY, old, flag1); - } - public boolean isFlag2() { - return this.flag2; - } - public void setFlag2(boolean flag2) { - boolean old = this.flag2; - this.flag2 = flag2; - this.firePropertyChanged(FLAG2_PROPERTY, old, flag2); - - old = this.notFlag2; - this.notFlag2 = ! flag2; - this.firePropertyChanged(NOT_FLAG2_PROPERTY, old, this.notFlag2); - } - public boolean isNotFlag2() { - return this.notFlag2; - } - public void setNotFlag2(boolean notFlag2) { - this.setFlag2( ! notFlag2); - } - @Override - public String toString() { - return "TestModel(" + this.isFlag1() + " - " + this.isFlag2() + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterTests.java deleted file mode 100644 index 891611573d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterTests.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import javax.swing.ComboBoxModel; -import javax.swing.ListModel; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ComboBoxModelAdapter; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.internal.swing.SimpleDisplayable; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.model.value.CoordinatedList; - -@SuppressWarnings("nls") -public class ComboBoxModelAdapterTests extends TestCase { - - public ComboBoxModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - // nothing yet... - } - - @Override - protected void tearDown() throws Exception { - // nothing yet... - super.tearDown(); - } - - public void testHasListeners() throws Exception { - SimpleListValueModel<Displayable> listHolder = this.buildListHolder(); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - SimplePropertyValueModel<Object> selectionHolder = new SimplePropertyValueModel<Object>(listHolder.iterator().next()); - assertFalse(selectionHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - - ComboBoxModel comboBoxModel = new ComboBoxModelAdapter(listHolder, selectionHolder); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(selectionHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(comboBoxModel); - - CoordinatedList<Displayable> synchList = new CoordinatedList<Displayable>(comboBoxModel); - PropertyChangeListener selectionListener = this.buildSelectionListener(); - selectionHolder.addPropertyChangeListener(PropertyValueModel.VALUE, selectionListener); - assertTrue(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(selectionHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(comboBoxModel); - - comboBoxModel.removeListDataListener(synchList); - selectionHolder.removePropertyChangeListener(PropertyValueModel.VALUE, selectionListener); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertFalse(selectionHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(comboBoxModel); - } - - private PropertyChangeListener buildSelectionListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent evt) { - // do nothing... - } - }; - } - - private void verifyHasNoListeners(ListModel listModel) throws Exception { - boolean hasNoListeners = ((Boolean) ReflectionTools.executeMethod(listModel, "hasNoListDataListeners")).booleanValue(); - assertTrue(hasNoListeners); - } - - private void verifyHasListeners(ListModel listModel) throws Exception { - boolean hasListeners = ((Boolean) ReflectionTools.executeMethod(listModel, "hasListDataListeners")).booleanValue(); - assertTrue(hasListeners); - } - - private SimpleListValueModel<Displayable> buildListHolder() { - return new SimpleListValueModel<Displayable>(this.buildList()); - } - - private List<Displayable> buildList() { - List<Displayable> list = new ArrayList<Displayable>(); - this.populateCollection(list); - return list; - } - - private void populateCollection(Collection<Displayable> c) { - c.add(new SimpleDisplayable("foo")); - c.add(new SimpleDisplayable("bar")); - c.add(new SimpleDisplayable("baz")); - c.add(new SimpleDisplayable("joo")); - c.add(new SimpleDisplayable("jar")); - c.add(new SimpleDisplayable("jaz")); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterUITest.java deleted file mode 100644 index ac12b38a71..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterUITest.java +++ /dev/null @@ -1,393 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ComboBoxModel; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.ListCellRenderer; -import javax.swing.UIManager; -import javax.swing.WindowConstants; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ComboBoxModelAdapter; -import org.eclipse.jpt.common.utility.internal.swing.FilteringListBrowser; -import org.eclipse.jpt.common.utility.internal.swing.ListChooser; -import org.eclipse.jpt.common.utility.internal.swing.SimpleListCellRenderer; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - - -/** - * Play around with a set of combo-boxes. - * - * DefaultLongListBrowserDialogUITest subclasses this class; so be - * careful when making changes. - */ -@SuppressWarnings("nls") -public class ComboBoxModelAdapterUITest { - - protected JFrame window; - private TestModel testModel; - private ModifiablePropertyValueModel<TestModel> testModelHolder; - private ModifiablePropertyValueModel<Object> colorHolder; - private SimpleListValueModel<String> colorListHolder; - protected ComboBoxModel colorComboBoxModel; - private int nextColorNumber = 0; - - public static void main(String[] args) throws Exception { - new ComboBoxModelAdapterUITest().exec(); - } - - protected ComboBoxModelAdapterUITest() { - super(); - } - - protected void exec() throws Exception { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); -// UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); // Metal LAF -// UIManager.setLookAndFeel(com.sun.java.swing.plaf.windows.WindowsLookAndFeel.class.getName()); -// UIManager.setLookAndFeel(com.sun.java.swing.plaf.motif.MotifLookAndFeel.class.getName()); -// UIManager.setLookAndFeel(oracle.bali.ewt.olaf.OracleLookAndFeel.class.getName()); - this.testModel = this.buildTestModel(); - this.testModelHolder = new SimplePropertyValueModel<TestModel>(this.testModel); - this.colorHolder = this.buildColorHolder(this.testModelHolder); - this.colorListHolder = this.buildColorListHolder(); - this.colorComboBoxModel = this.buildComboBoxModelAdapter(this.colorListHolder, this.colorHolder); - this.openWindow(); - } - - private ModifiablePropertyValueModel<Object> buildColorHolder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Object>(vm, TestModel.COLOR_PROPERTY) { - @Override - protected String buildValue_() { - return this.subject.getColor(); - } - @Override - protected void setValue_(Object value) { - this.subject.setColor((String) value); - } - }; - } - - protected TestModel buildTestModel() { - return new TestModel(); - } - - private SimpleListValueModel<String> buildColorListHolder() { - return new SimpleListValueModel<String>(TestModel.validColors()); -// return new AbstractReadOnlyListValueModel() { -// public Object value() { -// return new ArrayListIterator(TestModel.VALID_COLORS); -// } -// public int size() { -// return TestModel.VALID_COLORS.length; -// } -// }; - } - - protected ListValueModel<String> uiColorListHolder() { - return this.colorListHolder; - } - - private ComboBoxModel buildComboBoxModelAdapter(ListValueModel<String> listHolder, ModifiablePropertyValueModel<Object> selectionHolder) { - return new ComboBoxModelAdapter(listHolder, selectionHolder); - } - - private void openWindow() { - this.window = new JFrame(this.getClass().getSimpleName()); - this.window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - this.window.addWindowListener(this.buildWindowListener()); - this.window.getContentPane().add(this.buildMainPanel(), "Center"); - this.window.setLocation(300, 300); - this.window.setSize(400, 150); - this.window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildComboBoxPanel(), BorderLayout.NORTH); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - protected JPanel buildComboBoxPanel() { - JPanel panel = new JPanel(new GridLayout(1, 0)); - panel.add(this.buildComboBox()); - panel.add(this.buildComboBox()); - panel.add(this.buildListChooser1()); - panel.add(this.buildListChooser2()); - return panel; - } - - private JComboBox buildComboBox() { - JComboBox comboBox = new JComboBox(this.colorComboBoxModel); - comboBox.setRenderer(this.buildComboBoxRenderer()); - return comboBox; - } - - protected ListCellRenderer buildComboBoxRenderer() { - return new SimpleListCellRenderer() { - @Override - protected String buildText(Object value) { - return super.buildText(value); - } - }; - } - - private ListChooser buildListChooser1() { - return new LocalListChooser1(this.colorComboBoxModel); - } - - private ListChooser buildListChooser2() { - return new LocalListChooser2(this.colorComboBoxModel); - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(2, 0)); - controlPanel.add(this.buildResetColorButton()); - controlPanel.add(this.buildClearModelButton()); - controlPanel.add(this.buildRestoreModelButton()); - controlPanel.add(this.buildPrintModelButton()); - controlPanel.add(this.buildAddTenButton()); - controlPanel.add(this.buildRemoveTenButton()); - return controlPanel; - } - - // ********** reset color button ********** - private JButton buildResetColorButton() { - return new JButton(this.buildResetColorAction()); - } - - private Action buildResetColorAction() { - Action action = new AbstractAction("reset color") { - public void actionPerformed(ActionEvent event) { - ComboBoxModelAdapterUITest.this.resetColor(); - } - }; - action.setEnabled(true); - return action; - } - - void resetColor() { - this.testModel.setColor(TestModel.DEFAULT_COLOR); - } - - // ********** clear model button ********** - private JButton buildClearModelButton() { - return new JButton(this.buildClearModelAction()); - } - - private Action buildClearModelAction() { - Action action = new AbstractAction("clear model") { - public void actionPerformed(ActionEvent event) { - ComboBoxModelAdapterUITest.this.clearModel(); - } - }; - action.setEnabled(true); - return action; - } - - void clearModel() { - this.testModelHolder.setValue(null); - } - - // ********** restore model button ********** - private JButton buildRestoreModelButton() { - return new JButton(this.buildRestoreModelAction()); - } - - private Action buildRestoreModelAction() { - Action action = new AbstractAction("restore model") { - public void actionPerformed(ActionEvent event) { - ComboBoxModelAdapterUITest.this.restoreModel(); - } - }; - action.setEnabled(true); - return action; - } - - void restoreModel() { - this.testModelHolder.setValue(this.testModel); - } - - // ********** print model button ********** - private JButton buildPrintModelButton() { - return new JButton(this.buildPrintModelAction()); - } - - private Action buildPrintModelAction() { - Action action = new AbstractAction("print model") { - public void actionPerformed(ActionEvent event) { - ComboBoxModelAdapterUITest.this.printModel(); - } - }; - action.setEnabled(true); - return action; - } - - void printModel() { - System.out.println(this.testModel); - } - - // ********** add 20 button ********** - private JButton buildAddTenButton() { - return new JButton(this.buildAddTenAction()); - } - - private Action buildAddTenAction() { - Action action = new AbstractAction("add 20") { - public void actionPerformed(ActionEvent event) { - ComboBoxModelAdapterUITest.this.addTen(); - } - }; - action.setEnabled(true); - return action; - } - - void addTen() { - for (int i = this.nextColorNumber; i < this.nextColorNumber + 20; i++) { - this.colorListHolder.add(this.colorListHolder.size(), "color" + i); - } - this.nextColorNumber += 20; - } - - // ********** remove 20 button ********** - private JButton buildRemoveTenButton() { - return new JButton(this.buildRemoveTenAction()); - } - - private Action buildRemoveTenAction() { - Action action = new AbstractAction("remove 20") { - public void actionPerformed(ActionEvent event) { - ComboBoxModelAdapterUITest.this.removeTen(); - } - }; - action.setEnabled(true); - return action; - } - - void removeTen() { - for (int i = 0; i < 20; i++) { - if (this.colorListHolder.size() > 0) { - this.colorListHolder.remove(this.colorListHolder.size() - 1); - } - } - } - - - protected static class TestModel extends AbstractModel { - private String color; - public static final String COLOR_PROPERTY = "color"; - public static final String RED = "red"; - public static final String ORANGE = "orange"; - public static final String YELLOW = "yellow"; - public static final String GREEN = "green"; - public static final String BLUE = "blue"; - public static final String INDIGO = "indigo"; - public static final String VIOLET = "violet"; - public static final String DEFAULT_COLOR = RED; - public static List<String> validColors; - public static final String[] DEFAULT_VALID_COLORS = { - RED, - ORANGE, - YELLOW, - GREEN, - BLUE, - INDIGO, - VIOLET - }; - - public static List<String> validColors() { - if (validColors == null) { - validColors = buildDefaultValidColors(); - } - return validColors; - } - public static List<String> buildDefaultValidColors() { - List<String> result = new ArrayList<String>(); - CollectionTools.addAll(result, DEFAULT_VALID_COLORS); - return result; - } - - public TestModel() { - this(DEFAULT_COLOR); - } - public TestModel(String color) { - this.color = color; - } - public String getColor() { - return this.color; - } - public void setColor(String color) { - this.checkColor(color); - Object old = this.color; - this.color = color; - this.firePropertyChanged(COLOR_PROPERTY, old, color); - } - public void checkColor(String c) { - if ( ! validColors().contains(c)) { - throw new IllegalArgumentException(c); - } - } - @Override - public String toString() { - return "TestModel(" + this.color + ")"; - } - } - - - private class LocalListChooser1 extends ListChooser { - public LocalListChooser1(ComboBoxModel model) { - super(model); - } - } - - - private class LocalListChooser2 extends ListChooser { - public LocalListChooser2(ComboBoxModel model) { - super(model); - } - @Override - protected ListBrowser buildBrowser() { - return new FilteringListBrowser<String>(); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterUITest2.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterUITest2.java deleted file mode 100644 index ed00f4cf18..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ComboBoxModelAdapterUITest2.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.ListCellRenderer; -import org.eclipse.jpt.common.utility.internal.model.value.ExtendedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.swing.SimpleListCellRenderer; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; - -/** - * - */ -@SuppressWarnings("nls") -public class ComboBoxModelAdapterUITest2 extends ComboBoxModelAdapterUITest { - - public static void main(String[] args) throws Exception { - new ComboBoxModelAdapterUITest2().exec(); - } - - public ComboBoxModelAdapterUITest2() { - super(); - } - - /** - * use a different model that allows the color to be set to null - */ - @Override - protected TestModel buildTestModel() { - return new TestModel2(); - } - - /** - * add a null to the front of the list - */ - @Override - protected ListValueModel<String> uiColorListHolder() { - // the default is to prepend the wrapped list with a null item - return new ExtendedListValueModelWrapper<String>(super.uiColorListHolder()); - } - - /** - * convert null to some text - */ - @Override - protected ListCellRenderer buildComboBoxRenderer() { - return new SimpleListCellRenderer() { - @Override - protected String buildText(Object value) { - return (value == null) ? "<none selected>" : super.buildText(value); - } - }; - } - - - protected static class TestModel2 extends TestModel { - /** - * null is OK here - */ - @Override - public void checkColor(String color) { - if (color == null) { - return; - } - super.checkColor(color); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DateSpinnerModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DateSpinnerModelAdapterTests.java deleted file mode 100644 index 813550a23e..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DateSpinnerModelAdapterTests.java +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.util.Date; -import javax.swing.SpinnerModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.DateSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class DateSpinnerModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Object> valueHolder; - private SpinnerModel spinnerModelAdapter; - boolean eventFired; - - public DateSpinnerModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.valueHolder = new SimplePropertyValueModel<Object>(new Date()); - this.spinnerModelAdapter = new DateSpinnerModelAdapter(this.valueHolder) { - @Override - protected PropertyChangeListener buildDateChangeListener() { - return this.buildDateChangeListener_(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSetValueSpinnerModel() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - DateSpinnerModelAdapterTests.this.eventFired = true; - } - }); - Date newDate = new Date(); - newDate.setTime(777777); - this.spinnerModelAdapter.setValue(newDate); - assertTrue(this.eventFired); - assertEquals(777777, ((Date) this.valueHolder.getValue()).getTime()); - } - - public void testSetValueValueHolder() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - DateSpinnerModelAdapterTests.this.eventFired = true; - } - }); - Date newDate = new Date(); - newDate.setTime(777777); - this.valueHolder.setValue(newDate); - assertTrue(this.eventFired); - assertEquals(777777, ((Date) this.spinnerModelAdapter.getValue()).getTime()); - } - - public void testDefaultValue() throws Exception { - Date newDate = new Date(); - newDate.setTime(777777); - this.valueHolder.setValue(newDate); - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - DateSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(777777, ((Date) this.spinnerModelAdapter.getValue()).getTime()); - this.valueHolder.setValue(null); - assertTrue(this.eventFired); - assertFalse(((Date) this.spinnerModelAdapter.getValue()).getTime() == 777777); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<Object> localValueHolder = (SimplePropertyValueModel<Object>) this.valueHolder; - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - - ChangeListener listener = new TestChangeListener(); - this.spinnerModelAdapter.addChangeListener(listener); - assertTrue(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.spinnerModelAdapter); - - this.spinnerModelAdapter.removeChangeListener(listener); - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - } - - private void verifyHasNoListeners(SpinnerModel adapter) throws Exception { - assertEquals(0, ((DateSpinnerModelAdapter) adapter).getChangeListeners().length); - } - - private void verifyHasListeners(Object adapter) throws Exception { - assertFalse(((DateSpinnerModelAdapter) adapter).getChangeListeners().length == 0); - } - - public void testNullInitialValue() { - Date today = new Date(); - this.valueHolder = new SimplePropertyValueModel<Object>(); - this.spinnerModelAdapter = new DateSpinnerModelAdapter(this.valueHolder, today) { - @Override - protected PropertyChangeListener buildDateChangeListener() { - return this.buildDateChangeListener_(); - } - }; - - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - DateSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(today, this.spinnerModelAdapter.getValue()); - - Date newDate = new Date(); - newDate.setTime(777777); - this.valueHolder.setValue(newDate); - - assertTrue(this.eventFired); - assertEquals(777777, ((Date) this.spinnerModelAdapter.getValue()).getTime()); - } - - - // ********** inner class ********** - private class TestChangeListener implements ChangeListener { - TestChangeListener() { - super(); - } - public void stateChanged(ChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DocumentAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DocumentAdapterTests.java deleted file mode 100644 index 8a271c029d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DocumentAdapterTests.java +++ /dev/null @@ -1,159 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.DocumentEvent.EventType; -import javax.swing.text.Document; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.DocumentAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class DocumentAdapterTests extends TestCase { - private ModifiablePropertyValueModel<String> stringHolder; - Document documentAdapter; - boolean eventFired; - - public DocumentAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.stringHolder = new SimplePropertyValueModel<String>("0123456789"); - this.documentAdapter = new DocumentAdapter(this.stringHolder) { - @Override - protected PropertyChangeListener buildStringListener() { - return this.buildStringListener_(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testRemove() throws Exception { - this.eventFired = false; - this.documentAdapter.addDocumentListener(new TestDocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - DocumentAdapterTests.this.eventFired = true; - assertEquals(EventType.REMOVE, e.getType()); - assertEquals(DocumentAdapterTests.this.documentAdapter, e.getDocument()); - // this will be the removal of "23456" - assertEquals(2, e.getOffset()); - assertEquals(5, e.getLength()); - } - }); - this.documentAdapter.remove(2, 5); - assertTrue(this.eventFired); - assertEquals("01789", this.stringHolder.getValue()); - } - - public void testInsert() throws Exception { - this.eventFired = false; - this.documentAdapter.addDocumentListener(new TestDocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - DocumentAdapterTests.this.eventFired = true; - assertEquals(EventType.INSERT, e.getType()); - assertEquals(DocumentAdapterTests.this.documentAdapter, e.getDocument()); - // this will be the insert of "xxxxxx" - assertEquals(2, e.getOffset()); - assertEquals(5, e.getLength()); - } - }); - this.documentAdapter.insertString(2, "xxxxx", null); - assertTrue(this.eventFired); - assertEquals("01xxxxx23456789", this.stringHolder.getValue()); - } - - public void testSetValue() throws Exception { - this.eventFired = false; - this.documentAdapter.addDocumentListener(new TestDocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - DocumentAdapterTests.this.eventFired = true; - assertEquals(EventType.INSERT, e.getType()); - assertEquals(DocumentAdapterTests.this.documentAdapter, e.getDocument()); - // this will be the insert of "foo" - assertEquals(0, e.getOffset()); - assertEquals(3, e.getLength()); - } - @Override - public void removeUpdate(DocumentEvent e) { - assertEquals(EventType.REMOVE, e.getType()); - assertEquals(DocumentAdapterTests.this.documentAdapter, e.getDocument()); - // this will be the removal of "0123456789" - assertEquals(0, e.getOffset()); - assertEquals(10, e.getLength()); - } - }); - assertEquals("0123456789", this.documentAdapter.getText(0, this.documentAdapter.getLength())); - this.stringHolder.setValue("foo"); - assertTrue(this.eventFired); - assertEquals("foo", this.documentAdapter.getText(0, this.documentAdapter.getLength())); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<String> localStringHolder = (SimplePropertyValueModel<String>) this.stringHolder; - assertFalse(localStringHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.documentAdapter); - - DocumentListener listener = new TestDocumentListener(); - this.documentAdapter.addDocumentListener(listener); - assertTrue(localStringHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.documentAdapter); - - this.documentAdapter.removeDocumentListener(listener); - assertFalse(localStringHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.documentAdapter); - } - - private void verifyHasNoListeners(Object document) throws Exception { - Object delegate = ReflectionTools.getFieldValue(document, "delegate"); - Object[] listeners = (Object[]) ReflectionTools.executeMethod(delegate, "getDocumentListeners"); - assertEquals(0, listeners.length); - } - - private void verifyHasListeners(Object document) throws Exception { - Object delegate = ReflectionTools.getFieldValue(document, "delegate"); - Object[] listeners = (Object[]) ReflectionTools.executeMethod(delegate, "getDocumentListeners"); - assertFalse(listeners.length == 0); - } - - -private class TestDocumentListener implements DocumentListener { - TestDocumentListener() { - super(); - } - public void changedUpdate(DocumentEvent e) { - fail("unexpected event"); - } - public void insertUpdate(DocumentEvent e) { - fail("unexpected event"); - } - public void removeUpdate(DocumentEvent e) { - fail("unexpected event"); - } -} - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DocumentAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DocumentAdapterUITest.java deleted file mode 100644 index 5347191b57..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/DocumentAdapterUITest.java +++ /dev/null @@ -1,256 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.WindowConstants; -import javax.swing.text.AbstractDocument; -import javax.swing.text.AttributeSet; -import javax.swing.text.BadLocationException; -import javax.swing.text.Document; -import javax.swing.text.PlainDocument; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.DocumentAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -/** - * Play around with a set of entry fields. - */ -@SuppressWarnings("nls") -public class DocumentAdapterUITest { - - private TestModel testModel; - private static final String DEFAULT_NAME = "Scooby Doo"; - private ModifiablePropertyValueModel<TestModel> testModelHolder; - private ModifiablePropertyValueModel<String> nameHolder; - private Document nameDocument; - private Document upperCaseNameDocument; - - public static void main(String[] args) throws Exception { - new DocumentAdapterUITest().exec(); - } - - private DocumentAdapterUITest() { - super(); - } - - private void exec() throws Exception { - this.testModel = new TestModel(DEFAULT_NAME); - this.testModelHolder = new SimplePropertyValueModel<TestModel>(this.testModel); - this.nameHolder = this.buildNameHolder(this.testModelHolder); - this.nameDocument = this.buildNameDocument(this.nameHolder); - this.upperCaseNameDocument = this.buildUpperCaseNameDocument(this.nameHolder); - this.openWindow(); - } - - private ModifiablePropertyValueModel<String> buildNameHolder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, String>(vm, TestModel.NAME_PROPERTY) { - @Override - protected String buildValue_() { - return this.subject.getName(); - } - @Override - protected void setValue_(String value) { - this.subject.setName(value); - } - }; - } - - private Document buildNameDocument(ModifiablePropertyValueModel<String> stringHolder) { - return new DocumentAdapter(stringHolder); - } - - private Document buildUpperCaseNameDocument(ModifiablePropertyValueModel<String> stringHolder) { - return new DocumentAdapter(stringHolder, this.buildUpperCaseNameDocumentDelegate()); - } - - private AbstractDocument buildUpperCaseNameDocumentDelegate() { - return new PlainDocument() { - @Override - public void insertString(int offset, String string, AttributeSet a) throws BadLocationException { - if (string == null) { - return; - } - char[] upper = string.toCharArray(); - for (int i = 0; i < upper.length; i++) { - upper[i] = Character.toUpperCase(upper[i]); - } - super.insertString(offset, new String(upper), a); - } - }; - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setSize(400, 100); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildTextFieldPanel(), BorderLayout.NORTH); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildTextFieldPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(1, 0)); - taskListPanel.add(this.buildNameTextField()); - taskListPanel.add(this.buildReadOnlyNameTextField()); - taskListPanel.add(this.buildUpperCaseNameTextField()); - return taskListPanel; - } - - private JTextField buildNameTextField() { - return new JTextField(this.nameDocument, null, 0); - } - - private JTextField buildReadOnlyNameTextField() { - JTextField nameTextField = this.buildNameTextField(); - nameTextField.setEditable(false); - return nameTextField; - } - - private JTextField buildUpperCaseNameTextField() { - return new JTextField(this.upperCaseNameDocument, null, 0); - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(1, 0)); - controlPanel.add(this.buildResetNameButton()); - controlPanel.add(this.buildClearModelButton()); - controlPanel.add(this.buildRestoreModelButton()); - controlPanel.add(this.buildPrintModelButton()); - return controlPanel; - } - - private JButton buildResetNameButton() { - return new JButton(this.buildResetNameAction()); - } - - private Action buildResetNameAction() { - Action action = new AbstractAction("reset name") { - public void actionPerformed(ActionEvent event) { - DocumentAdapterUITest.this.resetName(); - } - }; - action.setEnabled(true); - return action; - } - - void resetName() { - this.testModel.setName(DEFAULT_NAME); - } - - private JButton buildClearModelButton() { - return new JButton(this.buildClearModelAction()); - } - - private Action buildClearModelAction() { - Action action = new AbstractAction("clear model") { - public void actionPerformed(ActionEvent event) { - DocumentAdapterUITest.this.clearModel(); - } - }; - action.setEnabled(true); - return action; - } - - void clearModel() { - this.testModelHolder.setValue(null); - } - - private JButton buildRestoreModelButton() { - return new JButton(this.buildRestoreModelAction()); - } - - private Action buildRestoreModelAction() { - Action action = new AbstractAction("restore model") { - public void actionPerformed(ActionEvent event) { - DocumentAdapterUITest.this.restoreModel(); - } - }; - action.setEnabled(true); - return action; - } - - void restoreModel() { - this.testModelHolder.setValue(this.testModel); - } - - private JButton buildPrintModelButton() { - return new JButton(this.buildPrintModelAction()); - } - - private Action buildPrintModelAction() { - Action action = new AbstractAction("print model") { - public void actionPerformed(ActionEvent event) { - DocumentAdapterUITest.this.printModel(); - } - }; - action.setEnabled(true); - return action; - } - - void printModel() { - System.out.println("name: " + this.testModel.getName()); - } - - - private class TestModel extends AbstractModel { - private String name; - public static final String NAME_PROPERTY = "name"; - - public TestModel(String name) { - this.name = name; - } - public String getName() { - return this.name; - } - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - @Override - public String toString() { - return "TestModel(" + this.getName() + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/JptUtilityModelValueSwingTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/JptUtilityModelValueSwingTests.java deleted file mode 100644 index 93c6b41c9d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/JptUtilityModelValueSwingTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class JptUtilityModelValueSwingTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityModelValueSwingTests.class.getPackage().getName()); - - suite.addTestSuite(CheckBoxModelAdapterTests.class); - suite.addTestSuite(ComboBoxModelAdapterTests.class); - suite.addTestSuite(DateSpinnerModelAdapterTests.class); - suite.addTestSuite(DocumentAdapterTests.class); - suite.addTestSuite(ListModelAdapterTests.class); - suite.addTestSuite(ListSpinnerModelAdapterTests.class); - suite.addTestSuite(NumberSpinnerModelAdapterTests.class); - suite.addTestSuite(ObjectListSelectionModelTests.class); - suite.addTestSuite(PrimitiveListTreeModelTests.class); - suite.addTestSuite(RadioButtonModelAdapterTests.class); - suite.addTestSuite(SpinnerModelAdapterTests.class); - suite.addTestSuite(TableModelAdapterTests.class); - suite.addTestSuite(TreeModelAdapterTests.class); - - return suite; - } - - private JptUtilityModelValueSwingTests() { - super(); - throw new UnsupportedOperationException(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListModelAdapterTests.java deleted file mode 100644 index 0be426de9f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListModelAdapterTests.java +++ /dev/null @@ -1,320 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.swing.ListModel; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.Bag; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.model.value.CoordinatedList; - -@SuppressWarnings("nls") -public class ListModelAdapterTests extends TestCase { - - public ListModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - // nothing yet... - } - - @Override - protected void tearDown() throws Exception { - // nothing yet... - super.tearDown(); - } - - private ListModelAdapter buildListModel(ListValueModel<String> listHolder) { - return new ListModelAdapter(listHolder) { - @Override - protected ListChangeListener buildListChangeListener() { - return this.buildListChangeListener_(); - } - }; - } - - private ListModel buildListModel(CollectionValueModel<String> collectionHolder) { - return new ListModelAdapter(collectionHolder) { - @Override - protected ListChangeListener buildListChangeListener() { - return this.buildListChangeListener_(); - } - }; - } - - public void testCollectionSynchronization() { - SimpleCollectionValueModel<String> collectionHolder = this.buildCollectionHolder(); - ListModel listModel = this.buildListModel(collectionHolder); - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - assertEquals(6, synchList.size()); - this.compare(listModel, synchList); - - collectionHolder.add("tom"); - collectionHolder.add("dick"); - collectionHolder.add("harry"); - collectionHolder.add(null); - assertEquals(10, synchList.size()); - this.compare(listModel, synchList); - - collectionHolder.remove("foo"); - collectionHolder.remove("jar"); - collectionHolder.remove("harry"); - collectionHolder.remove(null); - assertEquals(6, synchList.size()); - this.compare(listModel, synchList); - } - - public void testListSynchronization() { - SimpleListValueModel<String> listHolder = this.buildListHolder(); - ListModel listModel = this.buildListModel(listHolder); - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - assertEquals(6, synchList.size()); - this.compare(listModel, synchList); - - listHolder.add(6, "tom"); - listHolder.add(7, "dick"); - listHolder.add(8, "harry"); - listHolder.add(9, null); - assertEquals(10, synchList.size()); - this.compare(listModel, synchList); - - listHolder.remove(9); - listHolder.remove(8); - listHolder.remove(4); - listHolder.remove(0); - assertEquals(6, synchList.size()); - this.compare(listModel, synchList); - } - - public void testSetModel() { - SimpleListValueModel<String> listHolder1 = this.buildListHolder(); - ListModelAdapter listModel = this.buildListModel(listHolder1); - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - assertTrue(listHolder1.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - assertEquals(6, synchList.size()); - this.compare(listModel, synchList); - - SimpleListValueModel<String> listHolder2 = this.buildListHolder2(); - listModel.setModel(listHolder2); - assertEquals(3, synchList.size()); - this.compare(listModel, synchList); - assertTrue(listHolder1.hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(listHolder2.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - listModel.setModel(new SimpleListValueModel<String>()); - assertEquals(0, synchList.size()); - this.compare(listModel, synchList); - assertTrue(listHolder1.hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - assertTrue(listHolder2.hasNoListChangeListeners(ListValueModel.LIST_VALUES)); - } - - private void compare(ListModel listModel, List<String> list) { - assertEquals(listModel.getSize(), list.size()); - for (int i = 0; i < listModel.getSize(); i++) { - assertEquals(listModel.getElementAt(i), list.get(i)); - } - } - - public void testCollectionSort() { - this.verifyCollectionSort(null); - } - - public void testListSort() { - this.verifyListSort(null); - } - - public void testCustomCollectionSort() { - this.verifyCollectionSort(this.buildCustomComparator()); - } - - public void testCustomListSort() { - this.verifyListSort(this.buildCustomComparator()); - } - - private Comparator<String> buildCustomComparator() { - // sort with reverse order - return new Comparator<String>() { - public int compare(String s1, String s2) { - return s2.compareTo(s1); - } - }; - } - - private void verifyCollectionSort(Comparator<String> comparator) { - SimpleCollectionValueModel<String> collectionHolder = this.buildCollectionHolder(); - ListModel listModel = this.buildListModel(new SortedListValueModelAdapter<String>(collectionHolder, comparator)); - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - assertEquals(6, synchList.size()); - this.compareSort(listModel, synchList, comparator); - - collectionHolder.add("tom"); - collectionHolder.add("dick"); - collectionHolder.add("harry"); - assertEquals(9, synchList.size()); - this.compareSort(listModel, synchList, comparator); - - collectionHolder.remove("foo"); - collectionHolder.remove("jar"); - collectionHolder.remove("harry"); - assertEquals(6, synchList.size()); - this.compareSort(listModel, synchList, comparator); - } - - private void verifyListSort(Comparator<String> comparator) { - SimpleListValueModel<String> listHolder = this.buildListHolder(); - ListModel listModel = this.buildListModel(new SortedListValueModelWrapper<String>(listHolder, comparator)); - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - assertEquals(6, synchList.size()); - this.compareSort(listModel, synchList, comparator); - - listHolder.add(0, "tom"); - listHolder.add(0, "dick"); - listHolder.add(0, "harry"); - assertEquals(9, synchList.size()); - this.compareSort(listModel, synchList, comparator); - - listHolder.remove(8); - listHolder.remove(4); - listHolder.remove(0); - listHolder.remove(5); - assertEquals(5, synchList.size()); - this.compareSort(listModel, synchList, comparator); - } - - private void compareSort(ListModel listModel, List<String> list, Comparator<String> comparator) { - SortedSet<String> ss = new TreeSet<String>(comparator); - for (int i = 0; i < listModel.getSize(); i++) { - ss.add((String) listModel.getElementAt(i)); - } - assertEquals(ss.size(), list.size()); - for (Iterator<String> stream1 = ss.iterator(), stream2 = list.iterator(); stream1.hasNext(); ) { - assertEquals(stream1.next(), stream2.next()); - } - } - - public void testHasListeners() throws Exception { - SimpleListValueModel<String> listHolder = this.buildListHolder(); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - - ListModel listModel = this.buildListModel(listHolder); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.verifyHasNoListeners(listModel); - - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - assertTrue(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.verifyHasListeners(listModel); - - listModel.removeListDataListener(synchList); - assertFalse(listHolder.hasAnyListChangeListeners(ListValueModel.LIST_VALUES)); - this.verifyHasNoListeners(listModel); - } - - public void testGetSize() throws Exception { - SimpleListValueModel<String> listHolder = this.buildListHolder(); - ListModel listModel = this.buildListModel(listHolder); - this.verifyHasNoListeners(listModel); - assertEquals(6, listModel.getSize()); - - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - this.verifyHasListeners(listModel); - assertEquals(6, listModel.getSize()); - - listModel.removeListDataListener(synchList); - this.verifyHasNoListeners(listModel); - assertEquals(6, listModel.getSize()); - } - - public void testGetElementAt() throws Exception { - SimpleListValueModel<String> listHolder = this.buildListHolder(); - ListModel listModel = this.buildListModel(new SortedListValueModelWrapper<String>(listHolder)); - CoordinatedList<String> synchList = new CoordinatedList<String>(listModel); - this.verifyHasListeners(listModel); - assertEquals("bar", listModel.getElementAt(0)); - assertEquals("bar", synchList.get(0)); - } - - private void verifyHasNoListeners(ListModel listModel) throws Exception { - boolean hasNoListeners = ((Boolean) ReflectionTools.executeMethod(listModel, "hasNoListDataListeners")).booleanValue(); - assertTrue(hasNoListeners); - } - - private void verifyHasListeners(ListModel listModel) throws Exception { - boolean hasListeners = ((Boolean) ReflectionTools.executeMethod(listModel, "hasListDataListeners")).booleanValue(); - assertTrue(hasListeners); - } - - private SimpleCollectionValueModel<String> buildCollectionHolder() { - return new SimpleCollectionValueModel<String>(this.buildCollection()); - } - - private Collection<String> buildCollection() { - Bag<String> bag = new HashBag<String>(); - this.populateCollection(bag); - return bag; - } - - private SimpleListValueModel<String> buildListHolder() { - return new SimpleListValueModel<String>(this.buildList()); - } - - private List<String> buildList() { - List<String> list = new ArrayList<String>(); - this.populateCollection(list); - return list; - } - - private void populateCollection(Collection<String> c) { - c.add("foo"); - c.add("bar"); - c.add("baz"); - c.add("joo"); - c.add("jar"); - c.add("jaz"); - } - - private SimpleListValueModel<String> buildListHolder2() { - return new SimpleListValueModel<String>(this.buildList2()); - } - - private List<String> buildList2() { - List<String> list = new ArrayList<String>(); - this.populateCollection2(list); - return list; - } - - private void populateCollection2(Collection<String> c) { - c.add("tom"); - c.add("dick"); - c.add("harry"); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListModelAdapterUITest.java deleted file mode 100644 index ca51772dae..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListModelAdapterUITest.java +++ /dev/null @@ -1,370 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.TextField; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.ListIterator; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListModel; -import javax.swing.WindowConstants; - -import org.eclipse.jpt.common.utility.internal.StringTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ListAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -/** - * an example UI for testing various permutations of the ListModelAdapter - */ -@SuppressWarnings("nls") -public class ListModelAdapterUITest { - - private ModifiablePropertyValueModel<TaskList> taskListHolder; - private TextField taskTextField; - - public static void main(String[] args) throws Exception { - new ListModelAdapterUITest().exec(args); - } - - private ListModelAdapterUITest() { - super(); - } - - private void exec(@SuppressWarnings("unused") String[] args) throws Exception { - this.taskListHolder = new SimplePropertyValueModel<TaskList>(new TaskList()); - this.openWindow(); - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setSize(800, 400); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildTaskListPanel(), BorderLayout.CENTER); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildTaskListPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(0, 1)); - taskListPanel.add(this.buildPrimitiveTaskListPanel()); - taskListPanel.add(this.buildDisplayableTaskListPanel()); - return taskListPanel; - } - - private Component buildPrimitiveTaskListPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(1, 0)); - taskListPanel.add(this.buildUnsortedPrimitiveListPanel()); - taskListPanel.add(this.buildStandardSortedPrimitiveListPanel()); - taskListPanel.add(this.buildCustomSortedPrimitiveListPanel()); - return taskListPanel; - } - - private Component buildDisplayableTaskListPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(1, 0)); - taskListPanel.add(this.buildUnsortedDisplayableListPanel()); - taskListPanel.add(this.buildStandardSortedDisplayableListPanel()); - taskListPanel.add(this.buildCustomSortedDisplayableListPanel()); - return taskListPanel; - } - - private Component buildUnsortedPrimitiveListPanel() { - return this.buildListPanel("primitive unsorted", this.buildUnsortedPrimitiveListModel()); - } - - private Component buildStandardSortedPrimitiveListPanel() { - return this.buildListPanel("primitive sorted", this.buildStandardSortedPrimitiveListModel()); - } - - private Component buildCustomSortedPrimitiveListPanel() { - return this.buildListPanel("primitive reverse sorted", this.buildCustomSortedPrimitiveListModel()); - } - - private Component buildUnsortedDisplayableListPanel() { - return this.buildListPanel("displayable unsorted", this.buildUnsortedDisplayableListModel()); - } - - private Component buildStandardSortedDisplayableListPanel() { - return this.buildListPanel("displayable sorted", this.buildStandardSortedDisplayableListModel()); - } - - private Component buildCustomSortedDisplayableListPanel() { - return this.buildListPanel("displayable reverse sorted", this.buildCustomSortedDisplayableListModel()); - } - - private ListModel buildUnsortedPrimitiveListModel() { - return new ListModelAdapter(this.buildPrimitiveTaskListAdapter()); - } - - private ListModel buildStandardSortedPrimitiveListModel() { - return new ListModelAdapter(new SortedListValueModelWrapper<String>(this.buildPrimitiveTaskListAdapter())); - } - - private ListModel buildCustomSortedPrimitiveListModel() { - return new ListModelAdapter(new SortedListValueModelWrapper<String>(this.buildPrimitiveTaskListAdapter(), this.buildCustomStringComparator())); - } - - private ListModel buildUnsortedDisplayableListModel() { - return new ListModelAdapter(this.buildDisplayableTaskListAdapter()); - } - - private ListModel buildStandardSortedDisplayableListModel() { - return new ListModelAdapter(new SortedListValueModelWrapper<Task>(this.buildDisplayableTaskListAdapter())); - } - - private ListModel buildCustomSortedDisplayableListModel() { - return new ListModelAdapter(new SortedListValueModelWrapper<Task>(this.buildDisplayableTaskListAdapter(), this.buildCustomTaskObjectComparator())); - } - - private Component buildListPanel(String label, ListModel listModel) { - JPanel listPanel = new JPanel(new BorderLayout()); - JLabel listLabel = new JLabel(" " + label); - listPanel.add(listLabel, BorderLayout.NORTH); - - JList listBox = new JList(); - listBox.setModel(listModel); - listBox.setDoubleBuffered(true); - listLabel.setLabelFor(listBox); - listPanel.add(new JScrollPane(listBox), BorderLayout.CENTER); - return listPanel; - } - - private Comparator<String> buildCustomStringComparator() { - return new Comparator<String>() { - public int compare(String s1, String s2) { - return s2.compareTo(s1); - } - }; - } - - private Comparator<Task> buildCustomTaskObjectComparator() { - return new Comparator<Task>() { - public int compare(Task to1, Task to2) { - return to2.displayString().compareTo(to1.displayString()); - } - }; - } - - private ListValueModel<String> buildPrimitiveTaskListAdapter() { - return new ListAspectAdapter<TaskList, String>(TaskList.TASK_NAMES_LIST, this.taskList()) { - @Override - protected ListIterator<String> listIterator_() { - return this.subject.taskNames(); - } - }; - } - - private ListValueModel<Task> buildDisplayableTaskListAdapter() { - return new ListAspectAdapter<TaskList, Task>(TaskList.TASKS_LIST, this.taskList()) { - @Override - protected ListIterator<Task> listIterator_() { - return this.subject.tasks(); - } - }; - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new BorderLayout()); - controlPanel.add(this.buildAddRemoveTaskPanel(), BorderLayout.CENTER); - controlPanel.add(this.buildClearButton(), BorderLayout.EAST); - return controlPanel; - } - - private Component buildAddRemoveTaskPanel() { - JPanel addRemoveTaskPanel = new JPanel(new BorderLayout()); - addRemoveTaskPanel.add(this.buildAddButton(), BorderLayout.WEST); - addRemoveTaskPanel.add(this.buildTaskTextField(), BorderLayout.CENTER); - addRemoveTaskPanel.add(this.buildRemoveButton(), BorderLayout.EAST); - return addRemoveTaskPanel; - } - - private String getTask() { - return this.taskTextField.getText(); - } - - private TaskList taskList() { - return this.taskListHolder.getValue(); - } - - void addTask() { - String task = this.getTask(); - if (task.length() != 0) { - this.taskList().addTask(task); - } - } - - void removeTask() { - String task = this.getTask(); - if (task.length() != 0) { - this.taskList().removeTask(task); - } - } - - void clearTasks() { - this.taskList().clearTasks(); - } - - private TextField buildTaskTextField() { - this.taskTextField = new TextField(); - return this.taskTextField; - } - - private JButton buildAddButton() { - return new JButton(this.buildAddAction()); - } - - private Action buildAddAction() { - Action action = new AbstractAction("add") { - public void actionPerformed(ActionEvent event) { - ListModelAdapterUITest.this.addTask(); - } - }; - action.setEnabled(true); - return action; - } - - private JButton buildRemoveButton() { - return new JButton(this.buildRemoveAction()); - } - - private Action buildRemoveAction() { - Action action = new AbstractAction("remove") { - public void actionPerformed(ActionEvent event) { - ListModelAdapterUITest.this.removeTask(); - } - }; - action.setEnabled(true); - return action; - } - - private JButton buildClearButton() { - return new JButton(this.buildClearAction()); - } - - private Action buildClearAction() { - Action action = new AbstractAction("clear") { - public void actionPerformed(ActionEvent event) { - ListModelAdapterUITest.this.clearTasks(); - } - }; - action.setEnabled(true); - return action; - } - - public class TaskList extends AbstractModel { - private List<String> taskNames = new ArrayList<String>(); - private List<Task> taskObjects = new ArrayList<Task>(); - public static final String TASK_NAMES_LIST = "taskNames"; - public static final String TASKS_LIST = "tasks"; - TaskList() { - super(); - } - public ListIterator<String> taskNames() { - return this.taskNames.listIterator(); - } - public ListIterator<Task> tasks() { - return this.taskObjects.listIterator(); - } - public void addTask(String taskName) { - int index = this.taskNames.size(); - this.taskNames.add(index, taskName); - this.fireItemAdded(TASK_NAMES_LIST, index, taskName); - - Task taskObject = new Task(taskName); - this.taskObjects.add(index, taskObject); - this.fireItemAdded(TASKS_LIST, index, taskObject); - } - public void removeTask(String taskName) { - int index = this.taskNames.indexOf(taskName); - if (index != -1) { - Object removedTask = this.taskNames.remove(index); - this.fireItemRemoved(TASK_NAMES_LIST, index, removedTask); - // assume the indexes match... - Object removedTaskObject = this.taskObjects.remove(index); - this.fireItemRemoved(TASKS_LIST, index, removedTaskObject); - } - } - public void clearTasks() { - this.taskNames.clear(); - this.fireListChanged(TASK_NAMES_LIST, this.taskNames); - this.taskObjects.clear(); - this.fireListChanged(TASKS_LIST, this.taskObjects); - } - } - - public class Task extends AbstractModel implements Displayable { - private String name; - private Date creationTimeStamp; - public Task(String name) { - this.name = name; - this.creationTimeStamp = new Date(); - } - public String displayString() { - return this.name + ": " + this.creationTimeStamp.getTime(); - } - public Icon icon() { - return null; - } - public String getName() { - return this.name; - } - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(DISPLAY_STRING_PROPERTY, old, name); - } - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.displayString()); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListSpinnerModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListSpinnerModelAdapterTests.java deleted file mode 100644 index 90d50326e7..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ListSpinnerModelAdapterTests.java +++ /dev/null @@ -1,134 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.SpinnerModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ListSpinnerModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Object> valueHolder; - private SpinnerModel spinnerModelAdapter; - boolean eventFired; - private static final String[] VALUE_LIST = {"red", "green", "blue"}; - private static final String DEFAULT_VALUE = VALUE_LIST[0]; - - public ListSpinnerModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.valueHolder = new SimplePropertyValueModel<Object>(DEFAULT_VALUE); - this.spinnerModelAdapter = new ListSpinnerModelAdapter(this.valueHolder, VALUE_LIST) { - @Override - protected PropertyChangeListener buildValueChangeListener() { - return this.buildValueChangeListener_(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSetValueSpinnerModel() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - ListSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(DEFAULT_VALUE, this.valueHolder.getValue()); - this.spinnerModelAdapter.setValue(VALUE_LIST[2]); - assertTrue(this.eventFired); - assertEquals(VALUE_LIST[2], this.valueHolder.getValue()); - } - - public void testSetValueValueHolder() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - ListSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(DEFAULT_VALUE, this.spinnerModelAdapter.getValue()); - this.valueHolder.setValue(VALUE_LIST[2]); - assertTrue(this.eventFired); - assertEquals(VALUE_LIST[2], this.spinnerModelAdapter.getValue()); - } - - public void testDefaultValue() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - ListSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(DEFAULT_VALUE, this.spinnerModelAdapter.getValue()); - - this.valueHolder.setValue(VALUE_LIST[2]); - assertTrue(this.eventFired); - assertEquals(VALUE_LIST[2], this.spinnerModelAdapter.getValue()); - - this.eventFired = false; - this.valueHolder.setValue(null); - assertTrue(this.eventFired); - assertEquals(VALUE_LIST[0], this.spinnerModelAdapter.getValue()); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<Object> localValueHolder = (SimplePropertyValueModel<Object>) this.valueHolder; - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - - ChangeListener listener = new TestChangeListener(); - this.spinnerModelAdapter.addChangeListener(listener); - assertTrue(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.spinnerModelAdapter); - - this.spinnerModelAdapter.removeChangeListener(listener); - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - } - - private void verifyHasNoListeners(SpinnerModel adapter) throws Exception { - assertEquals(0, ((ListSpinnerModelAdapter) adapter).getChangeListeners().length); - } - - private void verifyHasListeners(Object adapter) throws Exception { - assertFalse(((ListSpinnerModelAdapter) adapter).getChangeListeners().length == 0); - } - - - private class TestChangeListener implements ChangeListener { - TestChangeListener() { - super(); - } - public void stateChanged(ChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/NumberSpinnerModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/NumberSpinnerModelAdapterTests.java deleted file mode 100644 index ee0bc85994..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/NumberSpinnerModelAdapterTests.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.SpinnerModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.NumberSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class NumberSpinnerModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Number> valueHolder; - private SpinnerModel spinnerModelAdapter; - boolean eventFired; - - public NumberSpinnerModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.valueHolder = new SimplePropertyValueModel<Number>(new Integer(0)); - this.spinnerModelAdapter = new NumberSpinnerModelAdapter(this.valueHolder, -33, 33, 1) { - @Override - protected PropertyChangeListener buildNumberChangeListener() { - return this.buildNumberChangeListener_(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSetValueSpinnerModel() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - NumberSpinnerModelAdapterTests.this.eventFired = true; - } - }); - this.spinnerModelAdapter.setValue(new Integer(5)); - assertTrue(this.eventFired); - assertEquals(new Integer(5), this.valueHolder.getValue()); - } - - public void testSetValueValueHolder() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - NumberSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(new Integer(0), this.spinnerModelAdapter.getValue()); - this.valueHolder.setValue(new Integer(7)); - assertTrue(this.eventFired); - assertEquals(new Integer(7), this.spinnerModelAdapter.getValue()); - } - - public void testDefaultValue() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - NumberSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(new Integer(0), this.spinnerModelAdapter.getValue()); - this.valueHolder.setValue(null); - assertTrue(this.eventFired); - assertEquals(new Integer(-33), this.spinnerModelAdapter.getValue()); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<Number> localValueHolder = (SimplePropertyValueModel<Number>) this.valueHolder; - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - - ChangeListener listener = new TestChangeListener(); - this.spinnerModelAdapter.addChangeListener(listener); - assertTrue(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.spinnerModelAdapter); - - this.spinnerModelAdapter.removeChangeListener(listener); - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - } - - private void verifyHasNoListeners(SpinnerModel adapter) throws Exception { - assertEquals(0, ((NumberSpinnerModelAdapter) adapter).getChangeListeners().length); - } - - private void verifyHasListeners(Object adapter) throws Exception { - assertFalse(((NumberSpinnerModelAdapter) adapter).getChangeListeners().length == 0); - } - - public void testNullInitialValue() { - this.valueHolder = new SimplePropertyValueModel<Number>(); - this.spinnerModelAdapter = new NumberSpinnerModelAdapter(this.valueHolder, new Integer(-33), new Integer(33), new Integer(1), new Integer(0)) { - @Override - protected PropertyChangeListener buildNumberChangeListener() { - return this.buildNumberChangeListener_(); - } - }; - - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - NumberSpinnerModelAdapterTests.this.eventFired = true; - } - }); - assertEquals(new Integer(0), this.spinnerModelAdapter.getValue()); - this.valueHolder.setValue(new Integer(7)); - assertTrue(this.eventFired); - assertEquals(new Integer(7), this.spinnerModelAdapter.getValue()); - } - - - // ********** inner class ********** - private class TestChangeListener implements ChangeListener { - TestChangeListener() { - super(); - } - public void stateChanged(ChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ObjectListSelectionModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ObjectListSelectionModelTests.java deleted file mode 100644 index 4f55864415..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ObjectListSelectionModelTests.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.DefaultListModel; -import javax.swing.ListModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ObjectListSelectionModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ObjectListSelectionModelTests extends TestCase { - private DefaultListModel listModel; - private ObjectListSelectionModel selectionModel; - - public ObjectListSelectionModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.listModel = this.buildListModel(); - this.selectionModel = this.buildSelectionModel(this.listModel); - } - - private DefaultListModel buildListModel() { - DefaultListModel lm = new DefaultListModel(); - lm.addElement("foo"); - lm.addElement("bar"); - lm.addElement("baz"); - return lm; - } - - private ObjectListSelectionModel buildSelectionModel(ListModel lm) { - return new ObjectListSelectionModel(lm); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testListDataListener() { - this.selectionModel.addListSelectionListener(this.buildListSelectionListener()); - this.selectionModel.setSelectionInterval(0, 0); - assertEquals("foo", this.selectionModel.selectedValue()); - this.listModel.set(0, "jar"); - assertEquals("jar", this.selectionModel.selectedValue()); - } - - public void testGetSelectedValue() { - this.selectionModel.setSelectionInterval(0, 0); - assertEquals("foo", this.selectionModel.selectedValue()); - } - - public void testGetSelectedValues() { - this.selectionModel.setSelectionInterval(0, 0); - this.selectionModel.addSelectionInterval(2, 2); - assertEquals(2, this.selectionModel.selectedValues().length); - assertTrue(ArrayTools.contains(this.selectionModel.selectedValues(), "foo")); - assertTrue(ArrayTools.contains(this.selectionModel.selectedValues(), "baz")); - } - - public void testSetSelectedValue() { - this.selectionModel.setSelectedValue("foo"); - assertEquals(0, this.selectionModel.getMinSelectionIndex()); - assertEquals(0, this.selectionModel.getMaxSelectionIndex()); - } - - public void testSetSelectedValues() { - this.selectionModel.setSelectedValues(new Object[] {"foo", "baz"}); - assertEquals(0, this.selectionModel.getMinSelectionIndex()); - assertEquals(2, this.selectionModel.getMaxSelectionIndex()); - } - - public void testAddSelectedValue() { - this.listModel.addElement("joo"); - this.listModel.addElement("jar"); - this.listModel.addElement("jaz"); - this.selectionModel.setSelectedValue("foo"); - this.selectionModel.addSelectedValue("jaz"); - assertEquals(0, this.selectionModel.getMinSelectionIndex()); - assertEquals(5, this.selectionModel.getMaxSelectionIndex()); - assertTrue(this.selectionModel.isSelectedIndex(0)); - assertFalse(this.selectionModel.isSelectedIndex(1)); - assertFalse(this.selectionModel.isSelectedIndex(2)); - assertFalse(this.selectionModel.isSelectedIndex(3)); - assertFalse(this.selectionModel.isSelectedIndex(4)); - assertTrue(this.selectionModel.isSelectedIndex(5)); - } - - public void testAddSelectedValues() { - this.listModel.addElement("joo"); - this.listModel.addElement("jar"); - this.listModel.addElement("jaz"); - this.selectionModel.setSelectedValue("foo"); - this.selectionModel.addSelectedValues(new Object[] {"bar", "jar"}); - assertEquals(0, this.selectionModel.getMinSelectionIndex()); - assertEquals(4, this.selectionModel.getMaxSelectionIndex()); - assertTrue(this.selectionModel.isSelectedIndex(0)); - assertTrue(this.selectionModel.isSelectedIndex(1)); - assertFalse(this.selectionModel.isSelectedIndex(2)); - assertFalse(this.selectionModel.isSelectedIndex(3)); - assertTrue(this.selectionModel.isSelectedIndex(4)); - assertFalse(this.selectionModel.isSelectedIndex(5)); - } - - public void testRemoveSelectedValue() { - this.listModel.addElement("joo"); - this.listModel.addElement("jar"); - this.listModel.addElement("jaz"); - this.selectionModel.setSelectedValues(new Object[] {"foo", "baz", "jar"}); - this.selectionModel.removeSelectedValue("jar"); - assertEquals(0, this.selectionModel.getMinSelectionIndex()); - assertEquals(2, this.selectionModel.getMaxSelectionIndex()); - assertTrue(this.selectionModel.isSelectedIndex(0)); - assertFalse(this.selectionModel.isSelectedIndex(1)); - assertTrue(this.selectionModel.isSelectedIndex(2)); - assertFalse(this.selectionModel.isSelectedIndex(3)); - assertFalse(this.selectionModel.isSelectedIndex(4)); - assertFalse(this.selectionModel.isSelectedIndex(5)); - } - - public void testRemoveSelectedValues() { - this.listModel.addElement("joo"); - this.listModel.addElement("jar"); - this.listModel.addElement("jaz"); - this.selectionModel.setSelectedValues(new Object[] {"foo", "baz", "joo", "jar"}); - this.selectionModel.removeSelectedValues(new Object[] {"foo", "joo"}); - assertEquals(2, this.selectionModel.getMinSelectionIndex()); - assertEquals(4, this.selectionModel.getMaxSelectionIndex()); - assertFalse(this.selectionModel.isSelectedIndex(0)); - assertFalse(this.selectionModel.isSelectedIndex(1)); - assertTrue(this.selectionModel.isSelectedIndex(2)); - assertFalse(this.selectionModel.isSelectedIndex(3)); - assertTrue(this.selectionModel.isSelectedIndex(4)); - assertFalse(this.selectionModel.isSelectedIndex(5)); - } - - public void testGetAnchorSelectedValue() { - this.selectionModel.setAnchorSelectionIndex(1); - assertEquals("bar", this.selectionModel.getAnchorSelectedValue()); - } - - public void testGetLeadSelectedValue() { - this.selectionModel.setSelectedValue("bar"); - assertEquals("bar", this.selectionModel.getLeadSelectedValue()); - this.selectionModel.setSelectedValues(new Object[] {"foo", "baz"}); - assertEquals("baz", this.selectionModel.getLeadSelectedValue()); - } - - public void testGetMinMaxSelectedValue() { - this.listModel.addElement("joo"); - this.listModel.addElement("jar"); - this.listModel.addElement("jaz"); - this.selectionModel.setSelectedValue("foo"); - this.selectionModel.addSelectedValues(new Object[] {"bar", "jar"}); - assertEquals("foo", this.selectionModel.getMinSelectedValue()); - assertEquals("jar", this.selectionModel.getMaxSelectedValue()); - } - - public void testValueIsSelected() { - this.listModel.addElement("joo"); - this.listModel.addElement("jar"); - this.listModel.addElement("jaz"); - this.selectionModel.setSelectedValue("foo"); - this.selectionModel.addSelectedValues(new Object[] {"bar", "jar"}); - assertTrue(this.selectionModel.valueIsSelected("foo")); - assertTrue(this.selectionModel.valueIsSelected("bar")); - assertTrue(this.selectionModel.valueIsSelected("jar")); - assertFalse(this.selectionModel.valueIsSelected("baz")); - } - - public void testHasListeners() throws Exception { - ListSelectionListener listener = this.buildListSelectionListener(); - assertEquals(0, this.listModel.getListDataListeners().length); - this.selectionModel.addListSelectionListener(listener); - assertEquals(1, this.listModel.getListDataListeners().length); - this.selectionModel.removeListSelectionListener(listener); - assertEquals(0, this.listModel.getListDataListeners().length); - } - - private ListSelectionListener buildListSelectionListener() { - return new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - // do nothing for now... - } - }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/PrimitiveListTreeModelTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/PrimitiveListTreeModelTests.java deleted file mode 100644 index eca1bee8dd..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/PrimitiveListTreeModelTests.java +++ /dev/null @@ -1,198 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.ListIterator; -import javax.swing.event.TreeModelEvent; -import javax.swing.event.TreeModelListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreeModel; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyListIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.ListAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.PrimitiveListTreeModel; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class PrimitiveListTreeModelTests extends TestCase { - TestModel testModel; - private TreeModel treeModel; - - public PrimitiveListTreeModelTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.testModel = this.buildTestModel(); - this.treeModel = this.buildTreeModel(); - } - - private TestModel buildTestModel() { - return new TestModel(); - } - - private TreeModel buildTreeModel() { - return new PrimitiveListTreeModel(this.buildListValueModel()) { - @Override - protected void primitiveChanged(int index, Object newValue) { - if ( ! newValue.equals("")) { - PrimitiveListTreeModelTests.this.testModel.replaceName(index, (String) newValue); - } - } - @Override - protected ListChangeListener buildListChangeListener() { - return this.buildListChangeListener_(); - } - }; - } - - private ListValueModel<?> buildListValueModel() { - return new ListAspectAdapter<TestModel, String>(TestModel.NAMES_LIST, this.testModel) { - @Override - protected ListIterator<String> listIterator_() { - return this.subject.names(); - } - @Override - public String get(int index) { - return this.subject.getName(index); - } - @Override - public int size() { - return this.subject.namesSize(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testAddPrimitive() { - this.treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesInserted(TreeModelEvent e) { - PrimitiveListTreeModelTests.this.verifyTreeModelEvent(e, new int[] {0}, new String[] {"foo"}); - } - }); - this.testModel.addName("foo"); - } - - public void testRemovePrimitive() { - this.testModel.addName("foo"); - this.testModel.addName("bar"); - this.testModel.addName("baz"); - this.treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesRemoved(TreeModelEvent e) { - PrimitiveListTreeModelTests.this.verifyTreeModelEvent(e, new int[] {1}, new String[] {"bar"}); - } - }); - String name = this.testModel.removeName(1); - assertEquals("bar", name); - } - - public void testReplacePrimitive() { - this.testModel.addName("foo"); - this.testModel.addName("bar"); - this.testModel.addName("baz"); - this.treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesChanged(TreeModelEvent e) { - PrimitiveListTreeModelTests.this.verifyTreeModelEvent(e, new int[] {1}, new String[] {"jar"}); - } - }); - String name = this.testModel.replaceName(1, "jar"); - assertEquals("bar", name); - } - - void verifyTreeModelEvent(TreeModelEvent e, int[] expectedChildIndices, String[] expectedNames) { - assertTrue(Arrays.equals(expectedChildIndices, e.getChildIndices())); - Object[] actualChildren = e.getChildren(); - assertEquals(expectedNames.length, actualChildren.length); - for (int i = 0; i < expectedNames.length; i++) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) actualChildren[i]; - assertEquals(expectedNames[i], node.getUserObject()); - } - assertEquals(1, e.getPath().length); - assertEquals(this.treeModel.getRoot(), e.getPath()[0]); - assertEquals(this.treeModel, e.getSource()); - } - - -// ********** inner classes ********** - - class TestModel extends AbstractModel { - private final List<String> names; - static final String NAMES_LIST = "names"; - - TestModel() { - super(); - this.names = new ArrayList<String>(); - } - - public ListIterator<String> names() { - return new ReadOnlyListIterator<String>(this.names); - } - public int namesSize() { - return this.names.size(); - } - public String getName(int index) { - return this.names.get(index); - } - public void addName(int index, String name) { - this.addItemToList(index, name, this.names, NAMES_LIST); - } - public void addName(String name) { - this.addName(this.namesSize(), name); - } - public void addNames(int index, List<String> list) { - this.addItemsToList(index, this.names, list, NAMES_LIST); - } - public void addNames(List<String> list) { - this.addNames(this.namesSize(), list); - } - public String removeName(int index) { - return this.removeItemFromList(index, this.names, NAMES_LIST); - } - public List<String> removeNames(int index, int length) { - return this.removeItemsFromList(index, length, this.names, NAMES_LIST); - } - public String replaceName(int index, String newName) { - return this.setItemInList(index, newName, this.names, NAMES_LIST); - } - } - - - public class TestTreeModelListener implements TreeModelListener { - public void treeNodesChanged(TreeModelEvent e) { - fail("unexpected event"); - } - public void treeNodesInserted(TreeModelEvent e) { - fail("unexpected event"); - } - public void treeNodesRemoved(TreeModelEvent e) { - fail("unexpected event"); - } - public void treeStructureChanged(TreeModelEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/RadioButtonModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/RadioButtonModelAdapterTests.java deleted file mode 100644 index fd9749bbce..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/RadioButtonModelAdapterTests.java +++ /dev/null @@ -1,230 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.ButtonModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.EventListenerList; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.RadioButtonModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class RadioButtonModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Object> valueHolder; - - private ButtonModel redButtonModelAdapter; - private ChangeListener redListener; - boolean redEventFired; - - private ButtonModel greenButtonModelAdapter; - private ChangeListener greenListener; - boolean greenEventFired; - - private ButtonModel blueButtonModelAdapter; - private ChangeListener blueListener; - boolean blueEventFired; - -// private ButtonGroup buttonGroup; // DO NOT use a ButtonGroup - - private static final String RED = "red"; - private static final String GREEN = "green"; - private static final String BLUE = "blue"; - - public RadioButtonModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.valueHolder = new SimplePropertyValueModel<Object>(null); -// buttonGroup = new ButtonGroup(); - - this.redButtonModelAdapter = this.buildButtonModel(this.valueHolder, RED); -// this.redButtonModelAdapter.setGroup(buttonGroup); - this.redListener = new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - RadioButtonModelAdapterTests.this.redEventFired = true; - } - }; - - this.greenButtonModelAdapter = this.buildButtonModel(this.valueHolder, GREEN); -// this.greenButtonModelAdapter.setGroup(buttonGroup); - this.greenListener = new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - RadioButtonModelAdapterTests.this.greenEventFired = true; - } - }; - - this.blueButtonModelAdapter = this.buildButtonModel(this.valueHolder, BLUE); -// this.blueButtonModelAdapter.setGroup(buttonGroup); - this.blueListener = new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - RadioButtonModelAdapterTests.this.blueEventFired = true; - } - }; - - this.clearFlags(); - } - - private ButtonModel buildButtonModel(ModifiablePropertyValueModel<Object> pvm, Object buttonValue) { - return new RadioButtonModelAdapter(pvm, buttonValue) { - @Override - protected PropertyChangeListener buildBooleanChangeListener() { - return this.buildBooleanChangeListener_(); - } - }; - } - - private void listenToModelAdapters() { - this.redButtonModelAdapter.addChangeListener(this.redListener); - this.greenButtonModelAdapter.addChangeListener(this.greenListener); - this.blueButtonModelAdapter.addChangeListener(this.blueListener); - } - - private void clearFlags() { - this.redEventFired = false; - this.greenEventFired = false; - this.blueEventFired = false; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSetSelected() throws Exception { - this.listenToModelAdapters(); - - this.greenButtonModelAdapter.setSelected(true); - assertFalse(this.redEventFired); - assertTrue(this.greenEventFired); - assertFalse(this.blueEventFired); - assertEquals(GREEN, this.valueHolder.getValue()); - - this.clearFlags(); - this.blueButtonModelAdapter.setSelected(true); - assertFalse(this.redEventFired); - assertTrue(this.greenEventFired); - assertTrue(this.blueEventFired); - assertEquals(BLUE, this.valueHolder.getValue()); - - this.clearFlags(); - this.redButtonModelAdapter.setSelected(true); - assertTrue(this.redEventFired); - assertFalse(this.greenEventFired); - assertTrue(this.blueEventFired); - assertEquals(RED, this.valueHolder.getValue()); - } - - public void testSetValue() throws Exception { - this.listenToModelAdapters(); - - this.greenButtonModelAdapter.setSelected(true); - - this.clearFlags(); - this.valueHolder.setValue(BLUE); - assertFalse(this.redEventFired); - assertTrue(this.greenEventFired); - assertTrue(this.blueEventFired); - assertFalse(this.redButtonModelAdapter.isSelected()); - assertFalse(this.greenButtonModelAdapter.isSelected()); - assertTrue(this.blueButtonModelAdapter.isSelected()); - - this.clearFlags(); - this.valueHolder.setValue(RED); - assertTrue(this.redEventFired); - assertFalse(this.greenEventFired); - assertTrue(this.blueEventFired); - assertTrue(this.redButtonModelAdapter.isSelected()); - assertFalse(this.greenButtonModelAdapter.isSelected()); - assertFalse(this.blueButtonModelAdapter.isSelected()); - } - - public void testDefaultValue() throws Exception { - this.listenToModelAdapters(); - - this.valueHolder.setValue(GREEN); - assertFalse(this.redButtonModelAdapter.isSelected()); - assertTrue(this.greenButtonModelAdapter.isSelected()); - assertFalse(this.blueButtonModelAdapter.isSelected()); - - this.clearFlags(); - this.valueHolder.setValue(null); - assertFalse(this.redEventFired); - assertTrue(this.greenEventFired); - assertFalse(this.blueEventFired); - assertFalse(this.redButtonModelAdapter.isSelected()); - assertFalse(this.greenButtonModelAdapter.isSelected()); - assertFalse(this.blueButtonModelAdapter.isSelected()); - - this.clearFlags(); - this.valueHolder.setValue(BLUE); - assertFalse(this.redEventFired); - assertFalse(this.greenEventFired); - assertTrue(this.blueEventFired); - assertFalse(this.redButtonModelAdapter.isSelected()); - assertFalse(this.greenButtonModelAdapter.isSelected()); - assertTrue(this.blueButtonModelAdapter.isSelected()); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<Object> localValueHolder = (SimplePropertyValueModel<Object>) this.valueHolder; - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.redButtonModelAdapter); - this.verifyHasNoListeners(this.greenButtonModelAdapter); - this.verifyHasNoListeners(this.blueButtonModelAdapter); - - ChangeListener listener = new TestChangeListener(); - this.redButtonModelAdapter.addChangeListener(listener); - assertTrue(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.redButtonModelAdapter); - this.verifyHasNoListeners(this.greenButtonModelAdapter); - this.verifyHasNoListeners(this.blueButtonModelAdapter); - - this.redButtonModelAdapter.removeChangeListener(listener); - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.redButtonModelAdapter); - this.verifyHasNoListeners(this.greenButtonModelAdapter); - this.verifyHasNoListeners(this.blueButtonModelAdapter); - } - - private void verifyHasNoListeners(Object model) throws Exception { - EventListenerList listenerList = (EventListenerList) ReflectionTools.getFieldValue(model, "listenerList"); - assertEquals(0, listenerList.getListenerList().length); - } - - private void verifyHasListeners(Object model) throws Exception { - EventListenerList listenerList = (EventListenerList) ReflectionTools.getFieldValue(model, "listenerList"); - assertFalse(listenerList.getListenerList().length == 0); - } - - - private class TestChangeListener implements ChangeListener { - TestChangeListener() { - super(); - } - public void stateChanged(ChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/RadioButtonModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/RadioButtonModelAdapterUITest.java deleted file mode 100644 index 9bc19631d7..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/RadioButtonModelAdapterUITest.java +++ /dev/null @@ -1,260 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ButtonModel; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.WindowConstants; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.RadioButtonModelAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - - -/** - * Play around with a set of radio buttons. - */ -@SuppressWarnings("nls") -public class RadioButtonModelAdapterUITest { - - private TestModel testModel; - private ModifiablePropertyValueModel<TestModel> testModelHolder; - private ModifiablePropertyValueModel<Object> colorHolder; - private ButtonModel redButtonModel; - private ButtonModel greenButtonModel; - private ButtonModel blueButtonModel; - - public static void main(String[] args) throws Exception { - new RadioButtonModelAdapterUITest().exec(); - } - - private RadioButtonModelAdapterUITest() { - super(); - } - - private void exec() throws Exception { - this.testModel = new TestModel(); - this.testModelHolder = new SimplePropertyValueModel<TestModel>(this.testModel); - this.colorHolder = this.buildColorHolder(this.testModelHolder); - this.redButtonModel = this.buildRadioButtonModelAdapter(this.colorHolder, TestModel.RED); - this.greenButtonModel = this.buildRadioButtonModelAdapter(this.colorHolder, TestModel.GREEN); - this.blueButtonModel = this.buildRadioButtonModelAdapter(this.colorHolder, TestModel.BLUE); - this.openWindow(); - } - - private ModifiablePropertyValueModel<Object> buildColorHolder(PropertyValueModel<TestModel> subjectHolder) { - return new PropertyAspectAdapter<TestModel, Object>(subjectHolder, TestModel.COLOR_PROPERTY) { - @Override - protected Object buildValue_() { - return this.subject.getColor(); - } - @Override - protected void setValue_(Object value) { - this.subject.setColor((String) value); - } - }; - } - - private ButtonModel buildRadioButtonModelAdapter(ModifiablePropertyValueModel<Object> colorPVM, String color) { - return new RadioButtonModelAdapter(colorPVM, color); - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setSize(400, 100); - window.setLocation(200, 200); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildRadioButtonPanel(), BorderLayout.NORTH); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildRadioButtonPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(1, 0)); - taskListPanel.add(this.buildRedRadioButton()); - taskListPanel.add(this.buildGreenRadioButton()); - taskListPanel.add(this.buildBlueRadioButton()); - return taskListPanel; - } - - private JRadioButton buildRedRadioButton() { - JRadioButton radioButton = new JRadioButton(); - radioButton.setText("red"); - radioButton.setModel(this.redButtonModel); - return radioButton; - } - - private JRadioButton buildGreenRadioButton() { - JRadioButton radioButton = new JRadioButton(); - radioButton.setText("green"); - radioButton.setModel(this.greenButtonModel); - return radioButton; - } - - private JRadioButton buildBlueRadioButton() { - JRadioButton radioButton = new JRadioButton(); - radioButton.setText("blue"); - radioButton.setModel(this.blueButtonModel); - return radioButton; - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(1, 0)); - controlPanel.add(this.buildResetColorButton()); - controlPanel.add(this.buildClearModelButton()); - controlPanel.add(this.buildRestoreModelButton()); - controlPanel.add(this.buildPrintModelButton()); - return controlPanel; - } - - private JButton buildResetColorButton() { - return new JButton(this.buildResetColorAction()); - } - - private Action buildResetColorAction() { - Action action = new AbstractAction("reset color") { - public void actionPerformed(ActionEvent event) { - RadioButtonModelAdapterUITest.this.resetColor(); - } - }; - action.setEnabled(true); - return action; - } - - void resetColor() { - this.testModel.setColor(TestModel.DEFAULT_COLOR); - } - - private JButton buildClearModelButton() { - return new JButton(this.buildClearModelAction()); - } - - private Action buildClearModelAction() { - Action action = new AbstractAction("clear model") { - public void actionPerformed(ActionEvent event) { - RadioButtonModelAdapterUITest.this.clearModel(); - } - }; - action.setEnabled(true); - return action; - } - - void clearModel() { - this.testModelHolder.setValue(null); - } - - private JButton buildRestoreModelButton() { - return new JButton(this.buildRestoreModelAction()); - } - - private Action buildRestoreModelAction() { - Action action = new AbstractAction("restore model") { - public void actionPerformed(ActionEvent event) { - RadioButtonModelAdapterUITest.this.restoreModel(); - } - }; - action.setEnabled(true); - return action; - } - - void restoreModel() { - this.testModelHolder.setValue(this.testModel); - } - - private JButton buildPrintModelButton() { - return new JButton(this.buildPrintModelAction()); - } - - private Action buildPrintModelAction() { - Action action = new AbstractAction("print model") { - public void actionPerformed(ActionEvent event) { - RadioButtonModelAdapterUITest.this.printModel(); - } - }; - action.setEnabled(true); - return action; - } - - void printModel() { - System.out.println(this.testModel); - } - - - private static class TestModel extends AbstractModel { - private String color; - public static final String COLOR_PROPERTY = "color"; - public static final String RED = "red"; - public static final String GREEN = "green"; - public static final String BLUE = "blue"; - public static final String DEFAULT_COLOR = RED; - public static final String[] VALID_COLORS = { - RED, - GREEN, - BLUE - }; - - public TestModel() { - this(DEFAULT_COLOR); - } - public TestModel(String color) { - this.color = color; - } - public String getColor() { - return this.color; - } - public void setColor(String color) { - if ( ! ArrayTools.contains(VALID_COLORS, color)) { - throw new IllegalArgumentException(color); - } - Object old = this.color; - this.color = color; - this.firePropertyChanged(COLOR_PROPERTY, old, color); - } - @Override - public String toString() { - return "TestModel(" + this.color + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ReadOnlyTableModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ReadOnlyTableModelAdapterUITest.java deleted file mode 100644 index 72cb1d2d31..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/ReadOnlyTableModelAdapterUITest.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import org.eclipse.jpt.common.utility.internal.model.value.swing.ColumnAdapter; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TableModelAdapterTests.PersonColumnAdapter; - -/** - * Make it easy to test the table model adapter and - * renderers without any editing allowed. - */ -public class ReadOnlyTableModelAdapterUITest extends TableModelAdapterUITest { - - public static void main(String[] args) throws Exception { - new ReadOnlyTableModelAdapterUITest().exec(args); - } - - protected ReadOnlyTableModelAdapterUITest() { - super(); - } - - @Override - protected ColumnAdapter buildColumnAdapter() { - return new PersonColumnAdapter() { - @Override - public boolean columnIsEditable(int index) { - return false; - } - }; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/SpinnerModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/SpinnerModelAdapterTests.java deleted file mode 100644 index 2beb3ea9d0..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/SpinnerModelAdapterTests.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import javax.swing.SpinnerModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.ReflectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.SpinnerModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SpinnerModelAdapterTests extends TestCase { - private ModifiablePropertyValueModel<Object> valueHolder; - SpinnerModel spinnerModelAdapter; - boolean eventFired; - - public SpinnerModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.valueHolder = new SimplePropertyValueModel<Object>(new Integer(0)); - this.spinnerModelAdapter = new SpinnerModelAdapter(this.valueHolder) { - @Override - protected PropertyChangeListener buildValueListener() { - return this.buildValueListener_(); - } - }; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testSetValueSpinnerModel() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - SpinnerModelAdapterTests.this.eventFired = true; - assertEquals(SpinnerModelAdapterTests.this.spinnerModelAdapter, e.getSource()); - } - }); - this.spinnerModelAdapter.setValue(new Integer(5)); - assertTrue(this.eventFired); - assertEquals(new Integer(5), this.valueHolder.getValue()); - } - - public void testSetValueValueHolder() throws Exception { - this.eventFired = false; - this.spinnerModelAdapter.addChangeListener(new TestChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - SpinnerModelAdapterTests.this.eventFired = true; - assertEquals(SpinnerModelAdapterTests.this.spinnerModelAdapter, e.getSource()); - } - }); - assertEquals(new Integer(0), this.spinnerModelAdapter.getValue()); - this.valueHolder.setValue(new Integer(7)); - assertTrue(this.eventFired); - assertEquals(new Integer(7), this.spinnerModelAdapter.getValue()); - } - - public void testHasListeners() throws Exception { - SimplePropertyValueModel<Object> localValueHolder = (SimplePropertyValueModel<Object>) this.valueHolder; - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - - ChangeListener listener = new TestChangeListener(); - this.spinnerModelAdapter.addChangeListener(listener); - assertTrue(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasListeners(this.spinnerModelAdapter); - - this.spinnerModelAdapter.removeChangeListener(listener); - assertFalse(localValueHolder.hasAnyPropertyChangeListeners(PropertyValueModel.VALUE)); - this.verifyHasNoListeners(this.spinnerModelAdapter); - } - - private void verifyHasNoListeners(Object adapter) throws Exception { - Object delegate = ReflectionTools.getFieldValue(adapter, "delegate"); - Object[] listeners = (Object[]) ReflectionTools.executeMethod(delegate, "getChangeListeners"); - assertEquals(0, listeners.length); - } - - private void verifyHasListeners(Object adapter) throws Exception { - Object delegate = ReflectionTools.getFieldValue(adapter, "delegate"); - Object[] listeners = (Object[]) ReflectionTools.executeMethod(delegate, "getChangeListeners"); - assertFalse(listeners.length == 0); - } - - - private class TestChangeListener implements ChangeListener { - TestChangeListener() { - super(); - } - public void stateChanged(ChangeEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/SpinnerModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/SpinnerModelAdapterUITest.java deleted file mode 100644 index 0d18f92b6d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/SpinnerModelAdapterUITest.java +++ /dev/null @@ -1,344 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.Calendar; -import java.util.Date; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerModel; -import javax.swing.WindowConstants; - -import org.eclipse.jpt.common.utility.internal.ArrayTools; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.DateSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.NumberSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -/** - * Play around with a set of spinners. - */ -@SuppressWarnings("nls") -public class SpinnerModelAdapterUITest { - - private TestModel testModel; - private ModifiablePropertyValueModel<TestModel> testModelHolder; - - private ModifiablePropertyValueModel<Object> birthDateHolder; - private SpinnerModel birthDateSpinnerModel; - - private ModifiablePropertyValueModel<Number> ageHolder; - private SpinnerModel ageSpinnerModel; - - private ModifiablePropertyValueModel<Object> eyeColorHolder; - private SpinnerModel eyeColorSpinnerModel; - - - public static void main(String[] args) throws Exception { - new SpinnerModelAdapterUITest().exec(); - } - - private SpinnerModelAdapterUITest() { - super(); - } - - private void exec() throws Exception { - this.testModel = new TestModel(); - this.testModelHolder = new SimplePropertyValueModel<TestModel>(this.testModel); - - this.birthDateHolder = this.buildBirthDateHolder(this.testModelHolder); - this.birthDateSpinnerModel = this.buildBirthDateSpinnerModel(this.birthDateHolder); - - this.ageHolder = this.buildAgeHolder(this.testModelHolder); - this.ageSpinnerModel = this.buildAgeSpinnerModel(this.ageHolder); - - this.eyeColorHolder = this.buildEyeColorHolder(this.testModelHolder); - this.eyeColorSpinnerModel = this.buildEyeColorSpinnerModel(this.eyeColorHolder); - - this.openWindow(); - } - - private ModifiablePropertyValueModel<Object> buildBirthDateHolder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Object>(vm, TestModel.BIRTH_DATE_PROPERTY) { - @Override - protected Object buildValue_() { - return this.subject.getBirthDate(); - } - @Override - protected void setValue_(Object value) { - this.subject.setBirthDate((Date) value); - } - }; - } - - private SpinnerModel buildBirthDateSpinnerModel(ModifiablePropertyValueModel<Object> valueHolder) { - return new DateSpinnerModelAdapter(valueHolder); - } - - private ModifiablePropertyValueModel<Number> buildAgeHolder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Number>(vm, TestModel.AGE_PROPERTY) { - @Override - protected Number buildValue_() { - return new Integer(this.subject.getAge()); - } - @Override - protected void setValue_(Number value) { - this.subject.setAge(value.intValue()); - } - }; - } - - private SpinnerModel buildAgeSpinnerModel(ModifiablePropertyValueModel<Number> valueHolder) { - return new NumberSpinnerModelAdapter(valueHolder, valueHolder.getValue().intValue(), TestModel.MIN_AGE, TestModel.MAX_AGE, 1); - } - - private ModifiablePropertyValueModel<Object> buildEyeColorHolder(PropertyValueModel<TestModel> vm) { - return new PropertyAspectAdapter<TestModel, Object>(vm, TestModel.EYE_COLOR_PROPERTY) { - @Override - protected Object buildValue_() { - return this.subject.getEyeColor(); - } - @Override - protected void setValue_(Object value) { - this.subject.setEyeColor((String) value); - } - }; - } - - private SpinnerModel buildEyeColorSpinnerModel(ModifiablePropertyValueModel<Object> valueHolder) { - return new ListSpinnerModelAdapter(valueHolder, TestModel.VALID_EYE_COLORS); - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setSize(600, 100); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildSpinnerPanel(), BorderLayout.NORTH); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildSpinnerPanel() { - JPanel taskListPanel = new JPanel(new GridLayout(1, 0)); - taskListPanel.add(this.buildBirthDateSpinner()); - taskListPanel.add(this.buildAgeSpinner()); - taskListPanel.add(this.buildEyeColorSpinner()); - return taskListPanel; - } - - private JSpinner buildBirthDateSpinner() { - return new JSpinner(this.birthDateSpinnerModel); - } - - private JSpinner buildAgeSpinner() { - return new JSpinner(this.ageSpinnerModel); - } - - private JSpinner buildEyeColorSpinner() { - return new JSpinner(this.eyeColorSpinnerModel); - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(1, 0)); - controlPanel.add(this.buildResetModelButton()); - controlPanel.add(this.buildClearModelButton()); - controlPanel.add(this.buildRestoreModelButton()); - controlPanel.add(this.buildPrintModelButton()); - return controlPanel; - } - - private JButton buildResetModelButton() { - return new JButton(this.buildResetModelAction()); - } - - private Action buildResetModelAction() { - Action action = new AbstractAction("reset model") { - public void actionPerformed(ActionEvent event) { - SpinnerModelAdapterUITest.this.resetModel(); - } - }; - action.setEnabled(true); - return action; - } - - void resetModel() { - this.testModel.setBirthDate(TestModel.DEFAULT_BIRTH_DATE); - this.testModel.setEyeColor(TestModel.DEFAULT_EYE_COLOR); - } - - private JButton buildClearModelButton() { - return new JButton(this.buildClearModelAction()); - } - - private Action buildClearModelAction() { - Action action = new AbstractAction("clear model") { - public void actionPerformed(ActionEvent event) { - SpinnerModelAdapterUITest.this.clearModel(); - } - }; - action.setEnabled(true); - return action; - } - - void clearModel() { - this.testModelHolder.setValue(null); - } - - private JButton buildRestoreModelButton() { - return new JButton(this.buildRestoreModelAction()); - } - - private Action buildRestoreModelAction() { - Action action = new AbstractAction("restore model") { - public void actionPerformed(ActionEvent event) { - SpinnerModelAdapterUITest.this.restoreModel(); - } - }; - action.setEnabled(true); - return action; - } - - void restoreModel() { - this.testModelHolder.setValue(this.testModel); - } - - private JButton buildPrintModelButton() { - return new JButton(this.buildPrintModelAction()); - } - - private Action buildPrintModelAction() { - Action action = new AbstractAction("print model") { - public void actionPerformed(ActionEvent event) { - SpinnerModelAdapterUITest.this.printModel(); - } - }; - action.setEnabled(true); - return action; - } - - void printModel() { - System.out.println("birth date: " + this.testModel.getBirthDate()); - System.out.println("age: " + this.testModel.getAge()); - System.out.println("eyes: " + this.testModel.getEyeColor()); - } - - - static class TestModel extends AbstractModel { - private Calendar birthCal = Calendar.getInstance(); - // "virtual" properties - public static final String BIRTH_DATE_PROPERTY = "birthDate"; - public static final String AGE_PROPERTY = "age"; - public static final Date DEFAULT_BIRTH_DATE = new Date(); - public static final int DEFAULT_AGE = 0; - public static final int MIN_AGE = 0; - public static final int MAX_AGE = 150; - private String eyeColor; - public static final String EYE_COLOR_PROPERTY = "eyeColor"; - public static final String[] VALID_EYE_COLORS = {"blue", "brown", "green", "hazel", "pink"}; - public static final String DEFAULT_EYE_COLOR = VALID_EYE_COLORS[3]; - - TestModel() { - this(DEFAULT_BIRTH_DATE, DEFAULT_EYE_COLOR); - } - public TestModel(Date birthDate, String eyeColor) { - this.setBirthDate(birthDate); - this.setEyeColor(eyeColor); - } - public Date getBirthDate() { - return (Date) this.birthCal.getTime().clone(); - } - public void setBirthDate(Date birthDate) { - Date oldBirthDate = this.getBirthDate(); - int oldAge = this.getAge(); - this.birthCal.setTimeInMillis(birthDate.getTime()); - int newAge = this.getAge(); - if (newAge < MIN_AGE || newAge > MAX_AGE) { - throw new IllegalArgumentException(birthDate.toString()); - } - this.firePropertyChanged(BIRTH_DATE_PROPERTY, oldBirthDate, this.getBirthDate()); - this.firePropertyChanged(AGE_PROPERTY, oldAge, newAge); - } - public int getAge() { - Calendar currentCal = Calendar.getInstance(); - int age = currentCal.get(Calendar.YEAR) - this.birthCal.get(Calendar.YEAR); - if (currentCal.get(Calendar.MONTH) < this.birthCal.get(Calendar.MONTH)) { - age--; - } else if (currentCal.get(Calendar.MONTH) == this.birthCal.get(Calendar.MONTH)) { - if (currentCal.get(Calendar.DAY_OF_MONTH) < this.birthCal.get(Calendar.DAY_OF_MONTH)) { - age--; - } - } - return age; - } - public void setAge(int newAge) { - if (newAge < MIN_AGE || newAge > MAX_AGE) { - throw new IllegalArgumentException(String.valueOf(newAge)); - } - - int oldAge = this.getAge(); - int delta = newAge - oldAge; - - Calendar newBirthCal = Calendar.getInstance(); - newBirthCal.setTimeInMillis(this.birthCal.getTime().getTime()); - // if the age increased, the birth date must be "decreased"; and vice versa - newBirthCal.set(Calendar.YEAR, newBirthCal.get(Calendar.YEAR) - delta); - this.setBirthDate(newBirthCal.getTime()); - } - public String getEyeColor() { - return this.eyeColor; - } - public void setEyeColor(String eyeColor) { - if ( ! ArrayTools.contains(VALID_EYE_COLORS, eyeColor)) { - throw new IllegalArgumentException(eyeColor); - } - Object old = this.eyeColor; - this.eyeColor = eyeColor; - this.firePropertyChanged(EYE_COLOR_PROPERTY, old, eyeColor); - } - @Override - public String toString() { - return "TestModel(birth: " + this.getBirthDate() + " - eyes: " + this.eyeColor + ")"; - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TableModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TableModelAdapterTests.java deleted file mode 100644 index d1eb281ea5..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TableModelAdapterTests.java +++ /dev/null @@ -1,641 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.StringTools; -import org.eclipse.jpt.common.utility.internal.iterators.CloneIterator; -import org.eclipse.jpt.common.utility.internal.iterators.TransformationIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ColumnAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.TableModelAdapter; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class TableModelAdapterTests extends TestCase { - private Crowd crowd; - TableModelEvent event; - - public TableModelAdapterTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.crowd = this.buildCrowd(); - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testGetRowCount() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - assertEquals(0, tableModelAdapter.getRowCount()); - // we need to add a listener to wake up the adapter - tableModelAdapter.addTableModelListener(this.buildTableModelListener()); - assertEquals(this.crowd.peopleSize(), tableModelAdapter.getRowCount()); - } - - public void testGetColumnCount() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - assertEquals(PersonColumnAdapter.COLUMN_COUNT, tableModelAdapter.getColumnCount()); - } - - public void testGetValueAt() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - tableModelAdapter.addTableModelListener(this.buildTableModelListener()); - - List<String> sortedNames = this.sortedNames(); - for (int i = 0; i < this.crowd.peopleSize(); i++) { - assertEquals(sortedNames.get(i), tableModelAdapter.getValueAt(i, PersonColumnAdapter.NAME_COLUMN)); - } - } - - public void testSetValueAt() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - this.event = null; - tableModelAdapter.addTableModelListener(new TestTableModelListener() { - @Override - public void tableChanged(TableModelEvent e) { - TableModelAdapterTests.this.event = e; - } - }); - - Person person = this.crowd.personNamed("Gollum"); - assertEquals(Person.EYE_COLOR_BLUE, person.getEyeColor()); - assertFalse(person.isEvil()); - assertEquals(0, person.getRank()); - - for (int i = 0; i < tableModelAdapter.getRowCount(); i++) { - if (tableModelAdapter.getValueAt(i, PersonColumnAdapter.NAME_COLUMN).equals("Gollum")) { - tableModelAdapter.setValueAt(Person.EYE_COLOR_HAZEL, i, PersonColumnAdapter.EYE_COLOR_COLUMN); - tableModelAdapter.setValueAt(Boolean.TRUE, i, PersonColumnAdapter.EVIL_COLUMN); - tableModelAdapter.setValueAt(new Integer(-1), i, PersonColumnAdapter.RANK_COLUMN); - break; - } - } - assertNotNull(this.event); - assertEquals(Person.EYE_COLOR_HAZEL, person.getEyeColor()); - assertTrue(person.isEvil()); - assertEquals(-1, person.getRank()); - } - - public void testAddRow() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - this.event = null; - tableModelAdapter.addTableModelListener(this.buildSingleEventListener()); - // add a person to the end of the list so we only trigger one event - this.crowd.addPerson("Zzzzz"); - assertNotNull(this.event); - assertEquals(TableModelEvent.INSERT, this.event.getType()); - assertEquals(TableModelEvent.ALL_COLUMNS, this.event.getColumn()); - } - - public void testRemoveRow() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - this.event = null; - tableModelAdapter.addTableModelListener(this.buildSingleEventListener()); - // removing a person should only trigger one event, since a re-sort is not needed - this.crowd.removePerson(this.crowd.personNamed("Gollum")); - assertNotNull(this.event); - assertEquals(TableModelEvent.DELETE, this.event.getType()); - assertEquals(TableModelEvent.ALL_COLUMNS, this.event.getColumn()); - } - - public void testChangeCell() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - this.event = null; - tableModelAdapter.addTableModelListener(this.buildSingleEventListener()); - // add a person to the end of the list so we only trigger one event - Person person = this.crowd.personNamed("Gollum"); - person.setEvil(true); - assertNotNull(this.event); - assertEquals(TableModelEvent.UPDATE, this.event.getType()); - assertEquals(PersonColumnAdapter.EVIL_COLUMN, this.event.getColumn()); - } - - public void testLazyListListener() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - TableModelListener listener = this.buildTableModelListener(); - assertTrue(this.crowd.hasNoCollectionChangeListeners(Crowd.PEOPLE_COLLECTION)); - tableModelAdapter.addTableModelListener(listener); - assertTrue(this.crowd.hasAnyCollectionChangeListeners(Crowd.PEOPLE_COLLECTION)); - tableModelAdapter.removeTableModelListener(listener); - assertTrue(this.crowd.hasNoCollectionChangeListeners(Crowd.PEOPLE_COLLECTION)); - } - - public void testLazyCellListener() throws Exception { - TableModelAdapter<Person> tableModelAdapter = this.buildTableModelAdapter(); - TableModelListener listener = this.buildTableModelListener(); - Person person = this.crowd.personNamed("Gollum"); - assertTrue(person.hasNoPropertyChangeListeners(Person.NAME_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.BIRTH_DATE_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.EYE_COLOR_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.EVIL_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.RANK_PROPERTY)); - - tableModelAdapter.addTableModelListener(listener); - assertTrue(person.hasAnyPropertyChangeListeners(Person.NAME_PROPERTY)); - assertTrue(person.hasAnyPropertyChangeListeners(Person.BIRTH_DATE_PROPERTY)); - assertTrue(person.hasAnyPropertyChangeListeners(Person.EYE_COLOR_PROPERTY)); - assertTrue(person.hasAnyPropertyChangeListeners(Person.EVIL_PROPERTY)); - assertTrue(person.hasAnyPropertyChangeListeners(Person.RANK_PROPERTY)); - - tableModelAdapter.removeTableModelListener(listener); - assertTrue(person.hasNoPropertyChangeListeners(Person.NAME_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.BIRTH_DATE_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.EYE_COLOR_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.EVIL_PROPERTY)); - assertTrue(person.hasNoPropertyChangeListeners(Person.RANK_PROPERTY)); - } - - private TableModelAdapter<Person> buildTableModelAdapter() { - return new TableModelAdapter<Person>(this.buildSortedPeopleAdapter(), this.buildColumnAdapter()) { - @Override - protected PropertyChangeListener buildCellListener() { - return this.buildCellListener_(); - } - @Override - protected ListChangeListener buildListChangeListener() { - return this.buildListChangeListener_(); - } - }; - } - - private ListValueModel<Person> buildSortedPeopleAdapter() { - return new SortedListValueModelAdapter<Person>(this.buildPeopleAdapter()); - } - - private CollectionValueModel<Person> buildPeopleAdapter() { - return new CollectionAspectAdapter<Crowd, Person>(Crowd.PEOPLE_COLLECTION, this.crowd) { - @Override - protected Iterator<Person> iterator_() { - return this.subject.people(); - } - @Override - protected int size_() { - return this.subject.peopleSize(); - } - }; - } - - private Crowd buildCrowd() { - Crowd result = new Crowd(); - result.addPerson("Bilbo"); - result.addPerson("Gollum"); - result.addPerson("Frodo"); - result.addPerson("Samwise"); - return result; - } - - private ColumnAdapter buildColumnAdapter() { - return new PersonColumnAdapter(); - } - - private TableModelListener buildTableModelListener() { - return new TestTableModelListener(); - } - - private List<String> sortedNames() { - return new ArrayList<String>(CollectionTools.sortedSet(this.crowd.peopleNames())); - } - - private TableModelListener buildSingleEventListener() { - return new TestTableModelListener() { - @Override - public void tableChanged(TableModelEvent e) { - // we expect only a single event - if (TableModelAdapterTests.this.event == null) { - TableModelAdapterTests.this.event = e; - } else { - fail("unexpected event"); - } - } - }; - } - - - // ********** classes ********** - - public static class PersonColumnAdapter implements ColumnAdapter { - public static final int COLUMN_COUNT = 7; - - public static final int NAME_COLUMN = 0; - public static final int BIRTH_DATE_COLUMN = 1; - public static final int GONE_WEST_DATE_COLUMN = 2; - public static final int EYE_COLOR_COLUMN = 3; - public static final int EVIL_COLUMN = 4; - public static final int RANK_COLUMN = 5; - public static final int ADVENTURE_COUNT_COLUMN = 6; - - private static final String[] COLUMN_NAMES = new String[] { - "Name", - "Birth", - "Gone West", - "Eyes", - "Evil", - "Rank", - "Adventures" - }; - - - public int columnCount() { - return COLUMN_COUNT; - } - - public String columnName(int index) { - return COLUMN_NAMES[index]; - } - - public Class<?> columnClass(int index) { - switch (index) { - case NAME_COLUMN: return Object.class; - case BIRTH_DATE_COLUMN: return Date.class; - case GONE_WEST_DATE_COLUMN: return Date.class; - case EYE_COLOR_COLUMN: return Object.class; - case EVIL_COLUMN: return Boolean.class; - case RANK_COLUMN: return Integer.class; - case ADVENTURE_COUNT_COLUMN:return Integer.class; - default: return Object.class; - } - } - - public boolean columnIsEditable(int index) { - return index != NAME_COLUMN; - } - - public ModifiablePropertyValueModel<Object>[] cellModels(Object subject) { - Person person = (Person) subject; - @SuppressWarnings("unchecked") - ModifiablePropertyValueModel<Object>[] result = new ModifiablePropertyValueModel[COLUMN_COUNT]; - - result[NAME_COLUMN] = this.buildNameAdapter(person); - result[BIRTH_DATE_COLUMN] = this.buildBirthDateAdapter(person); - result[GONE_WEST_DATE_COLUMN] = this.buildGoneWestDateAdapter(person); - result[EYE_COLOR_COLUMN] = this.buildEyeColorAdapter(person); - result[EVIL_COLUMN] = this.buildEvilAdapter(person); - result[RANK_COLUMN] = this.buildRankAdapter(person); - result[ADVENTURE_COUNT_COLUMN] = this.buildAdventureCountAdapter(person); - - return result; - } - - private ModifiablePropertyValueModel<Object> buildNameAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.NAME_PROPERTY, person) { - @Override - protected String buildValue_() { - return this.subject.getName(); - } - @Override - protected void setValue_(Object value) { - this.subject.setName((String) value); - } - }; - } - - private ModifiablePropertyValueModel<Object> buildBirthDateAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.BIRTH_DATE_PROPERTY, person) { - @Override - protected Date buildValue_() { - return this.subject.getBirthDate(); - } - @Override - protected void setValue_(Object value) { - this.subject.setBirthDate((Date) value); - } - }; - } - - private ModifiablePropertyValueModel<Object> buildGoneWestDateAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.GONE_WEST_DATE_PROPERTY, person) { - @Override - protected Date buildValue_() { - return this.subject.getGoneWestDate(); - } - @Override - protected void setValue_(Object value) { - this.subject.setGoneWestDate((Date) value); - } - }; - } - - private ModifiablePropertyValueModel<Object> buildEyeColorAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.EYE_COLOR_PROPERTY, person) { - @Override - protected String buildValue_() { - return this.subject.getEyeColor(); - } - @Override - protected void setValue_(Object value) { - this.subject.setEyeColor((String) value); - } - }; - } - - private ModifiablePropertyValueModel<Object> buildEvilAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.EVIL_PROPERTY, person) { - @Override - protected Boolean buildValue_() { - return Boolean.valueOf(this.subject.isEvil()); - } - @Override - protected void setValue_(Object value) { - this.subject.setEvil(((Boolean)value).booleanValue()); - } - }; - } - - private ModifiablePropertyValueModel<Object> buildRankAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.RANK_PROPERTY, person) { - @Override - protected Integer buildValue_() { - return new Integer(this.subject.getRank()); - } - @Override - protected void setValue_(Object value) { - this.subject.setRank(((Integer) value).intValue()); - } - }; - } - - private ModifiablePropertyValueModel<Object> buildAdventureCountAdapter(Person person) { - return new PropertyAspectAdapter<Person, Object>(Person.ADVENTURE_COUNT_PROPERTY, person) { - @Override - protected Integer buildValue_() { - return new Integer(this.subject.getAdventureCount()); - } - @Override - protected void setValue_(Object value) { - this.subject.setAdventureCount(((Integer) value).intValue()); - } - }; - } - - } - - - public static class Crowd extends AbstractModel { - private final Collection<Person> people; - public static final String PEOPLE_COLLECTION = "people"; - - public Crowd() { - super(); - this.people = new ArrayList<Person>(); - } - - - public Iterator<Person> people() { - return new CloneIterator<Person>(this.people) { - @Override - protected void remove(Person person) { - Crowd.this.removePerson(person); - } - }; - } - - public int peopleSize() { - return this.people.size(); - } - - public Person addPerson(String name) { - this.checkPersonName(name); - return this.addPerson(new Person(this, name)); - } - - private Person addPerson(Person person) { - this.addItemToCollection(person, this.people, PEOPLE_COLLECTION); - return person; - } - - public void removePerson(Person person) { - this.removeItemFromCollection(person, this.people, PEOPLE_COLLECTION); - } - - public void removePeople(Collection<Person> persons) { - this.removeItemsFromCollection(persons, this.people, PEOPLE_COLLECTION); - } - - public void removePeople(Iterator<Person> persons) { - this.removeItemsFromCollection(persons, this.people, PEOPLE_COLLECTION); - } - - void checkPersonName(String personName) { - if (personName == null) { - throw new NullPointerException(); - } - if (CollectionTools.contains(this.peopleNames(), personName)) { - throw new IllegalArgumentException(personName); - } - } - - public Iterator<String> peopleNames() { - return new TransformationIterator<Person, String>(this.people.iterator()) { - @Override - protected String transform(Person person) { - return person.getName(); - } - }; - } - - public Person personNamed(String name) { - for (Iterator<Person> stream = this.people.iterator(); stream.hasNext(); ) { - Person person = stream.next(); - if (person.getName().equals(name)) { - return person; - } - } - return null; - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, String.valueOf(this.people.size()) + " people"); - } - - } - - - public static class Person extends AbstractModel implements Comparable<Person> { - private Crowd crowd; - private String name; - public static final String NAME_PROPERTY= "name"; - private Date birthDate; - public static final String BIRTH_DATE_PROPERTY= "birthDate"; - private Date goneWestDate; - public static final String GONE_WEST_DATE_PROPERTY= "goneWestDate"; - private String eyeColor; - public static final String EYE_COLOR_PROPERTY= "eyeColor"; - public static final String EYE_COLOR_BLUE = "blue"; - public static final String EYE_COLOR_GREEN = "green"; - public static final String EYE_COLOR_BROWN = "brown"; - public static final String EYE_COLOR_HAZEL = "hazel"; - public static final String EYE_COLOR_PINK = "pink"; - private static Collection<String> validEyeColors; - public static final String DEFAULT_EYE_COLOR = EYE_COLOR_BLUE; - private boolean evil; - public static final String EVIL_PROPERTY= "evil"; - private int rank; - public static final String RANK_PROPERTY= "rank"; - private int adventureCount; - public static final String ADVENTURE_COUNT_PROPERTY= "adventureCount"; - - Person(Crowd crowd, String name) { - super(); - this.crowd = crowd; - this.name = name; - this.birthDate = new Date(); - Calendar c = Calendar.getInstance(); - c.add(Calendar.YEAR, 250); - this.goneWestDate = new Date(c.getTimeInMillis()); - this.eyeColor = DEFAULT_EYE_COLOR; - this.evil = false; - this.rank = 0; - this.adventureCount = 0; - } - - public static Collection<String> getValidEyeColors() { - if (validEyeColors == null) { - validEyeColors = buildValidEyeColors(); - } - return validEyeColors; - } - - private static Collection<String> buildValidEyeColors() { - Collection<String> result = new ArrayList<String>(); - result.add(EYE_COLOR_BLUE); - result.add(EYE_COLOR_GREEN); - result.add(EYE_COLOR_BROWN); - result.add(EYE_COLOR_HAZEL); - result.add(EYE_COLOR_PINK); - return result; - } - - public Crowd getCrowd() { - return this.crowd; - } - - public String getName() { - return this.name; - } - public void setName(String name) { - this.crowd.checkPersonName(name); - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - public Date getBirthDate() { - return this.birthDate; - } - public void setBirthDate(Date birthDate) { - Object old = this.birthDate; - this.birthDate = birthDate; - this.firePropertyChanged(BIRTH_DATE_PROPERTY, old, birthDate); - } - - public Date getGoneWestDate() { - return this.goneWestDate; - } - public void setGoneWestDate(Date goneWestDate) { - Object old = this.goneWestDate; - this.goneWestDate = goneWestDate; - this.firePropertyChanged(GONE_WEST_DATE_PROPERTY, old, goneWestDate); - } - - public String getEyeColor() { - return this.eyeColor; - } - public void setEyeColor(String eyeColor) { - if (! getValidEyeColors().contains(eyeColor)) { - throw new IllegalArgumentException(eyeColor); - } - Object old = this.eyeColor; - this.eyeColor = eyeColor; - this.firePropertyChanged(EYE_COLOR_PROPERTY, old, eyeColor); - } - - public boolean isEvil() { - return this.evil; - } - public void setEvil(boolean evil) { - boolean old = this.evil; - this.evil = evil; - this.firePropertyChanged(EVIL_PROPERTY, old, evil); - } - - public int getRank() { - return this.rank; - } - public void setRank(int rank) { - int old = this.rank; - this.rank = rank; - this.firePropertyChanged(RANK_PROPERTY, old, rank); - } - - public int getAdventureCount() { - return this.adventureCount; - } - public void setAdventureCount(int adventureCount) { - int old = this.adventureCount; - this.adventureCount = adventureCount; - this.firePropertyChanged(ADVENTURE_COUNT_PROPERTY, old, adventureCount); - } - - public int compareTo(Person p) { - return this.name.compareToIgnoreCase(p.name); - } - - @Override - public String toString() { - return this.name + - "\tborn: " + DateFormat.getDateInstance().format(this.birthDate) + - "\tgone west: " + DateFormat.getDateInstance().format(this.goneWestDate) + - "\teyes: " + this.eyeColor + - "\tevil: " + this.evil + - "\trank: " + this.rank + - "\tadventures: " + this.adventureCount - ; - } - - } - - - private class TestTableModelListener implements TableModelListener { - TestTableModelListener() { - super(); - } - public void tableChanged(TableModelEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TableModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TableModelAdapterUITest.java deleted file mode 100644 index 1fba1a6966..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TableModelAdapterUITest.java +++ /dev/null @@ -1,733 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ButtonModel; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListCellRenderer; -import javax.swing.ListSelectionModel; -import javax.swing.SpinnerModel; -import javax.swing.UIManager; -import javax.swing.WindowConstants; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.TableColumn; -import javax.swing.table.TableModel; -import javax.swing.text.Document; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.ItemPropertyListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleCollectionValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.model.value.swing.CheckBoxModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ColumnAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ComboBoxModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.DateSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.DocumentAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ListModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.NumberSpinnerModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.swing.ObjectListSelectionModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.TableModelAdapter; -import org.eclipse.jpt.common.utility.internal.swing.CheckBoxTableCellRenderer; -import org.eclipse.jpt.common.utility.internal.swing.ComboBoxTableCellRenderer; -import org.eclipse.jpt.common.utility.internal.swing.SpinnerTableCellRenderer; -import org.eclipse.jpt.common.utility.internal.swing.TableCellEditorAdapter; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TableModelAdapterTests.Crowd; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TableModelAdapterTests.Person; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TableModelAdapterTests.PersonColumnAdapter; - -/** - * an example UI for testing the TableModelAdapter - * "name" column is read-only text field - * "birth date" column is date text field - * "gone west date" column is date spinner - * "eye color" column is combo-box - * "evil" column is check box - * "rank" column is number text field - * "adventure count" column is number spinner - * - * Note that the table model and row selection model share the same - * list value model (the sorted people adapter) - */ -@SuppressWarnings("nls") -public class TableModelAdapterUITest { - private SimpleCollectionValueModel<Object> eyeColorsHolder; // Object because it adapts to a combo-box - private ModifiablePropertyValueModel<Crowd> crowdHolder; - private ModifiablePropertyValueModel<Person> selectedPersonHolder; - private ListValueModel<Person> sortedPeopleAdapter; - private TableModel tableModel; - private ObjectListSelectionModel rowSelectionModel; - private Action removeAction; - private Action renameAction; - - public static void main(String[] args) throws Exception { - new TableModelAdapterUITest().exec(args); - } - - protected TableModelAdapterUITest() { - super(); - } - - protected void exec(@SuppressWarnings("unused") String[] args) throws Exception { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - this.eyeColorsHolder = this. buildEyeColorCollectionHolder(); - this.crowdHolder = this.buildCrowdHolder(); - this.selectedPersonHolder = this.buildSelectedPersonHolder(); - this.sortedPeopleAdapter = this.buildSortedPeopleAdapter(); - this.tableModel = this.buildTableModel(); - this.rowSelectionModel = this.buildRowSelectionModel(); - this.openWindow(); - } - - private SimpleCollectionValueModel<Object> buildEyeColorCollectionHolder() { - return new SimpleCollectionValueModel<Object>(new ArrayList<Object>(Person.getValidEyeColors())); - } - - private ModifiablePropertyValueModel<Crowd> buildCrowdHolder() { - return new SimplePropertyValueModel<Crowd>(this.buildCrowd()); - } - - private Crowd buildCrowd() { - Crowd crowd = new Crowd(); - - Person p = crowd.addPerson("Bilbo"); - p.setEyeColor(Person.EYE_COLOR_BROWN); - p.setRank(22); - p.setAdventureCount(1); - - p = crowd.addPerson("Gollum"); - p.setEyeColor(Person.EYE_COLOR_PINK); - p.setEvil(true); - p.setRank(2); - p.setAdventureCount(50); - - p = crowd.addPerson("Frodo"); - p.setEyeColor(Person.EYE_COLOR_BLUE); - p.setRank(34); - p.setAdventureCount(1); - - p = crowd.addPerson("Samwise"); - p.setEyeColor(Person.EYE_COLOR_GREEN); - p.setRank(19); - p.setAdventureCount(1); - - return crowd; - } - - private ModifiablePropertyValueModel<Person> buildSelectedPersonHolder() { - return new SimplePropertyValueModel<Person>(); - } - - private ListValueModel<Person> buildSortedPeopleAdapter() { - return new SortedListValueModelWrapper<Person>(this.buildPeopleNameAdapter()); - } - - // the list will need to be re-sorted if a name changes - private ListValueModel<Person> buildPeopleNameAdapter() { - return new ItemPropertyListValueModelAdapter<Person>(this.buildPeopleAdapter(), Person.NAME_PROPERTY); - } - - private CollectionValueModel<Person> buildPeopleAdapter() { - return new CollectionAspectAdapter<Crowd, Person>(this.crowdHolder, Crowd.PEOPLE_COLLECTION) { - @Override - protected Iterator<Person> iterator_() { - return this.subject.people(); - } - @Override - protected int size_() { - return this.subject.peopleSize(); - } - }; - } - - private TableModel buildTableModel() { - return new TableModelAdapter<Person>(this.sortedPeopleAdapter, this.buildColumnAdapter()); - } - - protected ColumnAdapter buildColumnAdapter() { - return new PersonColumnAdapter(); - } - - private ObjectListSelectionModel buildRowSelectionModel() { - ObjectListSelectionModel rsm = new ObjectListSelectionModel(new ListModelAdapter(this.sortedPeopleAdapter)); - rsm.addListSelectionListener(this.buildRowSelectionListener()); - rsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - return rsm; - } - - private ListSelectionListener buildRowSelectionListener() { - return new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - if (e.getValueIsAdjusting()) { - return; - } - TableModelAdapterUITest.this.rowSelectionChanged(e); - } - }; - } - - void rowSelectionChanged(@SuppressWarnings("unused") ListSelectionEvent event) { - Person selection = (Person) this.rowSelectionModel.selectedValue(); - this.selectedPersonHolder.setValue(selection); - boolean personSelected = (selection != null); - this.removeAction.setEnabled(personSelected); - this.renameAction.setEnabled(personSelected); - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getSimpleName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setLocation(200, 200); - window.setSize(600, 400); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildTablePane(), BorderLayout.CENTER); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildTablePane() { - return new JScrollPane(this.buildTable()); - } - - private JTable buildTable() { - JTable table = new JTable(this.tableModel); - table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); // see Java bug 5007652 - table.setSelectionModel(this.rowSelectionModel); - table.setDoubleBuffered(true); - table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); - int rowHeight = 20; // start with minimum of 20 - - // gone west column (spinner) - TableColumn column = table.getColumnModel().getColumn(PersonColumnAdapter.GONE_WEST_DATE_COLUMN); - SpinnerTableCellRenderer spinnerRenderer = this.buildDateSpinnerRenderer(); - column.setCellRenderer(spinnerRenderer); - column.setCellEditor(new TableCellEditorAdapter(this.buildDateSpinnerRenderer())); - rowHeight = Math.max(rowHeight, spinnerRenderer.preferredHeight()); - - // eye color column (combo-box) - // the jdk combo-box renderer looks like a text field - // until the user starts an edit - use a custom one - column = table.getColumnModel().getColumn(PersonColumnAdapter.EYE_COLOR_COLUMN); - ComboBoxTableCellRenderer eyeColorRenderer = this.buildEyeColorComboBoxRenderer(); - column.setCellRenderer(eyeColorRenderer); - column.setCellEditor(new TableCellEditorAdapter(this.buildEyeColorComboBoxRenderer())); - rowHeight = Math.max(rowHeight, eyeColorRenderer.preferredHeight()); - - // evil (check box) - // the jdk check box renderer and editor suck - use a custom ones - column = table.getColumnModel().getColumn(PersonColumnAdapter.EVIL_COLUMN); - CheckBoxTableCellRenderer evilRenderer = new CheckBoxTableCellRenderer(); - column.setCellRenderer(evilRenderer); - column.setCellEditor(new TableCellEditorAdapter(new CheckBoxTableCellRenderer())); - rowHeight = Math.max(rowHeight, evilRenderer.preferredHeight()); - - // adventure count column (spinner) - column = table.getColumnModel().getColumn(PersonColumnAdapter.ADVENTURE_COUNT_COLUMN); - spinnerRenderer = this.buildNumberSpinnerRenderer(); - column.setCellRenderer(spinnerRenderer); - column.setCellEditor(new TableCellEditorAdapter(this.buildNumberSpinnerRenderer())); - rowHeight = Math.max(rowHeight, spinnerRenderer.preferredHeight()); - - table.setRowHeight(rowHeight); - return table; - } - - private SpinnerTableCellRenderer buildDateSpinnerRenderer() { - return new SpinnerTableCellRenderer(new DateSpinnerModelAdapter(new SimplePropertyValueModel<Object>())); - } - - private SpinnerTableCellRenderer buildNumberSpinnerRenderer() { - return new SpinnerTableCellRenderer(new NumberSpinnerModelAdapter(new SimplePropertyValueModel<Number>())); - } - - private ComboBoxTableCellRenderer buildEyeColorComboBoxRenderer() { - return new ComboBoxTableCellRenderer(this.buildReadOnlyEyeColorComboBoxModel(), this.buildEyeColorRenderer()); - } - - private ComboBoxModel buildReadOnlyEyeColorComboBoxModel() { - return new ComboBoxModelAdapter(this.eyeColorsHolder, new SimplePropertyValueModel<Object>()); - } - - private ListCellRenderer buildEyeColorRenderer() { - return new EyeColorRenderer(); - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(0, 1)); - controlPanel.add(this.buildButtonPanel()); - controlPanel.add(this.buildPersonPanel()); - return controlPanel; - } - - private Component buildButtonPanel() { - JPanel buttonPanel = new JPanel(new GridLayout(1, 0)); - buttonPanel.add(this.buildAddButton()); - buttonPanel.add(this.buildRemoveButton()); - buttonPanel.add(this.buildRenameButton()); - buttonPanel.add(this.buildAddEyeColorButton()); - buttonPanel.add(this.buildPrintButton()); - buttonPanel.add(this.buildResetButton()); - return buttonPanel; - } - - private Component buildPersonPanel() { - JPanel personPanel = new JPanel(new GridLayout(1, 0)); - personPanel.add(this.buildNameTextField()); - personPanel.add(this.buildBirthDateSpinner()); - personPanel.add(this.buildGoneWestDateSpinner()); - personPanel.add(this.buildEyeColorComboBox()); - personPanel.add(this.buildEvilCheckBox()); - personPanel.add(this.buildRankSpinner()); - personPanel.add(this.buildAdventureCountSpinner()); - return personPanel; - } - - - // ********** add button ********** - - private JButton buildAddButton() { - return new JButton(this.buildAddAction()); - } - - private Action buildAddAction() { - Action action = new AbstractAction("add") { - public void actionPerformed(ActionEvent event) { - TableModelAdapterUITest.this.addPerson(); - } - }; - action.setEnabled(true); - return action; - } - - void addPerson() { - String name = this.getNameFromUser(); - if (name != null) { - this.setSelectedPerson(this.crowd().addPerson(name)); - } - } - - - // ********** remove button ********** - - private JButton buildRemoveButton() { - return new JButton(this.buildRemoveAction()); - } - - private Action buildRemoveAction() { - this.removeAction = new AbstractAction("remove") { - public void actionPerformed(ActionEvent event) { - TableModelAdapterUITest.this.removePerson(); - } - }; - this.removeAction.setEnabled(false); - return this.removeAction; - } - - void removePerson() { - Person person = this.selectedPerson(); - if (person != null) { - this.crowd().removePerson(person); - } - } - - - // ********** rename button ********** - - private JButton buildRenameButton() { - return new JButton(this.buildRenameAction()); - } - - private Action buildRenameAction() { - this.renameAction = new AbstractAction("rename") { - public void actionPerformed(ActionEvent event) { - TableModelAdapterUITest.this.renamePerson(); - } - }; - this.renameAction.setEnabled(false); - return this.renameAction; - } - - void renamePerson() { - Person person = this.selectedPerson(); - if (person != null) { - String name = this.promptUserForName(person.getName()); - if (name != null) { - person.setName(name); - this.setSelectedPerson(person); - } - } - } - - - // ********** add eye color button ********** - - private JButton buildAddEyeColorButton() { - return new JButton(this.buildAddEyeColorAction()); - } - - private Action buildAddEyeColorAction() { - Action action = new AbstractAction("add eye color") { - public void actionPerformed(ActionEvent event) { - TableModelAdapterUITest.this.addEyeColor(); - } - }; - action.setEnabled(true); - return action; - } - - void addEyeColor() { - String color = this.promptUserForEyeColor(); - if (color != null) { - this.eyeColorsHolder.add(color); - } - } - - private String promptUserForEyeColor() { - while (true) { - String eyeColor = JOptionPane.showInputDialog("Eye Color"); - if (eyeColor == null) { - return null; // user pressed <Cancel> - } - if ((eyeColor.length() == 0)) { - JOptionPane.showMessageDialog(null, "The eye color is required.", "Invalid Eye Color", JOptionPane.ERROR_MESSAGE); - } else if (CollectionTools.contains(this.eyeColorsHolder.iterator(), eyeColor)) { - JOptionPane.showMessageDialog(null, "The eye color already exists.", "Invalid Eye Color", JOptionPane.ERROR_MESSAGE); - } else { - return eyeColor; - } - } - } - - - // ********** print button ********** - - private JButton buildPrintButton() { - return new JButton(this.buildPrintAction()); - } - - private Action buildPrintAction() { - Action action = new AbstractAction("print") { - public void actionPerformed(ActionEvent event) { - TableModelAdapterUITest.this.printCrowd(); - } - }; - action.setEnabled(true); - return action; - } - - void printCrowd() { - System.out.println(this.crowd()); - for (Iterator<Person> stream = this.crowd().people(); stream.hasNext(); ) { - System.out.println("\t" + stream.next()); - } - } - - - // ********** reset button ********** - - private JButton buildResetButton() { - return new JButton(this.buildResetAction()); - } - - private Action buildResetAction() { - Action action = new AbstractAction("reset") { - public void actionPerformed(ActionEvent event) { - TableModelAdapterUITest.this.reset(); - } - }; - action.setEnabled(true); - return action; - } - - void reset() { - this.crowdHolder.setValue(this.buildCrowd()); - } - - - // ********** new name dialog ********** - - private String getNameFromUser() { - return this.promptUserForName(null); - } - - private String promptUserForName(@SuppressWarnings("unused") String originalName) { - while (true) { - String name = JOptionPane.showInputDialog("Person Name"); - if (name == null) { - return null; // user pressed <Cancel> - } - if ((name.length() == 0)) { - JOptionPane.showMessageDialog(null, "The name is required.", "Invalid Name", JOptionPane.ERROR_MESSAGE); - } else if (CollectionTools.contains(this.crowd().peopleNames(), name)) { - JOptionPane.showMessageDialog(null, "The name already exists.", "Invalid Name", JOptionPane.ERROR_MESSAGE); - } else { - return name; - } - } - } - - - // ********** name text field ********** - - private Component buildNameTextField() { - JTextField textField = new JTextField(this.buildNameDocument(), null, 0); - textField.setEditable(false); - return textField; - } - - private Document buildNameDocument() { - return new DocumentAdapter(this.buildNameAdapter()); - } - - private ModifiablePropertyValueModel<String> buildNameAdapter() { - return new PropertyAspectAdapter<Person, String>(this.selectedPersonHolder, Person.NAME_PROPERTY) { - @Override - protected String buildValue_() { - return this.subject.getName(); - } - @Override - protected void setValue_(String value) { - this.subject.setName(value); - } - }; - } - - - // ********** birth date spinner ********** - - private JSpinner buildBirthDateSpinner() { - return new JSpinner(this.buildBirthDateSpinnerModel()); - } - - private SpinnerModel buildBirthDateSpinnerModel() { - return new DateSpinnerModelAdapter(this.buildBirthDateAdapter()); - } - - private ModifiablePropertyValueModel<Object> buildBirthDateAdapter() { - return new PropertyAspectAdapter<Person, Object>(this.selectedPersonHolder, Person.BIRTH_DATE_PROPERTY) { - @Override - protected Date buildValue_() { - return this.subject.getBirthDate(); - } - @Override - protected void setValue_(Object value) { - this.subject.setBirthDate((Date) value); - } - }; - } - - - // ********** gone west date spinner ********** - - private JSpinner buildGoneWestDateSpinner() { - return new JSpinner(this.buildGoneWestDateSpinnerModel()); - } - - private SpinnerModel buildGoneWestDateSpinnerModel() { - return new DateSpinnerModelAdapter(this.buildGoneWestDateAdapter()); - } - - private ModifiablePropertyValueModel<Object> buildGoneWestDateAdapter() { - return new PropertyAspectAdapter<Person, Object>(this.selectedPersonHolder, Person.GONE_WEST_DATE_PROPERTY) { - @Override - protected Date buildValue_() { - return this.subject.getGoneWestDate(); - } - @Override - protected void setValue_(Object value) { - this.subject.setGoneWestDate((Date) value); - } - }; - } - - - // ********** eye color combo-box ********** - - private JComboBox buildEyeColorComboBox() { - return new JComboBox(this.buildEyeColorComboBoxModel()); - } - - private ComboBoxModel buildEyeColorComboBoxModel() { - return new ComboBoxModelAdapter(this.eyeColorsHolder, this.buildEyeColorAdapter()); - } - - private ModifiablePropertyValueModel<Object> buildEyeColorAdapter() { - return new PropertyAspectAdapter<Person, Object>(this.selectedPersonHolder, Person.EYE_COLOR_PROPERTY) { - @Override - protected Object buildValue_() { - return this.subject.getEyeColor(); - } - @Override - protected void setValue_(Object value) { - this.subject.setEyeColor((String) value); - } - }; - } - - - // ********** evil check box ********** - - private JCheckBox buildEvilCheckBox() { - JCheckBox checkBox = new JCheckBox(); - checkBox.setText("evil"); - checkBox.setModel(this.buildEvilCheckBoxModel()); - return checkBox; - } - - private ButtonModel buildEvilCheckBoxModel() { - return new CheckBoxModelAdapter(this.buildEvilAdapter()); - } - - private ModifiablePropertyValueModel<Boolean> buildEvilAdapter() { - return new PropertyAspectAdapter<Person, Boolean>(this.selectedPersonHolder, Person.EVIL_PROPERTY) { - @Override - protected Boolean buildValue_() { - return Boolean.valueOf(this.subject.isEvil()); - } - @Override - protected void setValue_(Boolean value) { - this.subject.setEvil(value.booleanValue()); - } - }; - } - - - // ********** rank spinner ********** - - private JSpinner buildRankSpinner() { - return new JSpinner(this.buildRankSpinnerModel()); - } - - private SpinnerModel buildRankSpinnerModel() { - return new NumberSpinnerModelAdapter(this.buildRankAdapter()); - } - - private ModifiablePropertyValueModel<Number> buildRankAdapter() { - return new PropertyAspectAdapter<Person, Number>(this.selectedPersonHolder, Person.RANK_PROPERTY) { - @Override - protected Number buildValue_() { - return new Integer(this.subject.getRank()); - } - @Override - protected void setValue_(Number value) { - this.subject.setRank(value.intValue()); - } - }; - } - - - // ********** adventure count spinner ********** - - private JSpinner buildAdventureCountSpinner() { - return new JSpinner(this.buildAdventureCountSpinnerModel()); - } - - private SpinnerModel buildAdventureCountSpinnerModel() { - return new NumberSpinnerModelAdapter(this.buildAdventureCountAdapter()); - } - - private ModifiablePropertyValueModel<Number> buildAdventureCountAdapter() { - return new PropertyAspectAdapter<Person, Number>(this.selectedPersonHolder, Person.ADVENTURE_COUNT_PROPERTY) { - @Override - protected Number buildValue_() { - return new Integer(this.subject.getAdventureCount()); - } - @Override - protected void setValue_(Number value) { - this.subject.setAdventureCount(value.intValue()); - } - }; - } - - - // ********** queries ********** - - private Crowd crowd() { - return this.crowdHolder.getValue(); - } - - private Person selectedPerson() { - if (this.rowSelectionModel.isSelectionEmpty()) { - return null; - } - return (Person) this.rowSelectionModel.selectedValue(); - } - - private void setSelectedPerson(Person person) { - this.rowSelectionModel.setSelectedValue(person); - } - - - // ********** custom renderer ********** - - /** - * This is simply an example of a renderer for the embedded combo-box. - * It does nothing special unless you uncomment the code below.... - */ - private class EyeColorRenderer extends DefaultListCellRenderer { - EyeColorRenderer() { - super(); - } - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - // just do something to show the renderer is working... - // value = ">" + value; - return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TreeModelAdapterTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TreeModelAdapterTests.java deleted file mode 100644 index 247c3ae569..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TreeModelAdapterTests.java +++ /dev/null @@ -1,812 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; - -import javax.swing.Icon; -import javax.swing.JTree; -import javax.swing.event.TreeModelEvent; -import javax.swing.event.TreeModelListener; -import javax.swing.tree.TreeModel; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.IndentingPrintWriter; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.StringTools; -import org.eclipse.jpt.common.utility.internal.iterators.ReadOnlyIterator; -import org.eclipse.jpt.common.utility.internal.model.AbstractModel; -import org.eclipse.jpt.common.utility.internal.model.value.AbstractTreeNodeValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.CollectionAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.ItemPropertyListValueModelAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.NullListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.PropertyAspectAdapter; -import org.eclipse.jpt.common.utility.internal.model.value.SimpleListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.SortedListValueModelWrapper; -import org.eclipse.jpt.common.utility.internal.model.value.StaticPropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.TransformationListValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.TreeModelAdapter; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; -import org.eclipse.jpt.common.utility.model.listener.ListChangeListener; -import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; -import org.eclipse.jpt.common.utility.model.listener.StateChangeListener; -import org.eclipse.jpt.common.utility.model.value.CollectionValueModel; -import org.eclipse.jpt.common.utility.model.value.ListValueModel; -import org.eclipse.jpt.common.utility.model.value.PropertyValueModel; -import org.eclipse.jpt.common.utility.model.value.TreeNodeValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; - -@SuppressWarnings("nls") -public class TreeModelAdapterTests extends TestCase { - boolean eventFired; - - public TreeModelAdapterTests(String name) { - super(name); - } - - public void testGetRoot() { - TreeModel treeModel = this.buildSortedTreeModel(); - treeModel.addTreeModelListener(new TestTreeModelListener()); - TestNode rootNode = (TestNode) treeModel.getRoot(); - TestModel root = rootNode.getTestModel(); - assertEquals("root", root.getName()); -// root.dump(); -// rootNode.dump(); - } - - public void testGetChild() { - TreeModel treeModel = this.buildSortedTreeModel(); - treeModel.addTreeModelListener(new TestTreeModelListener()); - TestNode rootNode = (TestNode) treeModel.getRoot(); - - TestNode expected = rootNode.childNamed("node 1"); - TestNode actual = (TestNode) treeModel.getChild(rootNode, 1); - assertEquals(expected, actual); - - expected = rootNode.childNamed("node 2"); - actual = (TestNode) treeModel.getChild(rootNode, 2); - assertEquals(expected, actual); - } - - public void testGetChildCount() { - TreeModel treeModel = this.buildSortedTreeModel(); - treeModel.addTreeModelListener(new TestTreeModelListener()); - TestNode rootNode = (TestNode) treeModel.getRoot(); - - assertEquals(5, treeModel.getChildCount(rootNode)); - - TestNode node = rootNode.childNamed("node 1"); - assertEquals(1, treeModel.getChildCount(node)); - } - - public void testGetIndexOfChild() { - TreeModel treeModel = this.buildSortedTreeModel(); - treeModel.addTreeModelListener(new TestTreeModelListener()); - TestNode rootNode = (TestNode) treeModel.getRoot(); - - TestNode child = rootNode.childNamed("node 0"); - assertEquals(0, treeModel.getIndexOfChild(rootNode, child)); - - child = rootNode.childNamed("node 1"); - assertEquals(1, treeModel.getIndexOfChild(rootNode, child)); - - child = rootNode.childNamed("node 2"); - assertEquals(2, treeModel.getIndexOfChild(rootNode, child)); - TestNode grandchild = child.childNamed("node 2.2"); - assertEquals(2, treeModel.getIndexOfChild(child, grandchild)); - } - - public void testIsLeaf() { - TreeModel treeModel = this.buildSortedTreeModel(); - treeModel.addTreeModelListener(new TestTreeModelListener()); - TestNode rootNode = (TestNode) treeModel.getRoot(); - assertFalse(treeModel.isLeaf(rootNode)); - TestNode node = rootNode.childNamed("node 1"); - assertFalse(treeModel.isLeaf(node)); - node = rootNode.childNamed("node 3"); - assertTrue(treeModel.isLeaf(node)); - } - - - public void testTreeNodesChanged() { - // the only way to trigger a "node changed" event is to use an unsorted tree; - // a sorted tree will will trigger only "node removed" and "node inserted" events - TreeModel treeModel = this.buildUnsortedTreeModel(); - this.eventFired = false; - treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesChanged(TreeModelEvent e) { - TreeModelAdapterTests.this.eventFired = true; - } - }); - TestNode rootNode = (TestNode) treeModel.getRoot(); - TestNode node = rootNode.childNamed("node 1"); - TestModel tm = node.getTestModel(); - tm.setName("node 1++"); - assertTrue(this.eventFired); - - this.eventFired = false; - node = node.childNamed("node 1.1"); - tm = node.getTestModel(); - tm.setName("node 1.1++"); - assertTrue(this.eventFired); - } - - public void testTreeNodesInserted() { - // use an unsorted tree so the nodes are not re-shuffled... - TreeModel treeModel = this.buildUnsortedTreeModel(); - this.eventFired = false; - treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesInserted(TreeModelEvent e) { - TreeModelAdapterTests.this.eventFired = true; - } - }); - TestNode rootNode = (TestNode) treeModel.getRoot(); - TestNode node = rootNode.childNamed("node 1"); - TestModel tm = node.getTestModel(); - tm.addChild("new child..."); - assertTrue(this.eventFired); - - this.eventFired = false; - node = node.childNamed("node 1.1"); - tm = node.getTestModel(); - tm.addChild("another new child..."); - assertTrue(this.eventFired); - } - - public void testTreeNodesRemoved() { - TreeModel treeModel = this.buildUnsortedTreeModel(); - this.eventFired = false; - treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesRemoved(TreeModelEvent e) { - TreeModelAdapterTests.this.eventFired = true; - } - }); - TestNode rootNode = (TestNode) treeModel.getRoot(); - TestModel root = rootNode.getTestModel(); - root.removeChild(root.childNamed("node 3")); - assertTrue(this.eventFired); - - this.eventFired = false; - TestNode node = rootNode.childNamed("node 2"); - TestModel tm = node.getTestModel(); - tm.removeChild(tm.childNamed("node 2.2")); - assertTrue(this.eventFired); - } - - public void testTreeStructureChanged() { - ModifiablePropertyValueModel<TreeNodeValueModel<Object>> nodeHolder = new SimplePropertyValueModel<TreeNodeValueModel<Object>>(this.buildSortedRootNode()); - TreeModel treeModel = this.buildTreeModel(nodeHolder); - this.eventFired = false; - treeModel.addTreeModelListener(new TestTreeModelListener() { - @Override - public void treeNodesInserted(TreeModelEvent e) { - // do nothing - } - @Override - public void treeNodesRemoved(TreeModelEvent e) { - // do nothing - } - @Override - public void treeStructureChanged(TreeModelEvent e) { - TreeModelAdapterTests.this.eventFired = true; - } - }); - nodeHolder.setValue(this.buildUnsortedRootNode()); - assertTrue(this.eventFired); - } - - /** - * test a problem we had where removing a child from a tree would cause - * the JTree to call #equals(Object) on each node removed (actually, it was - * TreePath, but that was because its own #equals(Object) was called by - * JTree); and since we had already removed the last listener from the - * aspect adapter, the aspect adapter would say its value was null; this - * would cause a NPE until we tweaked TreeModelAdapter to remove its - * listeners from a node only *after* the node had been completely - * removed from the JTree - * @see TreeModelAdapter#removeNode(Object[], int, TreeNodeValueModel) - * @see TreeModelAdapter#addNode(Object[], int, TreeNodeValueModel) - */ - public void testLazyInitialization() { - TreeModel treeModel = this.buildSpecialTreeModel(); - JTree jTree = new JTree(treeModel); - TestNode rootNode = (TestNode) treeModel.getRoot(); - TestModel root = rootNode.getTestModel(); - // this would cause a NPE: - root.removeChild(root.childNamed("node 3")); - assertEquals(treeModel, jTree.getModel()); - } - - - private TreeModel buildSortedTreeModel() { - return this.buildTreeModel(this.buildSortedRootNode()); - } - - private TestNode buildSortedRootNode() { - return new SortedTestNode(this.buildRoot()); - } - - private TreeModel buildUnsortedTreeModel() { - return this.buildTreeModel(this.buildUnsortedRootNode()); - } - - private TestNode buildUnsortedRootNode() { - return new UnsortedTestNode(this.buildRoot()); - } - - private TreeModel buildSpecialTreeModel() { - return this.buildTreeModel(this.buildSpecialRootNode()); - } - - private TestNode buildSpecialRootNode() { - return new SpecialTestNode(this.buildRoot()); - } - - private TestModel buildRoot() { - TestModel root = new TestModel("root"); - /*Node node_0 = */root.addChild("node 0"); - TestModel node_1 = root.addChild("node 1"); - TestModel node_1_1 = node_1.addChild("node 1.1"); - /*Node node_1_1_1 = */node_1_1.addChild("node 1.1.1"); - TestModel node_2 = root.addChild("node 2"); - /*Node node_2_0 = */node_2.addChild("node 2.0"); - /*Node node_2_1 = */node_2.addChild("node 2.1"); - /*Node node_2_2 = */node_2.addChild("node 2.2"); - /*Node node_2_3 = */node_2.addChild("node 2.3"); - /*Node node_2_4 = */node_2.addChild("node 2.4"); - /*Node node_2_5 = */node_2.addChild("node 2.5"); - /*Node node_3 = */root.addChild("node 3"); - /*Node node_4 = */root.addChild("node 4"); - return root; - } - - - // ********** member classes ********** - - /** - * This is a typical model class with the typical change notifications - * for #name and #children. - */ - public static class TestModel extends AbstractModel { - - // the parent is immutable; the root's parent is null - private final TestModel parent; - - // the name is mutable; so I guess it isn't the "primary key" :-) - private String name; - public static final String NAME_PROPERTY = "name"; - - private final Collection<TestModel> children; - public static final String CHILDREN_COLLECTION = "children"; - - - public TestModel(String name) { // root ctor - this(null, name); - } - private TestModel(TestModel parent, String name) { - super(); - this.parent = parent; - this.name = name; - this.children = new HashBag<TestModel>(); - } - - public TestModel getParent() { - return this.parent; - } - - public String getName() { - return this.name; - } - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - public Iterator<TestModel> children() { - return new ReadOnlyIterator<TestModel>(this.children); - } - public int childrenSize() { - return this.children.size(); - } - public TestModel addChild(String childName) { - TestModel child = new TestModel(this, childName); - this.addItemToCollection(child, this.children, CHILDREN_COLLECTION); - return child; - } - public TestModel[] addChildren(String[] childNames) { - TestModel[] newChildren = new TestModel[childNames.length]; - for (int i = 0; i < childNames.length; i++) { - newChildren[i] = new TestModel(this, childNames[i]); - } - this.addItemsToCollection(newChildren, this.children, CHILDREN_COLLECTION); - return newChildren; - } - public void removeChild(TestModel child) { - this.removeItemFromCollection(child, this.children, CHILDREN_COLLECTION); - } - public void removeChildren(TestModel[] testModels) { - this.removeItemsFromCollection(testModels, this.children, CHILDREN_COLLECTION); - } - public void clearChildren() { - this.clearCollection(this.children, CHILDREN_COLLECTION); - } - public TestModel childNamed(String childName) { - for (TestModel child : this.children) { - if (child.getName().equals(childName)) { - return child; - } - } - throw new RuntimeException("child not found: " + childName); - } - - public String dumpString() { - StringWriter sw = new StringWriter(); - IndentingPrintWriter ipw = new IndentingPrintWriter(sw); - this.dumpOn(ipw); - return sw.toString(); - } - public void dumpOn(IndentingPrintWriter writer) { - writer.println(this); - writer.indent(); - for (TestModel child : this.children) { - child.dumpOn(writer); - } - writer.undent(); - } - public void dumpOn(OutputStream stream) { - IndentingPrintWriter writer = new IndentingPrintWriter(new OutputStreamWriter(stream)); - this.dumpOn(writer); - writer.flush(); - } - public void dump() { - this.dumpOn(System.out); - } - - @Override - public String toString() { - return StringTools.buildToStringFor(this, this.name); - } - - } - - - /** - * This Node wraps a TestModel and converts into something that can - * be used by TreeModelAdapter. It converts changes to the TestModel's - * name into "state changes" to the Node; and converts the - * TestModel's children into a ListValueModel of Nodes whose order is - * determined by subclass implementations. - */ - public static abstract class TestNode extends AbstractTreeNodeValueModel<Object> implements Displayable, Comparable<TestNode> { - /** the model object wrapped by this node */ - private final TestModel testModel; - /** this node's parent node; null for the root node */ - private final TestNode parent; - /** this node's child nodes */ - private final ListValueModel<TreeNodeValueModel<Object>> childrenModel; - /** a listener that notifies us when the model object's "internal state" changes */ - private final PropertyChangeListener testModelListener; - - - // ********** constructors/initialization ********** - - /** - * root node constructor - */ - public TestNode(TestModel testModel) { - this(null, testModel); - } - - /** - * branch or leaf node constructor - */ - public TestNode(TestNode parent, TestModel testModel) { - super(); - this.parent = parent; - this.testModel = testModel; - this.childrenModel = this.buildChildrenModel(testModel); - this.testModelListener = this.buildTestModelListener(); - } - - private PropertyChangeListener buildTestModelListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - TestNode.this.testModelChanged(e); - } - }; - } - - /** - * subclasses decide the order of the child nodes - */ - protected abstract ListValueModel<TreeNodeValueModel<Object>> buildChildrenModel(TestModel model); - - /** - * used by subclasses; - * transform the test model children into nodes - */ - protected ListValueModel<TreeNodeValueModel<Object>> buildNodeAdapter(TestModel model) { - return new TransformationListValueModel<TestModel, TreeNodeValueModel<Object>>(this.buildChildrenAdapter(model)) { - @Override - protected TestNode transformItem(TestModel item) { - return TestNode.this.buildChildNode(item); - } - }; - } - - /** - * subclasses must build a concrete node for the specified test model - */ - protected abstract TestNode buildChildNode(TestModel childTestModel); - - /** - * return a collection value model on the specified model's children - */ - protected CollectionValueModel<TestModel> buildChildrenAdapter(TestModel model) { - return new CollectionAspectAdapter<TestModel, TestModel>(TestModel.CHILDREN_COLLECTION, model) { - @Override - protected Iterator<TestModel> iterator_() { - return this.subject.children(); - } - @Override - protected int size_() { - return this.subject.childrenSize(); - } - }; - } - - - // ********** TreeNodeValueModel implementation ********** - - public TestModel getValue() { - return this.testModel; - } - - public TreeNodeValueModel<Object> parent() { - return this.parent; - } - - public ListValueModel<TreeNodeValueModel<Object>> childrenModel() { - return this.childrenModel; - } - - - // ********** AbstractTreeNodeValueModel implementation ********** - - @Override - protected void engageValue() { - this.testModel.addPropertyChangeListener(TestModel.NAME_PROPERTY, this.testModelListener); - } - - @Override - protected void disengageValue() { - this.testModel.removePropertyChangeListener(TestModel.NAME_PROPERTY, this.testModelListener); - } - - - // ********** Displayable implementation ********** - - public String displayString() { - return this.testModel.getName(); - } - - public Icon icon() { - return null; - } - - - // ********** debugging support ********** - - public String dumpString() { - StringWriter sw = new StringWriter(); - IndentingPrintWriter ipw = new IndentingPrintWriter(sw); - this.dumpOn(ipw); - return sw.toString(); - } - - public void dumpOn(IndentingPrintWriter writer) { - writer.println(this); - writer.indent(); - for (Iterator<TreeNodeValueModel<Object>> stream = this.childrenModel.iterator(); stream.hasNext(); ) { - // cast to a TestNode (i.e. this won't work with a NameTestNode in the tree) - ((TestNode) stream.next()).dumpOn(writer); - } - writer.undent(); - } - - public void dumpOn(OutputStream stream) { - IndentingPrintWriter writer = new IndentingPrintWriter(new OutputStreamWriter(stream)); - this.dumpOn(writer); - writer.flush(); - } - - public void dump() { - this.dumpOn(System.out); - } - - - // ********** behavior ********** - - /** - * the model's name has changed, forward the event to our listeners - */ - protected void testModelChanged(PropertyChangeEvent e) { - // we need to notify listeners that our "internal state" has changed - this.fireStateChanged(); - // our display string stays in synch with the model's name - this.firePropertyChanged(DISPLAY_STRING_PROPERTY, e.getOldValue(), e.getNewValue()); - } - - - // ********** queries ********** - - public TestModel getTestModel() { - return this.testModel; - } - - /** - * testing convenience method - */ - public TestNode childNamed(String name) { - for (Iterator<TreeNodeValueModel<Object>> stream = this.childrenModel.iterator(); stream.hasNext(); ) { - TreeNodeValueModel<Object> childNode = stream.next(); - if (childNode instanceof TestNode) { - if (((TestNode) childNode).getTestModel().getName().equals(name)) { - return (TestNode) childNode; - } - } - } - throw new IllegalArgumentException("child not found: " + name); - } - - - // ********** standard methods ********** - - public int compareTo(TestNode o) { - return this.displayString().compareTo(o.displayString()); - } - - @Override - public String toString() { - return "Node(" + this.testModel + ")"; - } - - } - - /** - * concrete implementation that keeps its children sorted - */ - public static class SortedTestNode extends TestNode { - - // ********** constructors ********** - public SortedTestNode(TestModel testModel) { - super(testModel); - } - public SortedTestNode(TestNode parent, TestModel testModel) { - super(parent, testModel); - } - - // ********** initialization ********** - /** the list should be sorted */ - @Override - protected ListValueModel<TreeNodeValueModel<Object>> buildChildrenModel(TestModel testModel) { - return new SortedListValueModelWrapper<TreeNodeValueModel<Object>>(this.buildDisplayStringAdapter(testModel)); - } - /** the display string (name) of each node can change */ - protected ListValueModel<TreeNodeValueModel<Object>> buildDisplayStringAdapter(TestModel testModel) { - return new ItemPropertyListValueModelAdapter<TreeNodeValueModel<Object>>(this.buildNodeAdapter(testModel), DISPLAY_STRING_PROPERTY); - } - /** children are also sorted nodes */ - @Override - protected TestNode buildChildNode(TestModel childNode) { - return new SortedTestNode(this, childNode); - } - - } - - - /** - * concrete implementation that leaves its children unsorted - */ - public static class UnsortedTestNode extends TestNode { - - // ********** constructors ********** - public UnsortedTestNode(TestModel testModel) { - super(testModel); - } - public UnsortedTestNode(TestNode parent, TestModel testModel) { - super(parent, testModel); - } - - // ********** initialization ********** - /** the list should NOT be sorted */ - @Override - protected ListValueModel<TreeNodeValueModel<Object>> buildChildrenModel(TestModel testModel) { - return this.buildNodeAdapter(testModel); - } - /** children are also unsorted nodes */ - @Override - protected TestNode buildChildNode(TestModel childNode) { - return new UnsortedTestNode(this, childNode); - } - - } - - - /** - * concrete implementation that leaves its children unsorted - * and has a special set of children for "node 3" - */ - public static class SpecialTestNode extends UnsortedTestNode { - - // ********** constructors ********** - public SpecialTestNode(TestModel testModel) { - super(testModel); - } - public SpecialTestNode(TestNode parent, TestModel testModel) { - super(parent, testModel); - } - - // ********** initialization ********** - /** return a different list of children for "node 3" */ - @Override - protected ListValueModel<TreeNodeValueModel<Object>> buildChildrenModel(TestModel testModel) { - if (testModel.getName().equals("node 3")) { - return this.buildSpecialChildrenModel(); - } - return super.buildChildrenModel(testModel); - } - protected ListValueModel<TreeNodeValueModel<Object>> buildSpecialChildrenModel() { - TreeNodeValueModel<Object>[] children = new NameTestNode[1]; - children[0] = new NameTestNode(this); - return new SimpleListValueModel<TreeNodeValueModel<Object>>(Arrays.asList(children)); - } - /** children are also special nodes */ - @Override - protected TestNode buildChildNode(TestModel childNode) { - return new SpecialTestNode(this, childNode); - } - - } - - - public static class NameTestNode extends AbstractTreeNodeValueModel<Object> { - private final ModifiablePropertyValueModel<String> nameAdapter; - private final SpecialTestNode specialNode; // parent node - private final PropertyChangeListener nameListener; - private final ListValueModel<TreeNodeValueModel<Object>> childrenModel; - - // ********** construction/initialization ********** - - public NameTestNode(SpecialTestNode specialNode) { - super(); - this.nameListener = this.buildNameListener(); - this.specialNode = specialNode; - this.nameAdapter = this.buildNameAdapter(); - this.childrenModel = new NullListValueModel<TreeNodeValueModel<Object>>(); - } - protected PropertyChangeListener buildNameListener() { - return new PropertyChangeListener() { - public void propertyChanged(PropertyChangeEvent e) { - NameTestNode.this.nameChanged(e); - } - }; - } - protected ModifiablePropertyValueModel<String> buildNameAdapter() { - return new PropertyAspectAdapter<TestModel, String>(TestModel.NAME_PROPERTY, this.getTestModel()) { - @Override - protected String buildValue_() { - return this.subject.getName(); - } - @Override - protected void setValue_(String value) { - this.subject.setName(value); - } - }; - } - - public TestModel getTestModel() { - return this.specialNode.getTestModel(); - } - - // ********** TreeNodeValueModel implementation ********** - - public String getValue() { - return this.nameAdapter.getValue(); - } - @Override - public void setValue(Object value) { - this.nameAdapter.setValue((String) value); - } - public TreeNodeValueModel<Object> parent() { - return this.specialNode; - } - public ListValueModel<TreeNodeValueModel<Object>> childrenModel() { - return this.childrenModel; - } - - // ********** AbstractTreeNodeValueModel implementation ********** - - @Override - protected void engageValue() { - this.nameAdapter.addPropertyChangeListener(PropertyValueModel.VALUE, this.nameListener); - } - @Override - protected void disengageValue() { - this.nameAdapter.removePropertyChangeListener(PropertyValueModel.VALUE, this.nameListener); - } - - // ********** behavior ********** - - protected void nameChanged(PropertyChangeEvent e) { - // we need to notify listeners that our "value" has changed - this.firePropertyChanged(VALUE, e.getOldValue(), e.getNewValue()); - } - } - - private TreeModel buildTreeModel(TestNode root) { - return this.buildTreeModel(new StaticPropertyValueModel<TreeNodeValueModel<Object>>(root)); - } - - private TreeModel buildTreeModel(PropertyValueModel<TreeNodeValueModel<Object>> rootHolder) { - return new TreeModelAdapter<Object>(rootHolder) { - @Override - protected ListChangeListener buildChildrenListener() { - return this.buildChildrenListener_(); - } - @Override - protected StateChangeListener buildNodeStateListener() { - return this.buildNodeStateListener_(); - } - @Override - protected PropertyChangeListener buildNodeValueListener() { - return this.buildNodeValueListener_(); - } - @Override - protected PropertyChangeListener buildRootListener() { - return this.buildRootListener_(); - } - }; - } - - - - /** - * listener that will blow up with any event; - * override and implement expected event methods - */ - public class TestTreeModelListener implements TreeModelListener { - public void treeNodesChanged(TreeModelEvent e) { - fail("unexpected event"); - } - public void treeNodesInserted(TreeModelEvent e) { - fail("unexpected event"); - } - public void treeNodesRemoved(TreeModelEvent e) { - fail("unexpected event"); - } - public void treeStructureChanged(TreeModelEvent e) { - fail("unexpected event"); - } - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TreeModelAdapterUITest.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TreeModelAdapterUITest.java deleted file mode 100644 index 9ab759c561..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/model/value/swing/TreeModelAdapterUITest.java +++ /dev/null @@ -1,425 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.model.value.swing; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.TextField; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.WindowConstants; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.iterators.EnumerationIterator; -import org.eclipse.jpt.common.utility.internal.model.value.SimplePropertyValueModel; -import org.eclipse.jpt.common.utility.internal.model.value.swing.TreeModelAdapter; -import org.eclipse.jpt.common.utility.internal.swing.Displayable; -import org.eclipse.jpt.common.utility.model.value.TreeNodeValueModel; -import org.eclipse.jpt.common.utility.model.value.ModifiablePropertyValueModel; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TreeModelAdapterTests.SortedTestNode; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TreeModelAdapterTests.TestModel; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TreeModelAdapterTests.TestNode; -import org.eclipse.jpt.common.utility.tests.internal.model.value.swing.TreeModelAdapterTests.UnsortedTestNode; - -/** - * an example UI for testing the TreeModelAdapter - */ -@SuppressWarnings("nls") -public class TreeModelAdapterUITest { - - // hold the tree so we can restore its expansion state - private JTree tree; - private ModifiablePropertyValueModel<TreeNodeValueModel<Object>> rootNodeHolder; - private boolean sorted; - private TreeModel treeModel; - private TreeSelectionModel treeSelectionModel; - private TextField nameTextField; - - public static void main(String[] args) throws Exception { - new TreeModelAdapterUITest().exec(); - } - - private TreeModelAdapterUITest() { - super(); - } - - private void exec() throws Exception { - this.rootNodeHolder = this.buildRootNodeHolder(); - this.sorted = this.rootNodeHolder.getValue() instanceof SortedTestNode; - this.treeModel = this.buildTreeModel(); - this.treeSelectionModel = this.buildTreeSelectionModel(); - this.nameTextField = new TextField(); - this.openWindow(); - } - - private ModifiablePropertyValueModel<TreeNodeValueModel<Object>> buildRootNodeHolder() { - return new SimplePropertyValueModel<TreeNodeValueModel<Object>>(this.buildSortedRootNode()); - } - - private TestNode buildSortedRootNode() { - return new SortedTestNode(this.buildRoot()); - } - - private TestNode buildUnsortedRootNode() { - return new UnsortedTestNode(this.buildRoot()); - } - - private TestModel buildRoot() { - TestModel root = new TestModel("root"); - - TestModel node_1 = root.addChild("node 1"); - /*Node node_1_1 = */node_1.addChild("node 1.1"); - - TestModel node_2 = root.addChild("node 2"); - /*Node node_2_1 = */node_2.addChild("node 2.1"); - TestModel node_2_2 = node_2.addChild("node 2.2"); - /*Node node_2_2_1 = */node_2_2.addChild("node 2.2.1"); - /*Node node_2_2_2 = */node_2_2.addChild("node 2.2.2"); - /*Node node_2_3 = */node_2.addChild("node 2.3"); - /*Node node_2_4 = */node_2.addChild("node 2.4"); - /*Node node_2_5 = */node_2.addChild("node 2.5"); - - TestModel node_3 = root.addChild("node 3"); - TestModel node_3_1 = node_3.addChild("node 3.1"); - TestModel node_3_1_1 = node_3_1.addChild("node 3.1.1"); - /*Node node_3_1_1_1 = */node_3_1_1.addChild("node 3.1.1.1"); - - /*Node node_4 = */root.addChild("node 4"); - - return root; - } - - private TreeModel buildTreeModel() { - return new TreeModelAdapter<Object>(this.rootNodeHolder); - } - - private TreeSelectionModel buildTreeSelectionModel() { - TreeSelectionModel tsm = new DefaultTreeSelectionModel(); - tsm.addTreeSelectionListener(this.buildTreeSelectionListener()); - tsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - return tsm; - } - - private TreeSelectionListener buildTreeSelectionListener() { - return new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - TreeModelAdapterUITest.this.treeSelectionChanged(e); - } - }; - } - - void treeSelectionChanged(@SuppressWarnings("unused") TreeSelectionEvent e) { - TestModel selectedTestModel = this.selectedTestModel(); - if (selectedTestModel != null) { - this.nameTextField.setText(selectedTestModel.getName()); - } - } - - private void openWindow() { - JFrame window = new JFrame(this.getClass().getName()); - window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - window.addWindowListener(this.buildWindowListener()); - window.getContentPane().add(this.buildMainPanel(), "Center"); - window.setLocation(300, 300); - window.setSize(400, 400); - window.setVisible(true); - } - - private WindowListener buildWindowListener() { - return new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - e.getWindow().setVisible(false); - System.exit(0); - } - }; - } - - private Component buildMainPanel() { - JPanel mainPanel = new JPanel(new BorderLayout()); - mainPanel.add(this.buildTreePane(), BorderLayout.CENTER); - mainPanel.add(this.buildControlPanel(), BorderLayout.SOUTH); - return mainPanel; - } - - private Component buildTreePane() { - return new JScrollPane(this.buildTree()); - } - - private JTree buildTree() { - this.tree = new JTree(this.treeModel) { - @Override - public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { - return ((Displayable) value).displayString(); - } - }; - this.tree.setSelectionModel(this.treeSelectionModel); - this.tree.setRootVisible(true); - this.tree.setShowsRootHandles(true); - this.tree.setRowHeight(20); - this.tree.setDoubleBuffered(true); - return this.tree; - } - - private Component buildControlPanel() { - JPanel controlPanel = new JPanel(new GridLayout(0, 1)); - controlPanel.add(this.buildAddRenameNodePanel()); - controlPanel.add(this.buildMiscPanel()); - return controlPanel; - } - - private Component buildAddRenameNodePanel() { - JPanel addRenameNodePanel = new JPanel(new BorderLayout()); - addRenameNodePanel.add(this.buildAddButton(), BorderLayout.WEST); - addRenameNodePanel.add(this.nameTextField, BorderLayout.CENTER); - addRenameNodePanel.add(this.buildRenameButton(), BorderLayout.EAST); - return addRenameNodePanel; - } - - private Component buildMiscPanel() { - JPanel miscPanel = new JPanel(new GridLayout(1, 0)); - miscPanel.add(this.buildClearChildrenButton()); - miscPanel.add(this.buildRemoveButton()); - miscPanel.add(this.buildResetButton()); - return miscPanel; - } - - private String getName() { - return this.nameTextField.getText(); - } - - // ********** queries ********** - private TestNode selectedNode() { - if (this.treeSelectionModel.isSelectionEmpty()) { - return null; - } - return (TestNode) this.treeSelectionModel.getSelectionPath().getLastPathComponent(); - } - - private TestModel selectedTestModel() { - if (this.treeSelectionModel.isSelectionEmpty()) { - return null; - } - return this.selectedNode().getValue(); - } - - private TestNode rootNode() { - return (TestNode) this.treeModel.getRoot(); - } - - private TestModel root() { - return this.rootNode().getValue(); - } - - private Collection<TreePath> expandedPaths() { - Enumeration<TreePath> stream = this.tree.getExpandedDescendants(new TreePath(this.rootNode())); - if (stream == null) { - return Collections.emptyList(); - } - return CollectionTools.list(new EnumerationIterator<TreePath>(stream)); - } - - // ********** behavior ********** - private void setSelectedNode(TestNode selectedNode) { - this.treeSelectionModel.setSelectionPath(new TreePath(selectedNode.path())); - } - - private void expandPaths(Collection<TreePath> paths) { - for (TreePath path : paths) { - this.tree.expandPath(path); - } - } - - // ********** add ********** - private JButton buildAddButton() { - return new JButton(this.buildAddAction()); - } - - private Action buildAddAction() { - Action action = new AbstractAction("add") { - public void actionPerformed(ActionEvent event) { - TreeModelAdapterUITest.this.addNode(); - } - }; - action.setEnabled(true); - return action; - } - - /** - * adding causes the tree to be sorted and nodes to be - * removed and re-added; so we have to fiddle with the expansion state - */ - void addNode() { - TestModel selectedTestModel = this.selectedTestModel(); - if (selectedTestModel != null) { - String name = this.getName(); - // save the expansion state and restore it after the add - Collection<TreePath> paths = this.expandedPaths(); - - selectedTestModel.addChild(name); - - this.expandPaths(paths); - this.setSelectedNode(this.selectedNode().childNamed(name)); - } - } - - // ********** remove ********** - private JButton buildRemoveButton() { - return new JButton(this.buildRemoveAction()); - } - - private Action buildRemoveAction() { - Action action = new AbstractAction("remove") { - public void actionPerformed(ActionEvent event) { - TreeModelAdapterUITest.this.removeNode(); - } - }; - action.setEnabled(true); - return action; - } - - /** - * we need to figure out which node to select after - * the selected node is deleted - */ - void removeNode() { - TestModel selectedTestModel = this.selectedTestModel(); - // do not allow the root to be removed - if ((selectedTestModel != null) && (selectedTestModel != this.root())) { - // save the parent and index, so we can select another, nearby, node - // once the selected node is removed - TestNode parentNode = (TestNode) this.selectedNode().parent(); - int childIndex = parentNode.indexOfChild(this.selectedNode()); - - selectedTestModel.getParent().removeChild(selectedTestModel); - - int childrenSize = parentNode.childrenSize(); - if (childIndex < childrenSize) { - // select the child that moved up and replaced the just-deleted child - this.setSelectedNode((TestNode) parentNode.child(childIndex)); - } else { - if (childrenSize == 0) { - // if there are no more children, select the parent - this.setSelectedNode(parentNode); - } else { - // if the child at the bottom of the list was deleted, select the next child up - this.setSelectedNode((TestNode) parentNode.child(childIndex - 1)); - } - } - } - } - - // ********** rename ********** - private JButton buildRenameButton() { - return new JButton(this.buildRenameAction()); - } - - private Action buildRenameAction() { - Action action = new AbstractAction("rename") { - public void actionPerformed(ActionEvent event) { - TreeModelAdapterUITest.this.renameNode(); - } - }; - action.setEnabled(true); - return action; - } - - /** - * renaming causes the tree to be sorted and nodes to be - * removed and re-added; so we have to fiddle with the expansion state - */ - void renameNode() { - TestModel selectedTestModel = this.selectedTestModel(); - if (selectedTestModel != null) { - // save the node and re-select it after the rename - TestNode selectedNode = this.selectedNode(); - // save the expansion state and restore it after the rename - Collection<TreePath> paths = this.expandedPaths(); - - selectedTestModel.setName(this.getName()); - - this.expandPaths(paths); - this.setSelectedNode(selectedNode); - } - } - - // ********** clear children ********** - private JButton buildClearChildrenButton() { - return new JButton(this.buildClearChildrenAction()); - } - - private Action buildClearChildrenAction() { - Action action = new AbstractAction("clear children") { - public void actionPerformed(ActionEvent event) { - TreeModelAdapterUITest.this.clearChildren(); - } - }; - action.setEnabled(true); - return action; - } - - /** - * nothing special, we just want to test #fireCollectionChanged(String) - */ - void clearChildren() { - TestModel selectedTestModel = this.selectedTestModel(); - if (selectedTestModel != null) { - selectedTestModel.clearChildren(); - } - } - - // ********** reset ********** - private JButton buildResetButton() { - return new JButton(this.buildResetAction()); - } - - private Action buildResetAction() { - Action action = new AbstractAction("reset") { - public void actionPerformed(ActionEvent event) { - TreeModelAdapterUITest.this.reset(); - } - }; - action.setEnabled(true); - return action; - } - - /** - * test the adapter's root node holder; - * toggle between sorted and unsorted lists - */ - void reset() { - this.sorted = ! this.sorted; - if (this.sorted) { - this.rootNodeHolder.setValue(this.buildSortedRootNode()); - } else { - this.rootNodeHolder.setValue(this.buildUnsortedRootNode()); - } - this.tree.expandPath(new TreePath(this.rootNode())); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/node/AbstractNodeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/node/AbstractNodeTests.java deleted file mode 100644 index 74cd629a88..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/node/AbstractNodeTests.java +++ /dev/null @@ -1,495 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.node; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.internal.CollectionTools; -import org.eclipse.jpt.common.utility.internal.HashBag; -import org.eclipse.jpt.common.utility.internal.iterators.CloneIterator; -import org.eclipse.jpt.common.utility.internal.node.AbstractNode; -import org.eclipse.jpt.common.utility.internal.node.Node; -import org.eclipse.jpt.common.utility.internal.node.Problem; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class AbstractNodeTests extends TestCase { - private TestWorkbenchModel root; - - public AbstractNodeTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.root = this.buildRoot(); - } - - private TestWorkbenchModel buildRoot() { - TestWorkbenchModel r = new RootTestWorkbenchModel("root"); - TestWorkbenchModel node1 = r.addTestChildNamed("node 1"); - TestWorkbenchModel node1_1 = node1.addTestChildNamed("node 1.1"); - node1_1.addTestChildNamed("node 1.1.1"); - node1_1.addTestChildNamed("node 1.1.2"); - node1_1.addTestChildNamed("node 1.1.3"); - node1.addTestChildNamed("node 1.2"); - TestWorkbenchModel node2 = r.addTestChildNamed("node 2"); - node2.addTestChildNamed("node 2.1"); - node2.addTestChildNamed("node 2.2"); - r.addTestChildNamed("node 3"); - r.addTestChildNamed("node 4"); - - // mark the entire tree clean - r.markEntireBranchClean(); - return r; - } - - @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - public void testTestWorkbenchModel() { - // make sure our test class works OK... - assertNull(this.root.testChildNamed("")); - assertNotNull(this.root.testChildNamed("node 1")); - assertTrue(this.root.testChildNamed("node 1").isClean()); - assertTrue(this.root.testChildNamed("node 1").isCleanBranch()); - assertNotNull(this.root.testChildNamed("node 2")); - assertTrue(this.root.testChildNamed("node 2").isClean()); - assertTrue(this.root.testChildNamed("node 2").isCleanBranch()); - assertNull(this.root.testChildNamed("node 2.1")); - - assertNull(this.root.testDescendantNamed("")); - assertNotNull(this.root.testDescendantNamed("node 1")); - assertNotNull(this.root.testDescendantNamed("node 2")); - assertNotNull(this.root.testDescendantNamed("node 2.1")); - assertTrue(this.root.testDescendantNamed("node 2.1").isClean()); - assertTrue(this.root.testDescendantNamed("node 2.1").isCleanBranch()); - assertNotNull(this.root.testDescendantNamed("node 1.1.3")); - assertTrue(this.root.testDescendantNamed("node 1.1.3").isClean()); - assertTrue(this.root.testDescendantNamed("node 1.1.3").isCleanBranch()); - } - - public void testParentAndChildren() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - assertEquals("node 1.1.3", node.getName()); - assertEquals(0, CollectionTools.size(node.children())); - - node = (TestWorkbenchModel) node.getParent(); - assertEquals("node 1.1", node.getName()); - assertEquals(3, CollectionTools.size(node.children())); - - node = (TestWorkbenchModel) node.getParent(); - assertEquals("node 1", node.getName()); - assertEquals(2, CollectionTools.size(node.children())); - - node = (TestWorkbenchModel) node.getParent(); - assertEquals("root", node.getName()); - assertEquals(4, CollectionTools.size(node.children())); - - node = (TestWorkbenchModel) node.getParent(); - assertNull(node); - } - - public void testDirty() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setSize(42); - assertTrue(node.isDirty()); - - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - assertTrue(parent.isClean()); - assertTrue(this.root.isClean()); - } - - public void testDirtyUnchangedAttribute() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setSize(42); - assertTrue(node.isDirty()); - - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - assertTrue(parent.isClean()); - assertTrue(this.root.isClean()); - - this.root.markEntireBranchClean(); - // set size to same number - should stay clean - node.setSize(42); - assertTrue(node.isClean()); - assertTrue(parent.isClean()); - assertTrue(this.root.isClean()); - } - - public void testDirtyBranch() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setSize(42); - assertTrue(node.isDirtyBranch()); - - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - assertTrue(parent.isDirtyBranch()); - assertTrue(this.root.isDirtyBranch()); - - parent.setSize(77); - assertTrue(parent.isDirty()); - assertTrue(parent.isDirtyBranch()); - - node.markEntireBranchClean(); - assertTrue(parent.isDirty()); - assertTrue(parent.isDirtyBranch()); - } - - public void testDirtyBranchCleanChildDirtyParent() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setSize(42); - - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - parent.setSize(77); - assertTrue(parent.isDirty()); - assertTrue(parent.isDirtyBranch()); - - // now, clean the child, but leave the parent dirty - node.markEntireBranchClean(); - assertTrue(parent.isDirty()); - assertTrue(parent.isDirtyBranch()); - } - - public void testDirtyBranchCleanChildDirtyChild() { - TestWorkbenchModel node1 = this.root.testDescendantNamed("node 1.1.1"); - node1.setSize(41); - TestWorkbenchModel node2 = this.root.testDescendantNamed("node 1.1.2"); - node2.setSize(42); - - TestWorkbenchModel parent = (TestWorkbenchModel) node1.getParent(); - assertTrue(parent.isClean()); - assertTrue(parent.isDirtyBranch()); - - // now, clean the first child, but leave the second child dirty - node1.markEntireBranchClean(); - assertTrue(parent.isClean()); - assertTrue(parent.isDirtyBranch()); - } - - public void testDirtyBranchForced() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - - assertTrue(node.isClean()); - assertTrue(node.isCleanBranch()); - assertTrue(parent.isClean()); - assertTrue(parent.isCleanBranch()); - assertTrue(this.root.isClean()); - assertTrue(this.root.isCleanBranch()); - - this.root.markEntireBranchDirty(); - - assertTrue(node.isDirty()); - assertTrue(node.isDirtyBranch()); - assertTrue(parent.isDirty()); - assertTrue(parent.isDirtyBranch()); - assertTrue(this.root.isDirty()); - assertTrue(this.root.isDirtyBranch()); - } - - public void testDirtyTransientAttribute() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setName("BOGUS"); - assertTrue(node.isDirty()); - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - assertTrue(parent.isClean()); - assertTrue(parent.isDirtyBranch()); - assertTrue(this.root.isClean()); - assertTrue(this.root.isDirtyBranch()); - - this.root.markEntireBranchClean(); - - this.root.validateBranch(); - - assertTrue(this.root.problemsSize() == 0); - assertTrue(node.branchProblems().hasNext()); - assertTrue(parent.problemsSize() == 0); - assertTrue(parent.branchProblems().hasNext()); - assertTrue(node.problemsSize() > 0); - - // since problems are transient, everything should still be clean - assertTrue(node.isClean()); - assertTrue(node.isCleanBranch()); - assertTrue(parent.isClean()); - assertTrue(parent.isCleanBranch()); - assertTrue(this.root.isClean()); - assertTrue(this.root.isCleanBranch()); - } - - public void testProblems() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setName("BOGUS"); - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - - this.root.validateBranch(); - - assertEquals(0, this.root.problemsSize()); - assertTrue(node.branchProblems().hasNext()); - assertEquals(0, parent.problemsSize()); - assertTrue(parent.branchProblems().hasNext()); - assertEquals(1, node.problemsSize()); - Problem problem1 = node.problems().next(); - - // now create another problem that should remove the old problem - node.setName("STILL BOGUS"); - this.root.validateBranch(); - - assertEquals(0, this.root.problemsSize()); - assertTrue(node.branchProblems().hasNext()); - assertEquals(0, parent.problemsSize()); - assertTrue(parent.branchProblems().hasNext()); - assertEquals(1, node.problemsSize()); - Problem problem2 = node.problems().next(); - assertFalse(problem1 == problem2); - problem1 = problem2; - - // now create another problem that should replace the old problem - node.setName("STILL BOGUS"); - this.root.validateBranch(); - - assertEquals(0, this.root.problemsSize()); - assertTrue(node.branchProblems().hasNext()); - assertEquals(0, parent.problemsSize()); - assertTrue(parent.branchProblems().hasNext()); - assertEquals(1, node.problemsSize()); - problem2 = node.problems().next(); - // the same problem should be there - assertTrue(problem1.equals(problem2)); - } - - public void testBranchProblems() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setName("BOGUS"); - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - parent.setName("BOGUS TOO"); - this.root.setName("BOGUS TOO TOO"); - - this.root.validateBranch(); - - assertEquals(1, this.root.problemsSize()); - assertEquals(3, this.root.branchProblemsSize()); - assertEquals(1, parent.problemsSize()); - assertEquals(2, parent.branchProblemsSize()); - assertEquals(1, node.problemsSize()); - assertEquals(1, node.branchProblemsSize()); - - node.setName("okie-dokie"); - - this.root.validateBranch(); - - assertEquals(1, this.root.problemsSize()); - assertEquals(2, this.root.branchProblemsSize()); - assertEquals(1, parent.problemsSize()); - assertEquals(1, parent.branchProblemsSize()); - assertEquals(0, node.problemsSize()); - assertEquals(0, node.branchProblemsSize()); - } - - public void testClearAllBranchProblems() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setName("BOGUS"); - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - parent.setName("BOGUS TOO"); - this.root.setName("BOGUS TOO TOO"); - - this.root.validateBranch(); - - assertEquals(1, this.root.problemsSize()); - assertEquals(3, this.root.branchProblemsSize()); - assertEquals(1, parent.problemsSize()); - assertEquals(2, parent.branchProblemsSize()); - assertEquals(1, node.problemsSize()); - assertEquals(1, node.branchProblemsSize()); - - parent.clearAllBranchProblems(); - - assertEquals(1, this.root.problemsSize()); - assertEquals(1, this.root.branchProblemsSize()); - assertEquals(0, parent.problemsSize()); - assertEquals(0, parent.branchProblemsSize()); - assertEquals(0, node.problemsSize()); - assertEquals(0, CollectionTools.size(node.branchProblems())); - } - - public void testRemovedBranchProblems() { - TestWorkbenchModel node = this.root.testDescendantNamed("node 1.1.3"); - node.setName("BOGUS"); - TestWorkbenchModel parent = (TestWorkbenchModel) node.getParent(); - parent.setName("BOGUS TOO"); - this.root.setName("BOGUS TOO TOO"); - - this.root.validateBranch(); - - assertEquals(1, this.root.problemsSize()); - assertEquals(3, CollectionTools.size(this.root.branchProblems())); - assertEquals(1, parent.problemsSize()); - assertEquals(2, parent.branchProblemsSize()); - assertEquals(1, node.problemsSize()); - assertEquals(1, CollectionTools.size(node.branchProblems())); - - // completely remove a node that has problems - - // the entire tree should recalculate its "branch" problems - parent.removeTestChild(node); - - this.root.validateBranch(); - - assertEquals(1, this.root.problemsSize()); - assertEquals(2, CollectionTools.size(this.root.branchProblems())); - assertEquals(1, parent.problemsSize()); - assertEquals(1, parent.branchProblemsSize()); - } - - - // ********** inner classes ********** - - public class TestWorkbenchModel extends AbstractNode { - private String name; - public static final String NAME_PROPERTY = "name"; - private int size; - public static final String SIZE_PROPERTY = "size"; - private Collection<TestWorkbenchModel> testChildren; - public static final String TEST_CHILDREN_COLLECTION = "children"; - - // ********** construction/initialization ********** - public TestWorkbenchModel(TestWorkbenchModel parent, String name) { - super(parent); - if (name == null) { - throw new NullPointerException(); - } - this.name = name; - } - @Override - protected void initialize() { - super.initialize(); - this.size = 0; - this.testChildren = new HashBag<TestWorkbenchModel>(); - } - - @Override - protected void checkParent(Node parent) { - // do nothing - } - - - // ********** accessors ********** - public String getName() { - return this.name; - } - public void setName(String name) { - Object old = this.name; - this.name = name; - this.firePropertyChanged(NAME_PROPERTY, old, name); - } - - public int getSize() { - return this.size; - } - public void setSize(int size) { - int old = this.size; - this.size = size; - this.firePropertyChanged(SIZE_PROPERTY, old, size); - } - - public Iterator<TestWorkbenchModel> testChildren() { - return new CloneIterator<TestWorkbenchModel>(this.testChildren) { - @Override - protected void remove(TestWorkbenchModel current) { - TestWorkbenchModel.this.removeTestChild(current); - } - }; - } - public int testChildrenSize() { - return this.testChildren.size(); - } - private TestWorkbenchModel addTestChild(TestWorkbenchModel testChild) { - this.addItemToCollection(testChild, this.testChildren, TEST_CHILDREN_COLLECTION); - return testChild; - } - public TestWorkbenchModel addTestChildNamed(String childName) { - if (this.testChildNamed(childName) != null) { - throw new IllegalArgumentException(childName); - } - return this.addTestChild(new TestWorkbenchModel(this, childName)); - } - public void removeTestChild(TestWorkbenchModel testChild) { - this.removeItemFromCollection(testChild, this.testChildren, TEST_CHILDREN_COLLECTION); - } - - // ********** queries ********** - public String displayString() { - return this.name; - } - public TestWorkbenchModel testChildNamed(String childName) { - for (TestWorkbenchModel testChild : this.testChildren) { - if (testChild.getName().equals(childName)) { - return testChild; - } - } - return null; - } - public TestWorkbenchModel testDescendantNamed(String descendantName) { - for (TestWorkbenchModel testDescendant : this.testChildren) { - if (testDescendant.getName().equals(descendantName)) { - return testDescendant; - } - // recurse... - testDescendant = testDescendant.testDescendantNamed(descendantName); - if (testDescendant != null) { - return testDescendant; - } - } - return null; - } - - // ********** behavior ********** - @Override - protected void addChildrenTo(List<Node> children) { - super.addChildrenTo(children); - children.addAll(this.testChildren); - } - @Override - protected void addProblemsTo(List<Problem> currentProblems) { - super.addProblemsTo(currentProblems); - // names must be all lowercase... - for (int i = this.name.length(); i-- > 0; ) { - char c = this.name.charAt(i); - if (Character.isLetter(c) && ! Character.isLowerCase(c)) { - currentProblems.add(this.buildProblem("NAME_MUST_BE_LOWERCASE", 3 ,this.name)); - return; - } - } - } - @Override - public void toString(StringBuilder sb) { - sb.append(this.name); - } - } - - - private class RootTestWorkbenchModel extends TestWorkbenchModel { - public RootTestWorkbenchModel(String name) { - super(null, name); - } - @Override - public Validator getValidator() { - return Node.NULL_VALIDATOR; - } - } - -} - diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/node/JptUtilityNodeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/node/JptUtilityNodeTests.java deleted file mode 100644 index 16f6dce93d..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/node/JptUtilityNodeTests.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.node; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class JptUtilityNodeTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilityNodeTests.class.getPackage().getName()); - - suite.addTestSuite(AbstractNodeTests.class); - - return suite; - } - - private JptUtilityNodeTests() { - super(); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/JptUtilitySynchronizersTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/JptUtilitySynchronizersTests.java deleted file mode 100644 index da7ad6f1f1..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/JptUtilitySynchronizersTests.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.synchronizers; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * decentralize test creation code - */ -public class JptUtilitySynchronizersTests { - - public static Test suite() { - TestSuite suite = new TestSuite(JptUtilitySynchronizersTests.class.getPackage().getName()); - - suite.addTestSuite(SynchronizerTests.class); - suite.addTestSuite(SynchronousSynchronizerTests.class); - - return suite; - } - - private JptUtilitySynchronizersTests() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/SynchronizerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/SynchronizerTests.java deleted file mode 100644 index 8f7c67bb69..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/SynchronizerTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.synchronizers; - -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.synchronizers.Synchronizer; - -public class SynchronizerTests extends TestCase { - - public SynchronizerTests(String name) { - super(name); - } - - public void testNullSynchronizerStart() { - Synchronizer synchronizer = Synchronizer.Null.instance(); - synchronizer.start(); // just make sure it doesn't blow up? - } - - public void testNullSynchronizerSynchronize() { - Synchronizer synchronizer = Synchronizer.Null.instance(); - synchronizer.synchronize(); // just make sure it doesn't blow up? - } - - public void testNullSynchronizerStop() { - Synchronizer synchronizer = Synchronizer.Null.instance(); - synchronizer.stop(); // just make sure it doesn't blow up? - } - - public void testNullSynchronizerToString() { - Synchronizer synchronizer = Synchronizer.Null.instance(); - assertNotNull(synchronizer.toString()); - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/SynchronousSynchronizerTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/SynchronousSynchronizerTests.java deleted file mode 100644 index 4bec15e68c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/synchronizers/SynchronousSynchronizerTests.java +++ /dev/null @@ -1,755 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0, which accompanies this distribution - * and is available at http://www.eclipse.org/legal/epl-v10.html. - * - * Contributors: - * Oracle - initial API and implementation - ******************************************************************************/ -package org.eclipse.jpt.common.utility.tests.internal.synchronizers; - -import org.eclipse.jpt.common.utility.command.Command; -import org.eclipse.jpt.common.utility.internal.CompositeException; -import org.eclipse.jpt.common.utility.internal.SynchronizedBoolean; -import org.eclipse.jpt.common.utility.internal.synchronizers.SynchronousSynchronizer; -import org.eclipse.jpt.common.utility.synchronizers.Synchronizer; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class SynchronousSynchronizerTests - extends MultiThreadedTestCase -{ - PrimaryModel1 primaryModel1; - SecondaryModel1 secondaryModel1; - Command command1; - Synchronizer synchronizer1; - - PrimaryModel2 primaryModel2; - SecondaryModel2 secondaryModel2; - Command command2; - Synchronizer synchronizer2; - - public SynchronousSynchronizerTests(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.primaryModel1 = new PrimaryModel1(); - this.secondaryModel1 = new SecondaryModel1(this.primaryModel1); - this.command1 = new SynchronizeSecondaryModelCommand1(this.secondaryModel1); - this.synchronizer1 = new SynchronousSynchronizer(this.command1); - this.primaryModel1.setSynchronizer(this.synchronizer1); - - this.primaryModel2 = new PrimaryModel2(); - this.secondaryModel2 = new SecondaryModel2(this.primaryModel2); - this.command2 = new SynchronizeSecondaryModelCommand2(this.primaryModel2, this.secondaryModel2); - this.synchronizer2 = new SynchronousSynchronizer(this.command2); - this.primaryModel2.setSynchronizer(this.synchronizer2); - } - - public void testInitialization() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - } - - public void testToString() { - assertNotNull(this.synchronizer1.toString()); - } - - public void testChange() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.setCount(7); - assertEquals(14, this.secondaryModel1.getDoubleCount()); - } - - public void testStart() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.setSynchronizer(Synchronizer.Null.instance()); - this.primaryModel1.setCount(7); - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.setSynchronizer(this.synchronizer1); - assertEquals(14, this.secondaryModel1.getDoubleCount()); - } - - public void testStop() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.dispose(); - this.primaryModel1.setCount(7); - assertEquals(4, this.secondaryModel1.getDoubleCount()); - } - - public void testDoubleStart() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - boolean exCaught = false; - try { - this.primaryModel1.startSynchronizer(); - fail(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - this.primaryModel1.setCount(7); - assertEquals(14, this.secondaryModel1.getDoubleCount()); - } - - public void testDoubleStop() { - assertEquals(4, this.secondaryModel1.getDoubleCount()); - this.primaryModel1.dispose(); - boolean exCaught = false; - try { - this.primaryModel1.dispose(); - fail(); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - this.primaryModel1.setCount(7); - assertEquals(4, this.secondaryModel1.getDoubleCount()); - } - - public void testRecursiveChange() { - assertEquals(4, this.secondaryModel2.getDoubleCount()); - this.primaryModel2.setCount(7); - assertEquals(10, this.primaryModel2.getCountPlus3()); - assertEquals(14, this.secondaryModel2.getDoubleCount()); - assertEquals(20, this.secondaryModel2.getDoubleCountPlus3()); - } - - /** - * Call #stop() from another thread. - * Verify that no further synchronizations occur. - * Verify the call to #stop() does not return until the pending - * synchronization is complete (must set {@link #DEBUG} to true and - * look at the console). - * - * ticks: - * 0 - start "sync" thread (which will sleep for 1 tick); - * start "stop" thread (which will sleep for 2 ticks) - * 1 - "sync" thread wakes up and calls PrimaryModel1.setCount(int) - * which triggers call to Synchronizer.synchronize() to begin - * synchronization of SecondaryModel (which will run for 2 ticks; - * i.e. it will finish on tick 3) - * 2 - "stop" thread wakes up and calls Synchronizer.stop() and should - * wait until synchronization is complete - * 3 - synchronization completes first execution and should stop; - * "stop" thread should run to completion once the synchronization has stopped - */ - public void testCallStopFromAnotherThread() throws Exception { - log("=====" + this.getName() + "====="); - PrimaryModel2 primaryModel3 = new PrimaryModel2(); - // a synchronize will occur here: - SecondaryModel3 secondaryModel3 = new SecondaryModel3(primaryModel3); - Command command3 = new SynchronizeSecondaryModelCommand2(primaryModel3, secondaryModel3); - Synchronizer synchronizer3 = new SynchronousSynchronizer(command3); - // another synchronize will occur here: - primaryModel3.setSynchronizer(synchronizer3); - secondaryModel3.setTicks(2); - - assertEquals(2, primaryModel3.getCount()); - assertEquals(5, primaryModel3.getCountPlus3()); - assertEquals(4, secondaryModel3.getDoubleCount()); - assertEquals(10, secondaryModel3.getDoubleCountPlus3()); - - Thread syncThread = this.buildTriggerSynchronizeThread(primaryModel3, 1); - Thread stopThread = this.buildStopThread(synchronizer3, 2); - - log("ALL threads start"); - stopThread.start(); - syncThread.start(); - - stopThread.join(); - syncThread.join(); - - // 'doubleCount' is synchronized; but the synchronization is stopped - // while that is happening (by the 'stopThread'), so 'doubleCountPlus3' - // does not get synchronized - assertEquals(7, primaryModel3.getCount()); - assertEquals(10, primaryModel3.getCountPlus3()); - assertEquals(14, secondaryModel3.getDoubleCount()); - - // this does not get updated because it would've been updated by the - // recursive call to #synchronize(), but by that time #stop() had been called - assertEquals(10, secondaryModel3.getDoubleCountPlus3()); - } - - private Thread buildTriggerSynchronizeThread(PrimaryModel2 primaryModel, long ticks) { - return this.buildThread(this.buildTriggerSynchronizeRunnable(primaryModel, ticks), "trigger sync"); - } - - private Runnable buildTriggerSynchronizeRunnable(final PrimaryModel2 primaryModel, final long ticks) { - return new Runnable() { - public void run() { - TestTools.sleep(ticks * TICK); - primaryModel.setCount(7); - } - }; - } - - private Thread buildStopThread(Synchronizer synchronizer, long ticks) { - return this.buildThread(this.buildStopRunnable(synchronizer, ticks), "stop"); - } - - private Runnable buildStopRunnable(final Synchronizer synchronizer, final long ticks) { - return new Runnable() { - public void run() { - TestTools.sleep(ticks * TICK); - log("STOP thread Synchronizer.stop()"); - synchronizer.stop(); - log("STOP thread stop"); - } - }; - } - - /** - * Code cloned from {@link #testStopCalledFromAnotherThread()}. - * - * Interrupt the "stop" thread while it is waiting for the "synch" thread to finish. - * Verify that no further synchronizations occur. - * Verify the call to #stop() returns *before* - * synchronization is complete (must set {@link #DEBUG} to true and - * look at the console). - * - * ticks: - * 0 - start "sync" thread (which will sleep for 1 tick); - * start "stop" thread (which will sleep for 2 ticks); - * start "interrupt" thread (which will sleep for 3 ticks) - * 1 - "sync" thread wakes up and calls PrimaryModel1.setCount(int) - * which triggers call to Synchronizer.synchronize() to begin - * synchronization of SecondaryModel (which will run for 3 ticks; - * i.e. it will finish on tick 4) - * 2 - "stop" thread wakes up and calls Synchronizer.stop() and should - * wait until it is interrupted - * 3 - "interrupt" thread wakes up and interrupts "stop" thread; - * both will run to completion at that point - * 4 - synchronization completes first execution and should stop since the - * "stop" thread, before it was interrupted, told the "synch" thread to stop - */ - public void testInterruptStopThread() throws Exception { - log("=====" + this.getName() + "====="); - PrimaryModel2 primaryModel3 = new PrimaryModel2(); - // a synchronize will occur here: - SecondaryModel3 secondaryModel3 = new SecondaryModel3(primaryModel3); - Command command3 = new SynchronizeSecondaryModelCommand2(primaryModel3, secondaryModel3); - Synchronizer synchronizer3 = new SynchronousSynchronizer(command3); - // another synchronize will occur here: - primaryModel3.setSynchronizer(synchronizer3); - secondaryModel3.setTicks(3); - - assertEquals(2, primaryModel3.getCount()); - assertEquals(5, primaryModel3.getCountPlus3()); - assertEquals(4, secondaryModel3.getDoubleCount()); - assertEquals(10, secondaryModel3.getDoubleCountPlus3()); - - Thread syncThread = this.buildTriggerSynchronizeThread(primaryModel3, 1); - Thread stopThread = this.buildStopThread(synchronizer3, 2); - Thread interruptThread = this.buildInterruptThread(stopThread, 3); - - log("ALL threads start"); - stopThread.start(); - syncThread.start(); - interruptThread.start(); - - stopThread.join(); - syncThread.join(); - interruptThread.join(); - - // 'doubleCount' is synchronized; but the synchronization is stopped - // while that is happening (by the 'stopThread'), so 'doubleCountPlus3' - // does not get synchronized - assertEquals(7, primaryModel3.getCount()); - assertEquals(10, primaryModel3.getCountPlus3()); - assertEquals(14, secondaryModel3.getDoubleCount()); - - // this does not get updated because it would've been updated by the - // recursive call to #synchronize(), but by that time #stop() had been called - assertEquals(10, secondaryModel3.getDoubleCountPlus3()); - } - - /** - * Code cloned from {@link #testStopCalledFromAnotherThread()}. - * - * Interrupt the "sync" thread while it is synchronizing, cutting short the synchronization. - * Verify that no further synchronizations occur. - * Verify the call to #stop() does not return until the pending - * synchronization is stops after it is interrupted (must set {@link #DEBUG} to true and - * look at the console). - * - * ticks: - * 0 - start "sync" thread (which will sleep for 1 tick) - * start "stop" thread (which will sleep for 2 ticks) - * start "interrupt" thread (which will sleep for 3 ticks) - * 1 - "sync" thread wakes up and calls PrimaryModel1.setCount(int) - * which triggers call to Synchronizer.synchronize() to begin - * synchronization of SecondaryModel (which will run for 4 ticks; - * i.e. it will finish on tick 5) - * 2 - "stop" thread wakes up and calls Synchronizer.stop() and should - * wait until the synchronization is interrupted - * 3 - "interrupt" thread wakes up and interrupts "sync" thread; - * the "interrupt" thread runs to completion, while the "sync" thread keeps - * going for another tick before it stops in "mid-synchronize" - * 4 - the "sync" thread acknowledges the interrupt and stops in - * "mid-synchronize"; it will stop since the "stop" thread told it to at tick 2; - * the "sync" and "stop" threads run to completion - */ - public void testInterruptSyncThread() throws Exception { - log("=====" + this.getName() + "====="); - PrimaryModel2 primaryModel3 = new PrimaryModel2(); - // a synchronize will occur here: - SecondaryModel3 secondaryModel3 = new SecondaryModel3(primaryModel3); - Command command3 = new SynchronizeSecondaryModelCommand2(primaryModel3, secondaryModel3); - Synchronizer synchronizer3 = new SynchronousSynchronizer(command3); - // another synchronize will occur here: - primaryModel3.setSynchronizer(synchronizer3); - secondaryModel3.setTicks(4); - - assertEquals(2, primaryModel3.getCount()); - assertEquals(5, primaryModel3.getCountPlus3()); - assertEquals(4, secondaryModel3.getDoubleCount()); - assertEquals(10, secondaryModel3.getDoubleCountPlus3()); - - Thread syncThread = this.buildTriggerSynchronizeThread(primaryModel3, 1); - Thread stopThread = this.buildStopThread(synchronizer3, 2); - Thread interruptThread = this.buildInterruptThread(syncThread, 3); - - log("ALL threads start"); - stopThread.start(); - syncThread.start(); - interruptThread.start(); - - stopThread.join(); - syncThread.join(); - interruptThread.join(); - - assertEquals(7, primaryModel3.getCount()); - assertEquals(10, primaryModel3.getCountPlus3()); - - // none of the secondary model is synchronized because the synchronize() - // method was interrupted before any synchronization had occurred - assertEquals(4, secondaryModel3.getDoubleCount()); - assertEquals(10, secondaryModel3.getDoubleCountPlus3()); - } - - private Thread buildInterruptThread(Thread thread, long ticks) { - return this.buildThread(this.buildInterruptRunnable(thread, ticks), "interrupt"); - } - - private Runnable buildInterruptRunnable(final Thread thread, final long ticks) { - return new Runnable() { - public void run() { - TestTools.sleep(ticks * TICK); - log("INTERRUPT thread Thread.interrupt()"); - thread.interrupt(); - } - }; - } - - /** - * Call #stop() during a long-running "synchronize"; then call #start() - * while the #stop() is waiting for the "synchronize" to complete. - * - * ticks: - * 0 - start "sync" thread (which will sleep for 1 tick) - * start "stop" thread (which will sleep for 2 ticks) - * start "start" thread (which will sleep for 3 ticks) - * 1 - "sync" thread wakes up and calls Synchronizer.synchronize() to begin - * synchronization (which will run for 3 ticks; i.e. it will finish on tick 4) - * 2 - "stop" thread wakes up and calls Synchronizer.stop() and should - * wait until the synchronization is finished (i.e. tick 4) - * 3 - "start" thread wakes up and calls Synchronizer.start() - * which will throw an exception - * 4 - the "sync" thread finishes execution; - * it will stop since the "stop" thread told it to at tick 2; - * the "sync" and "stop" threads run to completion - */ - public void testCallStartDuringStop() throws Exception { - log("=====" + this.getName() + "====="); - DelayCommand command = this.buildDelayCommand(3); - Synchronizer synchronizer = new SynchronousSynchronizer(command); - synchronizer.start(); - - Thread syncThread = this.buildSynchronizeThread(synchronizer, 1); - Thread stopThread = this.buildStopThread(synchronizer, 2); - SynchronizedBoolean exCaught = new SynchronizedBoolean(false); - Thread startThread = this.buildStartThread(synchronizer, 3, exCaught); - - log("ALL threads start"); - syncThread.start(); - stopThread.start(); - startThread.start(); - - syncThread.join(); - stopThread.join(); - startThread.join(); - - assertTrue(exCaught.getValue()); - assertEquals(2, command.count); - } - - private DelayCommand buildDelayCommand(int ticks) { - return new DelayCommand(ticks); - } - - class DelayCommand implements Command { - final long ticks; - boolean first = true; - int count = 0; - - DelayCommand(int ticks) { - super(); - this.ticks = ticks; - } - - public void execute() { - this.count++; - // do nothing for the first call (from #start()) - if (this.first) { - log("EXEC first"); - this.first = false; - return; - } - log("EXEC start " + this.count); - TestTools.sleep(this.ticks * TICK); - log("EXEC stop " + this.count); - } - - } - - private Thread buildStartThread(Synchronizer synchronizer, long ticks, SynchronizedBoolean exCaught) { - return this.buildThread(this.buildStartRunnable(synchronizer, ticks, exCaught), "start"); - } - - private Runnable buildStartRunnable(final Synchronizer synchronizer, final long ticks, final SynchronizedBoolean exCaught) { - return new Runnable() { - public void run() { - TestTools.sleep(ticks * TICK); - log("START thread Synchronizer.start()"); - try { - synchronizer.start(); - } catch (IllegalStateException ex) { - exCaught.setTrue(); - log("START thread exception"); - } - log("START thread stop"); - } - }; - } - - private Thread buildSynchronizeThread(Synchronizer synchronizer, long ticks) { - return this.buildThread(this.buildSynchronizeRunnable(synchronizer, ticks), "synchronize"); - } - - private Runnable buildSynchronizeRunnable(final Synchronizer synchronizer, final long ticks) { - return new Runnable() { - public void run() { - TestTools.sleep(ticks * TICK); - log("SYNC thread Synchronizer.synchronize()"); - synchronizer.synchronize(); - log("SYNC thread stop"); - } - }; - } - - public void testException() throws Exception { - BogusCommand command = new BogusCommand(); - Synchronizer synchronizer = new SynchronousSynchronizer(command); - synchronizer.start(); - - try { - synchronizer.synchronize(); - } catch (NullPointerException ex) { - // ignore - } - - boolean exCaught = false; - try { - // we used to hang here, before we began handling exceptions - synchronizer.stop(); - fail(); - } catch (CompositeException ex) { - assertEquals(1, ex.getExceptions().length); - exCaught = true; - } - assertTrue(exCaught); - // start + synchronize - assertEquals(2, command.count); - } - - public class BogusCommand implements Command { - int count = 0; - public void execute() { - this.count++; - if (this.count > 1) { - throw new NullPointerException(); - } - } - } - - - // ********** synchronize commands ********** - public static class SynchronizeSecondaryModelCommand1 implements Command { - private final SecondaryModel1 secondaryModel; - - public SynchronizeSecondaryModelCommand1(SecondaryModel1 secondaryModel) { - super(); - this.secondaryModel = secondaryModel; - } - - public void execute() { - this.secondaryModel.synchronize(); - } - - } - - /** - * the primary model (subclass) has to synchronize with itself (superclass) - */ - public static class SynchronizeSecondaryModelCommand2 extends SynchronizeSecondaryModelCommand1 { - private final PrimaryModel2 primaryModel; - - public SynchronizeSecondaryModelCommand2(PrimaryModel2 primaryModel, SecondaryModel2 secondaryModel) { - super(secondaryModel); - this.primaryModel = primaryModel; - } - - @Override - public void execute() { - super.execute(); - this.primaryModel.synchronize(); - } - - } - - // ********** primary models ********** - /** - * this object will call the synchronizer whenever its count changes, - * allowing interested parties to synchronize with the change - */ - public static class PrimaryModel1 { - protected Synchronizer synchronizer; - protected int count = 2; - - public PrimaryModel1() { - super(); - this.setSynchronizer_(Synchronizer.Null.instance()); - } - - public int getCount() { - return this.count; - } - public void setCount(int count) { - if (count != this.count) { - this.count = count; - this.stateChanged(); - } - } - - protected void stateChanged() { - this.synchronizer.synchronize(); - } - - public void setSynchronizer(Synchronizer synchronizer) { - if (synchronizer == null) { - throw new NullPointerException(); - } - this.synchronizer.stop(); - this.setSynchronizer_(synchronizer); - } - - protected void setSynchronizer_(Synchronizer synchronizer) { - this.synchronizer = synchronizer; - this.synchronizer.start(); - } - - public void startSynchronizer() { - this.synchronizer.start(); // this should cause an exception - } - public void dispose() { - this.synchronizer.stop(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append('('); - this.toString(sb); - sb.append(')'); - return sb.toString(); - } - public void toString(StringBuilder sb) { - sb.append("count="); - sb.append(this.count); - } - - } - - /** - * This model synchronizes with itself, triggering a recursive synchronization - * with the change. Whenever the [inherited] 'count' changes, 'countPlus3' - * is updated appropriately and another synchronize is initiated if appropriate. - */ - public static class PrimaryModel2 extends PrimaryModel1 { - private int countPlus3 = 0; - - public PrimaryModel2() { - super(); - this.countPlus3 = this.count + 3; - } - - public int getCountPlus3() { - return this.countPlus3; - } - protected void setCountPlus3(int countPlus3) { - if (countPlus3 != this.countPlus3) { - this.countPlus3 = countPlus3; - this.stateChanged(); - } - } - - // synchronize with itself, so to speak - public void synchronize() { - this.setCountPlus3(this.count + 3); - } - - @Override - public void toString(StringBuilder sb) { - super.toString(sb); - sb.append(", countPlus3="); - sb.append(this.countPlus3); - } - - } - - // ********** secondary models ********** - /** - * This dependent object updates its 'doubleCount' whenever the - * PrimaryModel1's 'count' changes, via the 'synchronizer'. - */ - public static class SecondaryModel1 { - protected final PrimaryModel1 primaryModel; - protected int doubleCount = 0; - - public SecondaryModel1(PrimaryModel1 primaryModel) { - super(); - this.primaryModel = primaryModel; - this.synchronize(); - } - - public void synchronize() { - this.doubleCount = this.primaryModel.getCount() * 2; - } - - public int getDoubleCount() { - return this.doubleCount; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(this.getClass().getSimpleName()); - sb.append('('); - this.toString(sb); - sb.append(')'); - return sb.toString(); - } - public void toString(StringBuilder sb) { - sb.append("doubleCount="); - sb.append(this.doubleCount); - } - - } - - public static class SecondaryModel2 extends SecondaryModel1 { - private int doubleCountPlus3 = 0; - - public SecondaryModel2(PrimaryModel2 extendedPrimaryModel) { - super(extendedPrimaryModel); - } - - protected PrimaryModel2 getExtendedPrimaryModel() { - return (PrimaryModel2) this.primaryModel; - } - - @Override - public void synchronize() { - super.synchronize(); - int temp = this.getExtendedPrimaryModel().getCountPlus3() * 2; - if (this.doubleCountPlus3 != temp) { - this.doubleCountPlus3 = temp; - } - } - - public int getDoubleCountPlus3() { - return this.doubleCountPlus3; - } - - @Override - public void toString(StringBuilder sb) { - super.toString(sb); - sb.append(", doubleCountPlus3="); - sb.append(this.doubleCountPlus3); - } - - } - - /** - * Allow the time required to synchronize to be specified. - * A (non-delayed) synchronize will execute before we have a chance to - * change the tick count. (It is called in the SecondaryModel1 constructor.) - */ - public static class SecondaryModel3 extends SecondaryModel2 { - private long delay = 0; - public SecondaryModel3(PrimaryModel2 primaryModel) { - super(primaryModel); - } - - public void setTicks(long ticks) { - this.delay = ticks * TICK; - } - - @Override - public void synchronize() { - // don't log anything until 'ticks' is set - if (this.delay == 0) { - super.synchronize(); - } else { - log("SYNC thread start - sync duration will be: " + (this.delay / TICK) + " ticks"); - try { - Thread.sleep(this.delay); - } catch (InterruptedException ex) { - log("SYNC thread interrupted"); - TestTools.sleep(TICK); - return; // stop synchronize (i.e. don't call super.synchronize()) - } - super.synchronize(); - log("SYNC thread stop"); - } - } - - } - - public void testDEBUG() { - assertFalse(DEBUG); - } - - public static final boolean DEBUG = false; - public static void log(String message) { - if (DEBUG) { - log_(message); - } - } - - private static void log_(String message) { - System.out.print(timestamp()); - System.out.print(' '); - System.out.print(message); - System.out.println(); - } - - public static String timestamp() { - return String.valueOf((System.currentTimeMillis() % 10000) / 1000f); - } -} |