From 1d62c97e1dada43ee9a58bbc48f540ee34e8a51d Mon Sep 17 00:00:00 2001 From: Brian Vosburgh Date: Wed, 23 Sep 2015 18:29:57 -0400 Subject: major rework of collections, stacks, queues, and deques --- .../internal/libval/LibraryValidatorTools.java | 4 +- .../java/binary/BinaryPackageFragment.java | 4 +- .../swt/listeners/SWTListenerWrapperDelegate.java | 7 +- .../ui/internal/widgets/NewNameDialogBuilder.java | 4 +- .../META-INF/MANIFEST.MF | 36 + .../jpt/common/utility/collection/Queue.java | 50 - .../jpt/common/utility/collection/Stack.java | 50 - .../eclipse/jpt/common/utility/deque/Deque.java | 34 + .../common/utility/deque/InputRestrictedDeque.java | 59 + .../utility/deque/OutputRestrictedDeque.java | 53 + .../jpt/common/utility/internal/ArrayTools.java | 38 +- .../jpt/common/utility/internal/NameTools.java | 8 +- .../eclipse/jpt/common/utility/internal/Range.java | 2 +- .../collection/AbstractRepeatingElementList.java | 15 +- .../utility/internal/collection/ArrayQueue.java | 204 ---- .../utility/internal/collection/ArrayStack.java | 203 ---- .../internal/collection/CollectionTools.java | 667 +++-------- .../utility/internal/collection/EmptyQueue.java | 62 - .../utility/internal/collection/EmptyStack.java | 62 - .../internal/collection/FixedSizeArrayQueue.java | 139 --- .../internal/collection/FixedSizeArrayStack.java | 148 --- .../utility/internal/collection/HashBag.java | 85 +- .../internal/collection/IdentityHashBag.java | 85 +- .../utility/internal/collection/LinkedQueue.java | 273 ----- .../utility/internal/collection/LinkedStack.java | 264 ---- .../utility/internal/collection/ListQueue.java | 77 -- .../utility/internal/collection/ListStack.java | 79 -- .../utility/internal/collection/ListTools.java | 153 +-- .../utility/internal/collection/MapTools.java | 172 +-- .../utility/internal/collection/NullList.java | 14 +- .../utility/internal/collection/PriorityQueue.java | 62 - .../utility/internal/collection/QueueTools.java | 403 ------- .../utility/internal/collection/StackQueue.java | 58 - .../utility/internal/collection/StackTools.java | 374 ------ .../internal/collection/SynchronizedBag.java | 16 +- .../internal/collection/SynchronizedQueue.java | 494 -------- .../internal/collection/SynchronizedStack.java | 494 -------- .../AbstractAsynchronousCommandContext.java | 7 +- .../command/AbstractQueueingCommandContext.java | 4 +- .../AbstractSingleUseQueueingCommandContext.java | 4 +- .../utility/internal/deque/AbstractArrayDeque.java | 203 ++++ .../internal/deque/AbstractPriorityDeque.java | 396 ++++++ .../common/utility/internal/deque/ArrayDeque.java | 85 ++ .../common/utility/internal/deque/DequeTools.java | 799 +++++++++++++ .../common/utility/internal/deque/EmptyDeque.java | 74 ++ .../internal/deque/FixedCapacityArrayDeque.java | 76 ++ .../internal/deque/FixedCapacityPriorityDeque.java | 69 ++ .../common/utility/internal/deque/LinkedDeque.java | 321 +++++ .../common/utility/internal/deque/ListDeque.java | 98 ++ .../utility/internal/deque/PriorityDeque.java | 87 ++ .../utility/internal/deque/ReverseDeque.java | 77 ++ .../utility/internal/deque/SynchronizedDeque.java | 984 +++++++++++++++ .../internal/enumeration/EnumerationTools.java | 18 +- .../utility/internal/iterable/ChainIterable.java | 4 +- .../internal/iterable/CompositeIterable.java | 4 +- .../internal/iterable/CompositeListIterable.java | 4 +- .../internal/iterable/FilteringIterable.java | 4 +- .../utility/internal/iterable/GraphIterable.java | 4 +- .../utility/internal/iterable/IterableTools.java | 22 +- .../utility/internal/iterable/QueueIterable.java | 4 +- .../iterable/ReadOnlyCompositeListIterable.java | 4 +- .../utility/internal/iterable/StackIterable.java | 4 +- .../internal/iterable/TransformationIterable.java | 4 +- .../iterable/TransformationListIterable.java | 4 +- .../utility/internal/iterable/TreeIterable.java | 4 +- .../internal/iterator/CloneListIterator.java | 4 +- .../utility/internal/iterator/IteratorTools.java | 42 +- .../utility/internal/iterator/QueueIterator.java | 5 +- .../utility/internal/iterator/ReverseIterator.java | 6 +- .../utility/internal/iterator/StackIterator.java | 5 +- .../utility/internal/model/ChangeSupport.java | 20 +- .../awt/AWTPropertyChangeListenerWrapper.java | 7 +- .../awt/AWTStateChangeListenerWrapper.java | 7 +- .../model/value/AbstractTreeNodeValueModel.java | 4 +- .../value/AspectCollectionValueModelAdapter.java | 4 +- .../model/value/AspectListValueModelAdapter.java | 4 +- .../model/value/CompositeCollectionValueModel.java | 6 +- .../model/value/CompositeListValueModel.java | 6 +- .../model/value/ExtendedListValueModelWrapper.java | 4 +- .../value/ItemAspectListValueModelAdapter.java | 4 +- .../utility/internal/model/value/ListCurator.java | 4 +- .../model/value/SimpleCollectionValueModel.java | 8 +- .../internal/model/value/SimpleListValueModel.java | 6 +- .../model/value/SortedListValueModelAdapter.java | 4 +- .../prefs/PreferencesCollectionValueModel.java | 4 +- .../utility/internal/queue/AbstractArrayQueue.java | 172 +++ .../common/utility/internal/queue/ArrayQueue.java | 78 ++ .../common/utility/internal/queue/DequeQueue.java | 69 ++ .../common/utility/internal/queue/EmptyQueue.java | 62 + .../internal/queue/FixedCapacityArrayQueue.java | 65 + .../common/utility/internal/queue/LinkedQueue.java | 283 +++++ .../common/utility/internal/queue/ListQueue.java | 77 ++ .../utility/internal/queue/PriorityQueue.java | 249 ++++ .../common/utility/internal/queue/QueueTools.java | 534 +++++++++ .../common/utility/internal/queue/StackQueue.java | 58 + .../utility/internal/queue/SynchronizedQueue.java | 602 ++++++++++ .../common/utility/internal/stack/ArrayStack.java | 164 +++ .../common/utility/internal/stack/DequeStack.java | 77 ++ .../common/utility/internal/stack/EmptyStack.java | 62 + .../internal/stack/FixedCapacityArrayStack.java | 139 +++ .../common/utility/internal/stack/LinkedStack.java | 274 +++++ .../common/utility/internal/stack/ListStack.java | 80 ++ .../common/utility/internal/stack/StackTools.java | 447 +++++++ .../utility/internal/stack/SynchronizedStack.java | 604 ++++++++++ .../eclipse/jpt/common/utility/queue/Queue.java | 54 + .../eclipse/jpt/common/utility/stack/Stack.java | 52 + .../tests/internal/utility/jdt/ASTToolsTests.java | 14 +- .../internal/jface/TreeContentProviderUiTest.java | 4 +- .../tests/internal/JptCommonUtilityTests.java | 12 +- .../AbstractRepeatingElementListTests.java | 26 +- .../tests/internal/collection/ArrayQueueTests.java | 192 --- .../tests/internal/collection/ArrayStackTests.java | 77 -- .../tests/internal/collection/BagTests.java | 811 ++++++++++++- .../internal/collection/CollectionToolsTests.java | 247 ++-- .../tests/internal/collection/EmptyBagTests.java | 84 ++ .../collection/FixedSizeArrayQueueTests.java | 216 ---- .../collection/FixedSizeArrayStackTests.java | 141 --- .../tests/internal/collection/HashBagTests.java | 511 +------- .../internal/collection/IdentityHashBagTests.java | 320 ++++- .../internal/collection/IdentityHashSetTests.java | 44 +- .../JptCommonUtilityCollectionTests.java | 14 +- .../internal/collection/LinkedQueueTests.java | 108 -- .../internal/collection/LinkedStackTests.java | 108 -- .../tests/internal/collection/ListQueueTests.java | 32 - .../tests/internal/collection/ListStackTests.java | 32 - .../tests/internal/collection/ListToolsTests.java | 461 ++++++- .../tests/internal/collection/MapToolsTests.java | 217 ++-- .../tests/internal/collection/NullListTests.java | 247 ++++ .../tests/internal/collection/QueueTests.java | 149 --- .../tests/internal/collection/StackTests.java | 150 --- .../internal/collection/SynchronizedBagTests.java | 78 ++ .../collection/SynchronizedQueueTests.java | 260 ---- .../collection/SynchronizedStackTests.java | 260 ---- .../tests/internal/collection/TightMapTests.java | 124 +- .../internal/deque/AbstractPriorityDequeTests.java | 370 ++++++ .../tests/internal/deque/ArrayDequeTests.java | 366 ++++++ .../utility/tests/internal/deque/DequeTests.java | 290 +++++ .../tests/internal/deque/DequeToolsTests.java | 832 +++++++++++++ .../tests/internal/deque/EmptyDequeTests.java | 113 ++ .../deque/FixedCapacityArrayDequeTests.java | 341 ++++++ .../deque/FixedCapacityPriorityDequeTests.java | 108 ++ .../internal/deque/JptCommonUtilityDequeTests.java | 41 + .../tests/internal/deque/LinkedDequeTests.java | 263 ++++ .../tests/internal/deque/ListDequeTests.java | 32 + .../tests/internal/deque/PriorityDequeTests.java | 121 ++ .../tests/internal/deque/ReverseDequeTests.java | 282 +++++ .../internal/deque/SynchronizedDequeTests.java | 1255 ++++++++++++++++++++ .../utility/tests/internal/eol/CheckWinEOL.java | 4 +- .../utility/tests/internal/io/FileToolsTests.java | 12 +- .../internal/iterable/GraphIterableTests.java | 4 +- .../internal/iterable/QueueIterableTests.java | 7 +- .../internal/iterable/StackIterableTests.java | 7 +- .../internal/iterator/GraphIteratorTests.java | 4 +- .../ReadOnlyCompositeListIteratorTests.java | 6 +- .../model/value/CollectionAspectAdapterTests.java | 28 +- .../CollectionListValueModelAdapterTests.java | 8 +- .../CollectionPropertyValueModelAdapterTests.java | 4 +- .../value/CompositeCollectionValueModelTests.java | 34 +- .../value/ExtendedListValueModelWrapperTests.java | 8 +- .../model/value/ListAspectAdapterTests.java | 42 +- .../ListCollectionValueModelAdapterTests.java | 26 +- .../internal/model/value/ListCuratorTests.java | 36 +- .../PropertyCollectionValueModelAdapterTests.java | 12 +- .../value/PropertyListValueModelAdapterTests.java | 12 +- .../model/value/SetCollectionValueModelTests.java | 12 +- .../value/SimpleCollectionValueModelTests.java | 12 +- .../model/value/SimpleListValueModelTests.java | 12 +- .../value/SortedListValueModelAdapterTests.java | 12 +- .../value/SortedListValueModelWrapperTests.java | 12 +- .../value/StaticCollectionValueModelTests.java | 4 +- .../model/value/StaticListValueModelTests.java | 4 +- .../value/TransformationListValueModelTests.java | 12 +- .../model/value/swing/TableModelAdapterTests.java | 4 +- .../model/value/swing/TreeModelAdapterUITest.java | 4 +- .../tests/internal/queue/ArrayQueueTests.java | 250 ++++ .../tests/internal/queue/DequeQueueTests.java | 32 + .../tests/internal/queue/EmptyQueueTests.java | 76 ++ .../queue/FixedCapacityArrayQueueTests.java | 216 ++++ .../internal/queue/JptCommonUtilityQueueTests.java | 41 + .../tests/internal/queue/LinkedQueueTests.java | 230 ++++ .../tests/internal/queue/ListQueueTests.java | 32 + .../tests/internal/queue/PriorityQueueTests.java | 444 +++++++ .../utility/tests/internal/queue/QueueTests.java | 160 +++ .../tests/internal/queue/QueueToolsTests.java | 506 ++++++++ .../tests/internal/queue/StackQueueTests.java | 163 +++ .../internal/queue/SynchronizedQueueTests.java | 793 +++++++++++++ .../tests/internal/stack/ArrayStackTests.java | 128 ++ .../tests/internal/stack/DequeStackTests.java | 32 + .../tests/internal/stack/EmptyStackTests.java | 77 ++ .../stack/FixedCapacityArrayStackTests.java | 157 +++ .../internal/stack/JptCommonUtilityStackTests.java | 39 + .../tests/internal/stack/LinkedStackTests.java | 214 ++++ .../tests/internal/stack/ListStackTests.java | 32 + .../utility/tests/internal/stack/StackTests.java | 169 +++ .../tests/internal/stack/StackToolsTests.java | 465 ++++++++ .../internal/stack/SynchronizedStackTests.java | 792 ++++++++++++ .../jpt/jaxb/core/internal/AbstractJaxbNode.java | 4 +- .../jpt/jaxb/core/internal/SchemaLibraryImpl.java | 4 +- .../internal/context/AbstractJaxbContextRoot.java | 22 +- .../internal/context/ContextContainerTools.java | 11 +- .../java/GenericJavaAttributesContainer.java | 22 +- .../context/java/GenericJavaClassMapping.java | 10 +- .../internal/context/java/GenericJavaXmlNs.java | 4 +- .../internal/context/ELJaxbContextRootImpl.java | 4 +- .../internal/context/java/ELJavaXmlJoinNode.java | 4 +- .../properties/JaxbSchemasPropertiesPage.java | 4 +- .../internal/context/AbstractJpaContextModel.java | 4 +- .../internal/context/ContextContainerTools.java | 4 +- .../jpa/core/internal/context/MappingTools.java | 4 +- .../context/java/AbstractJavaPersistentType.java | 14 +- .../internal/context/java/AbstractJavaQuery.java | 6 +- .../internal/context/orm/AbstractOrmQuery.java | 6 +- .../context/orm/SpecifiedOrmPersistentType.java | 10 +- .../persistence/AbstractPersistenceUnit.java | 16 +- .../internal/facet/JpaFacetDataModelProvider.java | 6 +- .../internal/jpa1/context/GenericContextRoot.java | 4 +- .../context/java/GenericJavaTableGenerator.java | 6 +- .../jpa1/context/orm/GenericOrmTableGenerator.java | 6 +- .../jpa2/GenericMetamodelSynchronizer2_0.java | 4 +- .../GenericJavaNamedStoredProcedureQuery2_1.java | 6 +- .../GenericOrmNamedStoredProcedureQuery2_1.java | 6 +- .../eclipse/jpt/jpa/core/jpql/spi/JpaMapping.java | 4 +- .../persistence/EclipseLinkPersistenceUnit.java | 8 +- .../java/EclipseLinkJavaObjectTypeConverter.java | 6 +- .../orm/EclipseLinkOrmObjectTypeConverter.java | 6 +- .../persistence/EclipseLinkCustomization.java | 4 +- .../EclipseLinkPersistenceUnitProperties.java | 4 +- .../details/EclipseLinkConversionValueDialog.java | 4 +- .../EclipseLinkProfilerClassChooser.java | 4 +- .../options/EclipseLinkLoggerClassChooser.java | 4 +- ...clipseLinkPersistenceUnitOptionsEditorPage.java | 6 +- .../JpaJavaCompletionProposalComputer.java | 4 +- .../internal/JpaXmlCompletionProposalComputer.java | 4 +- .../details/BaseJoinColumnStateObject.java | 8 +- .../JoinColumnInJoiningStrategyStateObject.java | 4 +- .../jpa/ui/internal/details/TemporalTypeCombo.java | 4 +- .../properties/JpaProjectPropertiesPage.java | 6 +- .../jpa/ui/internal/wizards/gen/DatabaseGroup.java | 4 +- .../wizards/gen/TablesSelectorWizardPage.java | 6 +- .../context/java/JavaAttributeOverrideTests.java | 6 +- .../context/orm/OrmSecondaryTableTests.java | 4 +- .../Generic2_0JpaMetadataConversionTests.java | 6 +- .../EclipseLink2_2JpaMetadataConversionTests.java | 4 +- 243 files changed, 20273 insertions(+), 7447 deletions(-) delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Queue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Stack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/Deque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/InputRestrictedDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/OutputRestrictedDeque.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayStack.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyStack.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayStack.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedStack.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListStack.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/PriorityQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/QueueTools.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackTools.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedQueue.java delete mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractArrayDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractPriorityDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ArrayDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/DequeTools.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/EmptyDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityArrayDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityPriorityDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/LinkedDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ListDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/PriorityDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ReverseDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/SynchronizedDeque.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/AbstractArrayQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ArrayQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/DequeQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/EmptyQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/FixedCapacityArrayQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/LinkedQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ListQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/PriorityQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/QueueTools.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/StackQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/SynchronizedQueue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ArrayStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/DequeStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/EmptyStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/FixedCapacityArrayStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/LinkedStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ListStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/StackTools.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/SynchronizedStack.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/queue/Queue.java create mode 100644 common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/stack/Stack.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayQueueTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/EmptyBagTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayQueueTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayStackTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedQueueTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedStackTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListQueueTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/NullListTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/QueueTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/StackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedBagTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedQueueTests.java delete mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/AbstractPriorityDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ArrayDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeToolsTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/EmptyDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityArrayDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityPriorityDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/JptCommonUtilityDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/LinkedDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ListDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/PriorityDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ReverseDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/SynchronizedDequeTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ArrayQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/DequeQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/EmptyQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/FixedCapacityArrayQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/JptCommonUtilityQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/LinkedQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ListQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/PriorityQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueToolsTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/StackQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/SynchronizedQueueTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ArrayStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/DequeStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/EmptyStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/FixedCapacityArrayStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/JptCommonUtilityStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/LinkedStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ListStackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackToolsTests.java create mode 100644 common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/SynchronizedStackTests.java diff --git a/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/libval/LibraryValidatorTools.java b/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/libval/LibraryValidatorTools.java index b2af0c2b43..52ceef8163 100644 --- a/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/libval/LibraryValidatorTools.java +++ b/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/libval/LibraryValidatorTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -76,7 +76,7 @@ public class LibraryValidatorTools { private static IStatus validateClassesInLibraries(Iterable libraryPaths, Iterable classNames) { HashMap flags = new HashMap(); HashMap classFileNameToClassName = new HashMap(); - for (String className : CollectionTools.set(classNames)) { + for (String className : CollectionTools.hashSet(classNames)) { String classFileName = className.replace('.', '/') + ".class"; //$NON-NLS-1$ flags.put(classFileName, Boolean.FALSE); classFileNameToClassName.put(classFileName, className); diff --git a/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/resource/java/binary/BinaryPackageFragment.java b/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/resource/java/binary/BinaryPackageFragment.java index a8e9073dc9..fb346a6258 100644 --- a/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/resource/java/binary/BinaryPackageFragment.java +++ b/common/plugins/org.eclipse.jpt.common.core/src/org/eclipse/jpt/common/core/internal/resource/java/binary/BinaryPackageFragment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -57,7 +57,7 @@ final class BinaryPackageFragment private Collection buildClassFiles() { IJavaElement[] children = this.getJDTChildren(); ArrayList result = new ArrayList(children.length); - Collection annotationNames = CollectionTools.collection(this.getAnnotationProvider().getAnnotationNames()); + Collection annotationNames = CollectionTools.hashBag(this.getAnnotationProvider().getAnnotationNames()); for (IJavaElement child : children) { IClassFile jdtClassFile = (IClassFile) child; IType jdtType = jdtClassFile.getType(); diff --git a/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/swt/listeners/SWTListenerWrapperDelegate.java b/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/swt/listeners/SWTListenerWrapperDelegate.java index fb4eaef299..4a8aabda14 100644 --- a/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/swt/listeners/SWTListenerWrapperDelegate.java +++ b/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/swt/listeners/SWTListenerWrapperDelegate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -14,7 +14,8 @@ import org.eclipse.jpt.common.ui.internal.swt.widgets.DisplayTools; import org.eclipse.jpt.common.utility.exception.ExceptionHandler; import org.eclipse.jpt.common.utility.internal.ObjectTools; import org.eclipse.jpt.common.utility.internal.RunnableAdapter; -import org.eclipse.jpt.common.utility.internal.collection.SynchronizedQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.queue.SynchronizedQueue; import org.eclipse.swt.widgets.Display; /** @@ -36,7 +37,7 @@ final class SWTListenerWrapperDelegate { private final Display display; private final Runnable forwardEventsRunnable = new ForwardEventsRunnable(); private final ExceptionHandler exceptionHandler; - private final SynchronizedQueue events = new SynchronizedQueue(); + private final SynchronizedQueue events = QueueTools.synchronizedQueue(); SWTListenerWrapperDelegate(Wrapper wrapper, Display display, ExceptionHandler exceptionHandler) { diff --git a/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/widgets/NewNameDialogBuilder.java b/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/widgets/NewNameDialogBuilder.java index f06df8851d..47bb464a29 100644 --- a/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/widgets/NewNameDialogBuilder.java +++ b/common/plugins/org.eclipse.jpt.common.ui/src/org/eclipse/jpt/common/ui/internal/widgets/NewNameDialogBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -145,7 +145,7 @@ public final class NewNameDialogBuilder { * @param names The collection of names that can't be used */ public void setExistingNames(Iterator names) { - this.names = CollectionTools.collection(names); + this.names = CollectionTools.hashBag(names); } /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/META-INF/MANIFEST.MF b/common/plugins/org.eclipse.jpt.common.utility/META-INF/MANIFEST.MF index 4836dae3a4..3815dfdfb9 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/META-INF/MANIFEST.MF +++ b/common/plugins/org.eclipse.jpt.common.utility/META-INF/MANIFEST.MF @@ -14,6 +14,7 @@ Export-Package: org.eclipse.jpt.common.utility, org.eclipse.jpt.common.utility.closure, org.eclipse.jpt.common.utility.collection, org.eclipse.jpt.common.utility.command, + org.eclipse.jpt.common.utility.deque, org.eclipse.jpt.common.utility.exception, org.eclipse.jpt.common.utility.factory, org.eclipse.jpt.common.utility.internal; @@ -73,6 +74,17 @@ Export-Package: org.eclipse.jpt.common.utility, org.eclipse.jpt.jpa.gen, org.eclipse.jpt.jpa.annotate, org.eclipse.jpt.jpa.ui", + org.eclipse.jpt.common.utility.internal.deque; + x-friends:="org.eclipse.jpt.common.core, + org.eclipse.jpt.common.ui, + org.eclipse.jpt.jaxb.core, + org.eclipse.jpt.jaxb.ui, + org.eclipse.jpt.jpa.core, + org.eclipse.jpt.jpa.db, + org.eclipse.jpt.jpa.db.ui, + org.eclipse.jpt.jpa.gen, + org.eclipse.jpt.jpa.annotate, + org.eclipse.jpt.jpa.ui", org.eclipse.jpt.common.utility.internal.enumeration; x-friends:="org.eclipse.jpt.common.core, org.eclipse.jpt.common.ui, @@ -225,6 +237,17 @@ Export-Package: org.eclipse.jpt.common.utility, org.eclipse.jpt.jpa.gen, org.eclipse.jpt.jpa.annotate, org.eclipse.jpt.jpa.ui", + org.eclipse.jpt.common.utility.internal.queue; + x-friends:="org.eclipse.jpt.common.core, + org.eclipse.jpt.common.ui, + org.eclipse.jpt.jaxb.core, + org.eclipse.jpt.jaxb.ui, + org.eclipse.jpt.jpa.core, + org.eclipse.jpt.jpa.db, + org.eclipse.jpt.jpa.db.ui, + org.eclipse.jpt.jpa.gen, + org.eclipse.jpt.jpa.annotate, + org.eclipse.jpt.jpa.ui", org.eclipse.jpt.common.utility.internal.reference; x-friends:="org.eclipse.jpt.common.core, org.eclipse.jpt.common.ui, @@ -236,6 +259,17 @@ Export-Package: org.eclipse.jpt.common.utility, org.eclipse.jpt.jpa.gen, org.eclipse.jpt.jpa.annotate, org.eclipse.jpt.jpa.ui", + org.eclipse.jpt.common.utility.internal.stack; + x-friends:="org.eclipse.jpt.common.core, + org.eclipse.jpt.common.ui, + org.eclipse.jpt.jaxb.core, + org.eclipse.jpt.jaxb.ui, + org.eclipse.jpt.jpa.core, + org.eclipse.jpt.jpa.db, + org.eclipse.jpt.jpa.db.ui, + org.eclipse.jpt.jpa.gen, + org.eclipse.jpt.jpa.annotate, + org.eclipse.jpt.jpa.ui", org.eclipse.jpt.common.utility.internal.swing; x-friends:="org.eclipse.jpt.common.ui, org.eclipse.jpt.jaxb.ui, @@ -260,5 +294,7 @@ Export-Package: org.eclipse.jpt.common.utility, org.eclipse.jpt.common.utility.model.value, org.eclipse.jpt.common.utility.node, org.eclipse.jpt.common.utility.predicate, + org.eclipse.jpt.common.utility.queue, org.eclipse.jpt.common.utility.reference, + org.eclipse.jpt.common.utility.stack, org.eclipse.jpt.common.utility.transformer diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Queue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Queue.java deleted file mode 100644 index 53299251fe..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Queue.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2015 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.collection; - -/** - * Interface defining the classic queue behavior, - * without the backdoors allowed by {@link java.util.Queue}. - *

- * Provisional API: This interface is part of an interim API that is still - * under development and expected to change significantly before reaching - * stability. It is available at this early stage to solicit feedback from - * pioneering adopters on the understanding that any code that uses this API - * will almost certainly be broken (repeatedly) as the API evolves. - * - * @param the type of elements contained by the queue - * @see org.eclipse.jpt.common.utility.internal.collection.ArrayQueue - * @see org.eclipse.jpt.common.utility.internal.collection.LinkedQueue - * @see org.eclipse.jpt.common.utility.internal.collection.QueueTools - * @see Stack Stack - for an interface without the semantic baggage of {@link java.util.Stack} - */ -public interface Queue { - - /** - * "Enqueue" the specified item to the tail of the queue. - */ - void enqueue(E element); - - /** - * "Dequeue" an item from the head of the queue. - */ - E dequeue(); - - /** - * Return the item on the head of the queue - * without removing it from the queue. - */ - E peek(); - - /** - * Return whether the queue is empty. - */ - boolean isEmpty(); -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Stack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Stack.java deleted file mode 100644 index 11efaf5600..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/collection/Stack.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2015 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.collection; - -/** - * Interface defining the classic stack behavior, - * without the backdoors allowed by {@link java.util.Stack}. - *

- * Provisional API: This interface is part of an interim API that is still - * under development and expected to change significantly before reaching - * stability. It is available at this early stage to solicit feedback from - * pioneering adopters on the understanding that any code that uses this API - * will almost certainly be broken (repeatedly) as the API evolves. - * - * @param the type of elements contained by the stack - * @see org.eclipse.jpt.common.utility.internal.collection.ArrayStack - * @see org.eclipse.jpt.common.utility.internal.collection.LinkedStack - * @see org.eclipse.jpt.common.utility.internal.collection.StackTools - * @see Queue Queue - for an interface without the semantic baggage of {@link java.util.Queue} - */ -public interface Stack { - - /** - * "Push" the specified item on to the top of the stack. - */ - void push(E element); - - /** - * "Pop" an item from the top of the stack. - */ - E pop(); - - /** - * Return the item on the top of the stack - * without removing it from the stack. - */ - E peek(); - - /** - * Return whether the stack is empty. - */ - boolean isEmpty(); -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/Deque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/Deque.java new file mode 100644 index 0000000000..4283b32f11 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/Deque.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Interface defining the classic double-ended queue behavior, + * without the backdoors allowed by {@link java.util.Deque}. + *

+ * Provisional API: This interface is part of an interim API that is still + * under development and expected to change significantly before reaching + * stability. It is available at this early stage to solicit feedback from + * pioneering adopters on the understanding that any code that uses this API + * will almost certainly be broken (repeatedly) as the API evolves. + * + * @param the type of elements contained by the deque + * @see org.eclipse.jpt.common.utility.internal.deque.ArrayDeque + * @see org.eclipse.jpt.common.utility.internal.deque.LinkedDeque + * @see org.eclipse.jpt.common.utility.internal.deque.DequeTools + * @see Queue Queue - for an interface without the semantic baggage of {@link java.util.Queue} + */ +public interface Deque + extends InputRestrictedDeque, OutputRestrictedDeque +{ + // combine the "restricted" interfaces +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/InputRestrictedDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/InputRestrictedDeque.java new file mode 100644 index 0000000000..b15cb365fd --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/InputRestrictedDeque.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +/** + * Interface defining a input-restricted double-ended queue. + * Elements can be removed from either end of the queue, + * but added to only the tail of the queue. + *

+ * Provisional API: This interface is part of an interim API that is still + * under development and expected to change significantly before reaching + * stability. It is available at this early stage to solicit feedback from + * pioneering adopters on the understanding that any code that uses this API + * will almost certainly be broken (repeatedly) as the API evolves. + * + * @param the type of elements contained by the deque + * @see Deque + */ +public interface InputRestrictedDeque { + + /** + * "Enqueue" the specified item to the tail of the deque. + */ + void enqueueTail(E element); + + /** + * "Dequeue" an item from the head of the deque. + */ + E dequeueHead(); + + /** + * "Dequeue" an item from the tail of the deque. + */ + E dequeueTail(); + + /** + * Return the item on the head of the deque + * without removing it from the deque. + */ + E peekHead(); + + /** + * Return the item on the tail of the deque + * without removing it from the deque. + */ + E peekTail(); + + /** + * Return whether the deque is empty. + */ + boolean isEmpty(); +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/OutputRestrictedDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/OutputRestrictedDeque.java new file mode 100644 index 0000000000..b2a42dca96 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/deque/OutputRestrictedDeque.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +/** + * Interface defining a output-restricted double-ended queue. + * Elements can be added to either end of the queue, + * but removed from only the head of the queue. + *

+ * Provisional API: This interface is part of an interim API that is still + * under development and expected to change significantly before reaching + * stability. It is available at this early stage to solicit feedback from + * pioneering adopters on the understanding that any code that uses this API + * will almost certainly be broken (repeatedly) as the API evolves. + * + * @param the type of elements contained by the deque + * @see Deque + */ +public interface OutputRestrictedDeque { + + /** + * "Enqueue" the specified item to the head of the queue. + */ + void enqueueHead(E element); + + /** + * "Enqueue" the specified item to the tail of the deque. + */ + void enqueueTail(E element); + + /** + * "Dequeue" an item from the head of the deque. + */ + E dequeueHead(); + + /** + * Return the item on the head of the deque + * without removing it from the deque. + */ + E peekHead(); + + /** + * Return whether the deque is empty. + */ + boolean isEmpty(); +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/ArrayTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/ArrayTools.java index 7e09f76b44..7a7b1a0dd4 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/ArrayTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/ArrayTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -160,7 +160,7 @@ public final class ArrayTools { */ public static Object[] array(Iterator iterator) { return iterator.hasNext() ? - ListTools.list(iterator).toArray() : + ListTools.arrayList(iterator).toArray() : ObjectTools.EMPTY_OBJECT_ARRAY; } @@ -171,7 +171,7 @@ public final class ArrayTools { */ public static Object[] array(Iterator iterator, int iteratorSize) { return iterator.hasNext() ? - ListTools.list(iterator, iteratorSize).toArray() : + ListTools.arrayList(iterator, iteratorSize).toArray() : ObjectTools.EMPTY_OBJECT_ARRAY; } @@ -183,7 +183,7 @@ public final class ArrayTools { public static E[] array(Iterator iterator, Class componentType) { E[] array = newInstance(componentType, 0); return iterator.hasNext() ? - ListTools.list(iterator).toArray(array) : + ListTools.arrayList(iterator).toArray(array) : array; } @@ -195,7 +195,7 @@ public final class ArrayTools { */ public static E[] array(Iterator iterator, int iteratorSize, Class componentType) { return iterator.hasNext() ? - ListTools.list(iterator, iteratorSize).toArray(newInstance(componentType, iteratorSize)) : + ListTools.arrayList(iterator, iteratorSize).toArray(newInstance(componentType, iteratorSize)) : newInstance(componentType, 0); } @@ -209,7 +209,7 @@ public final class ArrayTools { */ public static E[] array(Iterator iterator, E[] array) { return iterator.hasNext() ? - ListTools.list(iterator).toArray(array) : + ListTools.arrayList(iterator).toArray(array) : emptyArray(array); } @@ -224,7 +224,7 @@ public final class ArrayTools { */ public static E[] array(Iterator iterator, int iteratorSize, E[] array) { return iterator.hasNext() ? - ListTools.list(iterator, iteratorSize).toArray(array) : + ListTools.arrayList(iterator, iteratorSize).toArray(array) : emptyArray(array); } @@ -423,7 +423,7 @@ public final class ArrayTools { * in the specified iterator. */ public static E[] addAll(E[] array, Iterator iterator) { - return iterator.hasNext() ? addAll_(array, ListTools.list(iterator)) : array; + return iterator.hasNext() ? addAll_(array, ListTools.arrayList(iterator)) : array; } /** @@ -433,7 +433,7 @@ public final class ArrayTools { * The specified iterator size is a performance hint. */ public static E[] addAll(E[] array, Iterator iterator, int iteratorSize) { - return iterator.hasNext() ? addAll_(array, ListTools.list(iterator, iteratorSize)) : array; + return iterator.hasNext() ? addAll_(array, ListTools.arrayList(iterator, iteratorSize)) : array; } /** @@ -597,7 +597,7 @@ public final class ArrayTools { * in the specified iterator inserted at the specified index. */ public static E[] addAll(E[] array, int index, Iterator iterator) { - return iterator.hasNext() ? addAll_(array, index, ListTools.list(iterator)) : array; + return iterator.hasNext() ? addAll_(array, index, ListTools.arrayList(iterator)) : array; } /** @@ -607,7 +607,7 @@ public final class ArrayTools { * The specified iterator size is a performance hint. */ public static E[] addAll(E[] array, int index, Iterator iterator, int iteratorSize) { - return iterator.hasNext() ? addAll_(array, index, ListTools.list(iterator, iteratorSize)) : array; + return iterator.hasNext() ? addAll_(array, index, ListTools.arrayList(iterator, iteratorSize)) : array; } /** @@ -1025,7 +1025,7 @@ public final class ArrayTools { */ public static boolean containsAll(Object[] array, Iterator iterator) { // use hashed lookup - HashSet set = CollectionTools.set(array); + HashSet set = CollectionTools.hashSet(array); while (iterator.hasNext()) { if ( ! set.contains(iterator.next())) { return false; @@ -1040,7 +1040,7 @@ public final class ArrayTools { */ public static boolean containsAll(Object[] array1, Object... array2) { // use hashed lookup - HashSet set = CollectionTools.set(array1); + HashSet set = CollectionTools.hashSet(array1); for (int i = array2.length; i-- > 0; ) { if ( ! set.contains(array2[i])) { return false; @@ -2054,7 +2054,7 @@ public final class ArrayTools { */ public static E[] removeAll(E[] array, Iterator iterator) { // convert to a set to take advantage of hashed look-up - return iterator.hasNext() ? removeAll_(array, CollectionTools.set(iterator)) : array; + return iterator.hasNext() ? removeAll_(array, CollectionTools.hashSet(iterator)) : array; } /** @@ -2064,7 +2064,7 @@ public final class ArrayTools { */ public static E[] removeAll(E[] array, Iterator iterator, int iteratorSize) { // convert to a set to take advantage of hashed look-up - return iterator.hasNext() ? removeAll_(array, CollectionTools.set(iterator, iteratorSize)) : array; + return iterator.hasNext() ? removeAll_(array, CollectionTools.hashSet(iterator, iteratorSize)) : array; } /** @@ -2118,7 +2118,7 @@ public final class ArrayTools { */ public static E[] removeAll(E[] array1, Object... array2) { // convert to a set to take advantage of hashed look-up - return (array2.length == 0) ? array1 : removeAll_(array1, CollectionTools.set(array2)); + return (array2.length == 0) ? array1 : removeAll_(array1, CollectionTools.hashSet(array2)); } /** @@ -2553,7 +2553,7 @@ public final class ArrayTools { */ private static E[] retainAll(E[] array, int arrayLength, Iterator iterator) { return iterator.hasNext() ? - retainAll_(array, CollectionTools.set(iterator), arrayLength) : + retainAll_(array, CollectionTools.hashSet(iterator), arrayLength) : newInstance(array, 0); } @@ -2562,7 +2562,7 @@ public final class ArrayTools { */ private static E[] retainAll(E[] array, int arrayLength, Iterator iterator, int iteratorSize) { return iterator.hasNext() ? - retainAll_(array, CollectionTools.set(iterator, iteratorSize), arrayLength) : + retainAll_(array, CollectionTools.hashSet(iterator, iteratorSize), arrayLength) : newInstance(array, 0); } @@ -2616,7 +2616,7 @@ public final class ArrayTools { array1 : (array2.length == 0) ? newInstance(array1, 0) : - retainAll(array1, CollectionTools.set(array2), array1Length); + retainAll(array1, CollectionTools.hashSet(array2), array1Length); } /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/NameTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/NameTools.java index 5167b26185..ff08df4810 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/NameTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/NameTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2012 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -28,7 +28,7 @@ public final class NameTools { * @see #uniqueName(String, Collection) */ public static String uniqueName(String rootName, Iterable existingNames) { - return uniqueName(rootName, CollectionTools.set(existingNames)); + return uniqueName(rootName, CollectionTools.hashSet(existingNames)); } /** @@ -46,7 +46,7 @@ public final class NameTools { * @see #uniqueNameIgnoreCase(String, Collection) */ public static String uniqueNameIgnoreCase(String rootName, Iterable existingNames) { - return uniqueNameIgnoreCase(rootName, CollectionTools.set(existingNames)); + return uniqueNameIgnoreCase(rootName, CollectionTools.hashSet(existingNames)); } /** @@ -193,7 +193,7 @@ public final class NameTools { * Java Language Keywords */ public static final SortedSet JAVA_RESERVED_WORDS = - Collections.unmodifiableSortedSet(CollectionTools.sortedSet(JAVA_RESERVED_WORDS_ARRAY)); + Collections.unmodifiableSortedSet(CollectionTools.treeSet(JAVA_RESERVED_WORDS_ARRAY)); /** * Return whether the specified string consists of Java identifier diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/Range.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/Range.java index c52a936cf5..756a823e59 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/Range.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/Range.java @@ -43,7 +43,7 @@ public class Range /** * Construct a range with the specified start and end, both of which are - * mmutable. If the specified end is less than the specified start, the + * immutable. If the specified end is less than the specified start, the * values will be swapped in the range. */ public Range(int start, int end) { diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/AbstractRepeatingElementList.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/AbstractRepeatingElementList.java index 47287f3ff3..fa93b49112 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/AbstractRepeatingElementList.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/AbstractRepeatingElementList.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -14,7 +14,6 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; - import org.eclipse.jpt.common.utility.internal.ArrayTools; import org.eclipse.jpt.common.utility.internal.ObjectTools; @@ -217,7 +216,17 @@ public abstract class AbstractRepeatingElementList @Override public String toString() { - return ObjectTools.toString(this, this.size); + StringBuilder sb = new StringBuilder(); + sb.append('['); + for (int i = this.size; i-- > 0; ) { + sb.append(this.getElement()); + sb.append(", "); //$NON-NLS-1$ + } + if (sb.length() > 1) { + sb.setLength(sb.length() - 2); + } + sb.append(']'); + return sb.toString(); } private static final long serialVersionUID = 1L; diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayQueue.java deleted file mode 100644 index 5b7b87ddcf..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayQueue.java +++ /dev/null @@ -1,204 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; - -/** - * Resizable-array FIFO implementation of the {@link Queue} interface. - * @param the type of elements maintained by the queue - * @see FixedSizeArrayQueue - * @see QueueTools - */ -public class ArrayQueue - implements Queue, Cloneable, Serializable -{ - private transient E[] elements; - - /** Index of next element to be "dequeued". */ - private transient int head = 0; - - /** Index of next element to be "enqueued". */ - private transient int tail = 0; - - private int size = 0; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct an empty queue. - */ - public ArrayQueue() { - this(10); - } - - /** - * Construct an empty queue with the specified initial capacity. - */ - @SuppressWarnings("unchecked") - public ArrayQueue(int initialCapacity) { - super(); - if (initialCapacity < 0) { - throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ - } - this.elements = (E[]) new Object[initialCapacity]; - } - - - // ********** Queue implementation ********** - - public void enqueue(E element) { - this.ensureCapacity(this.size + 1); - this.elements[this.tail] = element; - if (++this.tail == this.elements.length) { - this.tail = 0; - } - this.size++; - } - - /** - * Increase the queue's capacity, if necessary, to ensure it has at least - * the specified minimum capacity. - */ - public void ensureCapacity(int minCapacity) { - int oldCapacity = this.elements.length; - if (oldCapacity < minCapacity) { - int newCapacity = ((oldCapacity * 3) >> 1) + 1; - if (newCapacity < minCapacity) { - newCapacity = minCapacity; - } - this.elements = this.copyElements(newCapacity); - this.head = 0; - this.tail = this.size; - } - } - - /** - * Decrease the queue's capacity, if necessary, to match its current size. - */ - public void trimToSize() { - if (this.elements.length > this.size) { - this.elements = this.copyElements(this.size); - this.head = 0; - this.tail = this.size; - } - } - - private E[] copyElements(int newCapacity) { - @SuppressWarnings("unchecked") - E[] newElements = (E[]) new Object[newCapacity]; - if (this.size != 0) { - Object oldElements[] = this.elements; - if ((this.head == 0) || (this.head < this.tail) || (this.tail == 0)) { - // elements are contiguous - System.arraycopy(oldElements, this.head, newElements, 0, this.size); - } else { - // elements wrap past end of array - int fragmentSize = oldElements.length - this.head; - System.arraycopy(oldElements, this.head, newElements, 0, fragmentSize); - System.arraycopy(oldElements, 0, newElements, fragmentSize, (this.size - fragmentSize)); - } - } - return newElements; - } - - public E dequeue() { - if (this.size == 0) { - throw new NoSuchElementException(); - } - E element = this.elements[this.head]; - this.elements[this.head] = null; // allow GC to work - if (++this.head == this.elements.length) { - this.head = 0; - } - this.size--; - return element; - } - - public E peek() { - if (this.size == 0) { - throw new NoSuchElementException(); - } - return this.elements[this.head]; - } - - public boolean isEmpty() { - return this.size == 0; - } - - - // ********** standard methods ********** - - @Override - public ArrayQueue clone() { - try { - @SuppressWarnings("unchecked") - ArrayQueue clone = (ArrayQueue) super.clone(); - @SuppressWarnings("cast") - E[] array = (E[]) this.elements.clone(); - clone.elements = array; - return clone; - } catch (CloneNotSupportedException ex) { - throw new InternalError(); - } - } - - @Override - public String toString() { - return Arrays.toString(this.copyElements(this.size)); - } - - - // ********** Serializable "implementation" ********** - - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { - // write size (and any hidden stuff) - stream.defaultWriteObject(); - Object[] array = this.elements; - int elementsLength = array.length; - stream.writeInt(elementsLength); - if (this.size == 0) { - return; - } - // save the elements in contiguous order - if (this.head < this.tail) { // elements are contiguous - for (int i = this.head; i < this.tail; i++) { - stream.writeObject(array[i]); - } - } else { // (this.head >= this.tail) - elements wrap past end of array - for (int i = this.head; i < elementsLength; i++) { - stream.writeObject(array[i]); - } - for (int i = 0; i < this.tail; i++) { - stream.writeObject(array[i]); - } - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { - // read size (and any hidden stuff) - stream.defaultReadObject(); - int elementsLength = stream.readInt(); - Object[] array = new Object[elementsLength]; - for (int i = 0; i < this.size; i++) { - array[i] = stream.readObject(); - } - this.elements = (E[]) array; - this.head = 0; - this.tail = this.size; - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayStack.java deleted file mode 100644 index 20fdf3102b..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ArrayStack.java +++ /dev/null @@ -1,203 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.EmptyStackException; -import org.eclipse.jpt.common.utility.collection.Stack; - -/** - * Resizable-array LIFO implementation of the {@link Stack} interface. - * @param the type of elements maintained by the stack - * @see FixedSizeArrayStack - * @see StackTools - */ -public class ArrayStack - implements Stack, Cloneable, Serializable -{ - private transient E[] elements; - - /** The index of where the next "pushed" element will go. */ - private transient int next = 0; - - private int size = 0; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct an empty stack. - */ - public ArrayStack() { - this(10); - } - - /** - * Construct an empty stack with the specified initial capacity. - */ - @SuppressWarnings("unchecked") - public ArrayStack(int initialCapacity) { - super(); - if (initialCapacity < 0) { - throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ - } - this.elements = (E[]) new Object[initialCapacity]; - } - - - // ********** Stack implementation ********** - - public void push(E element) { - this.ensureCapacity(this.size + 1); - this.elements[this.next] = element; - if (++this.next == this.elements.length) { - this.next = 0; - } - this.size++; - } - - /** - * Increase the stack's capacity, if necessary, to ensure it has at least - * the specified minimum capacity. - */ - public void ensureCapacity(int minCapacity) { - int oldCapacity = this.elements.length; - if (oldCapacity < minCapacity) { - int newCapacity = ((oldCapacity * 3) >> 1) + 1; - if (newCapacity < minCapacity) { - newCapacity = minCapacity; - } - this.elements = this.copyElements(newCapacity); - this.next = this.size; - } - } - - /** - * Decrease the stack's capacity, if necessary, to match its current size. - */ - public void trimToSize() { - if (this.elements.length > this.size) { - this.elements = this.copyElements(this.size); - this.next = this.size; - } - } - - private E[] copyElements(int newCapacity) { - @SuppressWarnings("unchecked") - E[] newElements = (E[]) new Object[newCapacity]; - int len = this.size; - if (len != 0) { - System.arraycopy(this.elements, 0, newElements, 0, len); - } - return newElements; - } - - public E pop() { - if (this.size == 0) { - throw new EmptyStackException(); - } - int index = this.next; - if (index == 0) { - index = this.elements.length; - } - index--; - E element = this.elements[index]; - this.elements[index] = null; // allow GC to work - this.next = index; - this.size--; - return element; - } - - public E peek() { - if (this.size == 0) { - throw new EmptyStackException(); - } - int index = this.next; - if (index == 0) { - index = this.elements.length; - } - index--; - return this.elements[index]; - } - - public boolean isEmpty() { - return this.size == 0; - } - - - // ********** standard methods ********** - - @Override - public ArrayStack clone() { - try { - @SuppressWarnings("unchecked") - ArrayStack clone = (ArrayStack) super.clone(); - @SuppressWarnings("cast") - E[] array = (E[]) this.elements.clone(); - clone.elements = array; - return clone; - } catch (CloneNotSupportedException ex) { - throw new InternalError(); - } - } - - /** - * Print the elements in the order in which they are "pushed" on to - * the stack (as opposed to the order in which they will be "popped" - * off of the stack). - */ - @Override - public String toString() { - return Arrays.toString(this.copyElements(this.size)); - } - - - // ********** Serializable "implementation" ********** - - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { - // write size (and any hidden stuff) - stream.defaultWriteObject(); - Object[] array = this.elements; - int elementsLength = array.length; - stream.writeInt(elementsLength); - if (this.size == 0) { - return; - } - // save the elements in contiguous order - if (this.next >= this.size) { // elements are contiguous - for (int i = (this.next - this.size); i < this.next; i++) { - stream.writeObject(array[i]); - } - } else { // (this.next < this.size) - elements wrap past end of array - for (int i = (elementsLength - (this.size - this.next)); i < elementsLength; i++) { - stream.writeObject(array[i]); - } - for (int i = 0; i < this.next; i++) { - stream.writeObject(array[i]); - } - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { - // read size (and any hidden stuff) - stream.defaultReadObject(); - int elementsLength = stream.readInt(); - Object[] array = new Object[elementsLength]; - for (int i = 0; i < this.size; i++) { - array[i] = stream.readObject(); - } - this.elements = (E[]) array; - this.next = this.size; - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/CollectionTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/CollectionTools.java index cd51bb3d59..a1f52a2862 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/CollectionTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/CollectionTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -16,12 +16,9 @@ import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; -import java.util.List; import java.util.TreeSet; import java.util.Vector; import org.eclipse.jpt.common.utility.collection.Bag; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.predicate.Predicate; import org.eclipse.jpt.common.utility.transformer.Transformer; @@ -67,11 +64,11 @@ public final class CollectionTools { /** * assume the iterator is not empty */ - private static boolean addAll_(Collection collection, Iterator iterator) { + /* package */ static boolean addAll_(Collection collection, Iterator iterator) { boolean modified = false; - while (iterator.hasNext()) { + do { modified |= collection.add(iterator.next()); - } + } while (iterator.hasNext()); return modified; } @@ -82,7 +79,7 @@ public final class CollectionTools { * The specified iterator size is a performance hint. */ public static boolean addAll(Collection collection, Iterator iterator, int iteratorSize) { - return iterator.hasNext() && collection.addAll(ListTools.list(iterator, iteratorSize)); + return iterator.hasNext() && collection.addAll(ListTools.arrayList(iterator, iteratorSize)); } /** @@ -91,69 +88,20 @@ public final class CollectionTools { * Return whether the collection changed as a result. */ public static boolean addAll(Collection collection, E... array) { - return (array.length != 0) && collection.addAll(Arrays.asList(array)); + return (array.length != 0) && addAll_(collection, array); } /** - * Dequeue all the elements from the specified queue and add them - * to the specified collection. - * Return whether the collection changed as a result. + * assume the array is not empty */ - public static boolean addAll(Collection collection, Queue queue) { - return ( ! queue.isEmpty()) && addAll_(collection, queue); - } - - /** - * assume the queue is not empty - */ - private static boolean addAll_(Collection collection, Queue queue) { + private static boolean addAll_(Collection collection, E... array) { boolean modified = false; - while ( ! queue.isEmpty()) { - modified |= collection.add(queue.dequeue()); + for (E element : array) { + modified |= collection.add(element); } return modified; } - /** - * Dequeue all the elements from the specified queue and add them - * to the specified collection. - * Return whether the collection changed as a result. - * The specified queue size is a performance hint. - */ - public static boolean addAll(Collection collection, Queue queue, int queueSize) { - return ( ! queue.isEmpty()) && collection.addAll(ListTools.list(queue, queueSize)); - } - - /** - * Pop all the elements from the specified stack and add them - * to the specified collection. - * Return whether the collection changed as a result. - */ - public static boolean addAll(Collection collection, Stack stack) { - return ( ! stack.isEmpty()) && addAll_(collection, stack); - } - - /** - * assume the stack is not empty - */ - private static boolean addAll_(Collection collection, Stack stack) { - boolean modified = false; - while ( ! stack.isEmpty()) { - modified |= collection.add(stack.pop()); - } - return modified; - } - - /** - * Pop all the elements from the specified stack and add them - * to the specified collection. - * Return whether the collection changed as a result. - * The specified stack size is a performance hint. - */ - public static boolean addAll(Collection collection, Stack stack, int stackSize) { - return ( ! stack.isEmpty()) && collection.addAll(ListTools.list(stack, stackSize)); - } - // ********** contains all ********** @@ -192,34 +140,6 @@ public final class CollectionTools { return true; } - /** - * Return whether the specified collection contains all of the - * elements in the specified queue, dequeueing elements from the queue - * until one is not found in the collection. - */ - public static boolean containsAll(Collection collection, Queue queue) { - while ( ! queue.isEmpty()) { - if ( ! collection.contains(queue.dequeue())) { - return false; - } - } - return true; - } - - /** - * Return whether the specified collection contains all of the - * elements in the specified stack, popping elements from the stack - * until one is not found in the collection. - */ - public static boolean containsAll(Collection collection, Stack stack) { - while ( ! stack.isEmpty()) { - if ( ! collection.contains(stack.pop())) { - return false; - } - } - return true; - } - // ********** filter ********** @@ -228,7 +148,7 @@ public final class CollectionTools { * elements of the specified collection. */ public static HashBag filter(Collection collection, Predicate filter) { - HashBag result = new HashBag(collection.size()); + HashBag result = hashBag(collection.size()); for (E e : collection) { if (filter.evaluate(e)) { result.add(e); @@ -314,7 +234,7 @@ public final class CollectionTools { * Return whether the collection changed as a result. */ public static boolean removeAll(Collection collection, Iterator iterator) { - return iterator.hasNext() && collection.removeAll(set(iterator)); + return iterator.hasNext() && collection.removeAll(hashSet(iterator)); } /** @@ -324,7 +244,7 @@ public final class CollectionTools { * The specified iterator size is a performance hint. */ public static boolean removeAll(Collection collection, Iterator iterator, int iteratorSize) { - return iterator.hasNext() && collection.removeAll(set(iterator, iteratorSize)); + return iterator.hasNext() && collection.removeAll(hashSet(iterator, iteratorSize)); } /** @@ -333,45 +253,7 @@ public final class CollectionTools { * Return whether the collection changed as a result. */ public static boolean removeAll(Collection collection, Object... array) { - return (array.length != 0) && collection.removeAll(set(array)); - } - - /** - * Remove all the elements dequeued from the specified queue - * from the specified collection, draining the queue in the process. - * Return whether the collection changed as a result. - */ - public static boolean removeAll(Collection collection, Queue queue) { - return ( ! queue.isEmpty()) && collection.removeAll(set(queue)); - } - - /** - * Remove all the elements dequeued from the specified queue - * from the specified collection, draining the queue in the process. - * Return whether the collection changed as a result. - * The specified queue size is a performance hint. - */ - public static boolean removeAll(Collection collection, Queue queue, int queueSize) { - return ( ! queue.isEmpty()) && collection.removeAll(set(queue, queueSize)); - } - - /** - * Remove all the elements from the specified stack - * from the specified collection, draining the stack in the process. - * Return whether the collection changed as a result. - */ - public static boolean removeAll(Collection collection, Stack stack) { - return ( ! stack.isEmpty()) && collection.removeAll(set(stack)); - } - - /** - * Remove all the elements from the specified stack - * from the specified collection, draining the stack in the process. - * Return whether the collection changed as a result. - * The specified stack size is a performance hint. - */ - public static boolean removeAll(Collection collection, Stack stack, int stackSize) { - return ( ! stack.isEmpty()) && collection.removeAll(set(stack, stackSize)); + return (array.length != 0) && collection.removeAll(hashSet(array)); } @@ -432,7 +314,7 @@ public final class CollectionTools { */ public static boolean retainAll(Collection collection, Iterator iterator) { if (iterator.hasNext()) { - return collection.retainAll(set(iterator)); + return collection.retainAll(hashSet(iterator)); } if (collection.isEmpty()) { return false; @@ -449,7 +331,7 @@ public final class CollectionTools { */ public static boolean retainAll(Collection collection, Iterator iterator, int iteratorSize) { if (iterator.hasNext()) { - return collection.retainAll(set(iterator, iteratorSize)); + return collection.retainAll(hashSet(iterator, iteratorSize)); } if (collection.isEmpty()) { return false; @@ -465,73 +347,7 @@ public final class CollectionTools { */ public static boolean retainAll(Collection collection, Object... array) { if (array.length > 0) { - return collection.retainAll(set(array)); - } - if (collection.isEmpty()) { - return false; - } - collection.clear(); - return true; - } - - /** - * Retain only the elements in the specified queue - * in the specified collection, draining the queue in the process. - * Return whether the collection changed as a result. - */ - public static boolean retainAll(Collection collection, Queue queue) { - if ( ! queue.isEmpty()) { - return collection.retainAll(set(queue)); - } - if (collection.isEmpty()) { - return false; - } - collection.clear(); - return true; - } - - /** - * Retain only the elements in the specified queue - * in the specified collection, draining the queue in the process. - * Return whether the collection changed as a result. - * The specified queue size is a performance hint. - */ - public static boolean retainAll(Collection collection, Queue queue, int queueSize) { - if ( ! queue.isEmpty()) { - return collection.retainAll(set(queue, queueSize)); - } - if (collection.isEmpty()) { - return false; - } - collection.clear(); - return true; - } - - /** - * Retain only the elements in the specified stack - * in the specified collection, draining the stack in the process. - * Return whether the collection changed as a result. - */ - public static boolean retainAll(Collection collection, Stack stack) { - if ( ! stack.isEmpty()) { - return collection.retainAll(set(stack)); - } - if (collection.isEmpty()) { - return false; - } - collection.clear(); - return true; - } - - /** - * Retain only the elements in the specified stack - * in the specified collection, draining the stack in the process. - * Return whether the collection changed as a result. - * The specified stack size is a performance hint. - */ - public static boolean retainAll(Collection collection, Stack stack, int stackSize) { - if ( ! stack.isEmpty()) { - return collection.retainAll(set(stack, stackSize)); + return collection.retainAll(hashSet(array)); } if (collection.isEmpty()) { return false; @@ -561,7 +377,7 @@ public final class CollectionTools { * elements in the specified collection. */ public static HashBag transform(Collection collection, Transformer transformer) { - HashBag result = new HashBag(collection.size()); + HashBag result = hashBag(collection.size()); for (E1 e : collection) { result.add(transformer.transform(e)); } @@ -569,39 +385,63 @@ public final class CollectionTools { } - // ********** bag factory methods ********** + // ********** hash bag factory methods ********** + + /** + * Return a new hash bag. + */ + public static HashBag hashBag() { + return new HashBag(); + } + + /** + * Return a new hash bag with the specified initial capacity. + */ + public static HashBag hashBag(int initialCapacity) { + return new HashBag(initialCapacity); + } + + /** + * Return a new hash bag with the specified initial capacity + * and load factor. + */ + public static HashBag hashBag(int initialCapacity, float loadFactor) { + return new HashBag(initialCapacity, loadFactor); + } /** - * Return a bag corresponding to the specified iterable. + * Return a new hash bag corresponding to the specified iterable. */ - public static HashBag bag(Iterable iterable) { - return bag(iterable.iterator()); + public static HashBag hashBag(Iterable iterable) { + return hashBag(iterable.iterator()); } /** - * Return a bag corresponding to the specified iterable. + * Return a new hash bag corresponding to the specified iterable. * The specified iterable size is a performance hint. */ - public static HashBag bag(Iterable iterable, int iterableSize) { - return bag(iterable.iterator(), iterableSize); + public static HashBag hashBag(Iterable iterable, int iterableSize) { + return hashBag(iterable.iterator(), iterableSize); } /** - * Return a bag corresponding to the specified iterator. + * Return a new hash bag corresponding to the specified iterator. */ - public static HashBag bag(Iterator iterator) { - return bag(iterator, new HashBag()); + public static HashBag hashBag(Iterator iterator) { + HashBag bag = hashBag(); + return hashBag(iterator, bag); } /** - * Return a bag corresponding to the specified iterator. + * Return a new hash bag corresponding to the specified iterator. * The specified iterator size is a performance hint. */ - public static HashBag bag(Iterator iterator, int iteratorSize) { - return bag(iterator, new HashBag(iteratorSize)); + public static HashBag hashBag(Iterator iterator, int iteratorSize) { + HashBag bag = hashBag(iteratorSize); + return hashBag(iterator, bag); } - private static HashBag bag(Iterator iterator, HashBag bag) { + private static HashBag hashBag(Iterator iterator, HashBag bag) { while (iterator.hasNext()) { bag.add(iterator.next()); } @@ -609,63 +449,49 @@ public final class CollectionTools { } /** - * Return a bag corresponding to the specified array. + * Return a new hash bag corresponding to the specified array. */ - public static HashBag bag(E... array) { + public static HashBag hashBag(E... array) { int len = array.length; - HashBag bag = new HashBag(len); + HashBag bag = hashBag(len); for (E item : array) { bag.add(item); } return bag; } + + // ********** synchronized bag factory methods ********** + /** - * Return a bag corresponding to the specified queue, draining the queue - * in the process. + * Return a synchronized bag. */ - public static HashBag bag(Queue queue) { - return bag(queue, new HashBag()); + public static SynchronizedBag synchronizedBag() { + HashBag bag = hashBag(); + return synchronizedBag(bag); } /** - * Return a bag corresponding to the specified queue, draining the queue - * in the process. - * The specified queue size is a performance hint. + * Return a bag that synchronizes with specified mutex. */ - public static HashBag bag(Queue queue, int queueSize) { - return bag(queue, new HashBag(queueSize)); - } - - private static HashBag bag(Queue queue, HashBag set) { - while ( ! queue.isEmpty()) { - set.add(queue.dequeue()); - } - return set; + public static SynchronizedBag synchronizedBag(Object mutex) { + HashBag bag = hashBag(); + return synchronizedBag(bag, mutex); } /** - * Return a bag corresponding to the specified stack, draining the stack - * in the process. + * Return a bag that synchronizes the specified bag. */ - public static HashBag bag(Stack stack) { - return bag(stack, new HashBag()); + public static SynchronizedBag synchronizedBag(Bag bag) { + return new SynchronizedBag(bag); } /** - * Return a bag corresponding to the specified stack, draining the stack - * in the process. - * The specified stack size is a performance hint. + * Return a bag that synchronizes the specified bag + * with specified mutex. */ - public static HashBag bag(Stack stack, int stackSize) { - return bag(stack, new HashBag(stackSize)); - } - - private static HashBag bag(Stack stack, HashBag set) { - while ( ! stack.isEmpty()) { - set.add(stack.pop()); - } - return set; + public static SynchronizedBag synchronizedBag(Bag bag, Object mutex) { + return new SynchronizedBag(bag, mutex); } /** @@ -674,169 +500,119 @@ public final class CollectionTools { * The specified stack size is a performance hint. */ public static Bag emptyBag() { - return EmptyBag.instance(); + return EmptyBag.instance(); } - // ********** identity bag factory methods ********** + // ********** identity hash bag factory methods ********** /** - * Return an identity bag corresponding to the specified iterable. + * Return a new identity hash bag. */ - public static IdentityHashBag identityBag(Iterable iterable) { - return identityBag(iterable.iterator()); + public static IdentityHashBag identityHashBag() { + return new IdentityHashBag(); } /** - * Return an identity bag corresponding to the specified iterable. - * The specified iterable size is a performance hint. - */ - public static IdentityHashBag identityBag(Iterable iterable, int iterableSize) { - return identityBag(iterable.iterator(), iterableSize); - } - - /** - * Return an identity bag corresponding to the specified iterator. - */ - public static IdentityHashBag identityBag(Iterator iterator) { - return identityBag(iterator, new IdentityHashBag()); - } - - /** - * Return an identity bag corresponding to the specified iterator. - * The specified iterator size is a performance hint. + * Return a new identity hash bag with the specified initial capacity. */ - public static IdentityHashBag identityBag(Iterator iterator, int iteratorSize) { - return identityBag(iterator, new IdentityHashBag(iteratorSize)); - } - - private static IdentityHashBag identityBag(Iterator iterator, IdentityHashBag bag) { - while (iterator.hasNext()) { - bag.add(iterator.next()); - } - return bag; + public static IdentityHashBag identityHashBag(int initialCapacity) { + return new IdentityHashBag(initialCapacity); } /** - * Return an identity bag corresponding to the specified array. + * Return a new identity hash bag with the specified initial capacity + * and load factor. */ - public static IdentityHashBag identityBag(E... array) { - int len = array.length; - IdentityHashBag bag = new IdentityHashBag(len); - for (E item : array) { - bag.add(item); - } - return bag; + public static IdentityHashBag identityHashBag(int initialCapacity, float loadFactor) { + return new IdentityHashBag(initialCapacity, loadFactor); } - - // ********** collection factory methods ********** - /** - * Return a collection corresponding to the specified iterable. + * Return a new identity hash bag corresponding to the specified iterable. */ - public static HashBag collection(Iterable iterable) { - return collection(iterable.iterator()); + public static IdentityHashBag identityHashBag(Iterable iterable) { + return identityHashBag(iterable.iterator()); } /** - * Return a collection corresponding to the specified iterable. + * Return a new identity hash bag corresponding to the specified iterable. * The specified iterable size is a performance hint. */ - public static HashBag collection(Iterable iterable, int iterableSize) { - return collection(iterable.iterator(), iterableSize); + public static IdentityHashBag identityHashBag(Iterable iterable, int iterableSize) { + return identityHashBag(iterable.iterator(), iterableSize); } /** - * Return a collection corresponding to the specified iterator. + * Return a new identity hash bag corresponding to the specified iterator. */ - public static HashBag collection(Iterator iterator) { - return bag(iterator); + public static IdentityHashBag identityHashBag(Iterator iterator) { + IdentityHashBag bag = identityHashBag(); + return identityHashBag(iterator, bag); } /** - * Return a collection corresponding to the specified iterator. + * Return a new identity hash bag corresponding to the specified iterator. * The specified iterator size is a performance hint. */ - public static HashBag collection(Iterator iterator, int iteratorSize) { - return bag(iterator, iteratorSize); + public static IdentityHashBag identityHashBag(Iterator iterator, int iteratorSize) { + IdentityHashBag bag = identityHashBag(iteratorSize); + return identityHashBag(iterator, bag); } - /** - * Return a collection corresponding to the specified array. - */ - public static HashBag collection(E... array) { - return bag(array); - } - - /** - * Return a collection corresponding to the specified queue, draining the queue - * in the process. - */ - public static HashBag collection(Queue queue) { - return bag(queue); - } - - /** - * Return a collection corresponding to the specified queue, draining the queue - * in the process. - * The specified queue size is a performance hint. - */ - public static HashBag collection(Queue queue, int queueSize) { - return bag(queue, queueSize); - } - - /** - * Return a collection corresponding to the specified stack, draining the stack - * in the process. - */ - public static HashBag collection(Stack stack) { - return bag(stack); + private static IdentityHashBag identityHashBag(Iterator iterator, IdentityHashBag bag) { + while (iterator.hasNext()) { + bag.add(iterator.next()); + } + return bag; } /** - * Return a collection corresponding to the specified stack, draining the stack - * in the process. - * The specified stack size is a performance hint. + * Return a new identity hash bag corresponding to the specified array. */ - public static HashBag collection(Stack stack, int stackSize) { - return bag(stack, stackSize); + public static IdentityHashBag identityHashBag(E... array) { + int len = array.length; + IdentityHashBag bag = identityHashBag(len); + for (E item : array) { + bag.add(item); + } + return bag; } - // ********** set factory methods ********** + // ********** hash set factory methods ********** /** - * Return a set corresponding to the specified iterable. + * Return a new hash set corresponding to the specified iterable. */ - public static HashSet set(Iterable iterable) { - return set(iterable.iterator()); + public static HashSet hashSet(Iterable iterable) { + return hashSet(iterable.iterator()); } /** - * Return a set corresponding to the specified iterable. + * Return a new hash set corresponding to the specified iterable. * The specified iterable size is a performance hint. */ - public static HashSet set(Iterable iterable, int iterableSize) { - return set(iterable.iterator(), iterableSize); + public static HashSet hashSet(Iterable iterable, int iterableSize) { + return hashSet(iterable.iterator(), iterableSize); } /** - * Return a set corresponding to the specified iterator. + * Return a new hash set corresponding to the specified iterator. */ - public static HashSet set(Iterator iterator) { - return set(iterator, new HashSet()); + public static HashSet hashSet(Iterator iterator) { + return hashSet(iterator, new HashSet()); } /** - * Return a set corresponding to the specified iterator. + * Return a new hash set corresponding to the specified iterator. * The specified iterator size is a performance hint. */ - public static HashSet set(Iterator iterator, int iteratorSize) { - return set(iterator, new HashSet(iteratorSize)); + public static HashSet hashSet(Iterator iterator, int iteratorSize) { + return hashSet(iterator, new HashSet(iteratorSize)); } - private static HashSet set(Iterator iterator, HashSet set) { + private static HashSet hashSet(Iterator iterator, HashSet set) { while (iterator.hasNext()) { set.add(iterator.next()); } @@ -844,9 +620,9 @@ public final class CollectionTools { } /** - * Return a set corresponding to the specified array. + * Return a new hash set corresponding to the specified array. */ - public static HashSet set(E... array) { + public static HashSet hashSet(E... array) { HashSet set = new HashSet(array.length); for (int i = array.length; i-- > 0;) { set.add(array[i]); @@ -854,213 +630,96 @@ public final class CollectionTools { return set; } - /** - * Return a set corresponding to the specified queue, draining the queue - * in the process. - */ - public static HashSet set(Queue queue) { - return set(queue, new HashSet()); - } - /** - * Return a set corresponding to the specified queue, draining the queue - * in the process. - * The specified queue size is a performance hint. - */ - public static HashSet set(Queue queue, int queueSize) { - return set(queue, new HashSet(queueSize)); - } - - private static HashSet set(Queue queue, HashSet set) { - while ( ! queue.isEmpty()) { - set.add(queue.dequeue()); - } - return set; - } + // ********** tree (sorted) set factory methods ********** /** - * Return a set corresponding to the specified stack, draining the stack - * in the process. + * Return a new tree (sorted) set corresponding to the specified iterable. */ - public static HashSet set(Stack stack) { - return set(stack, new HashSet()); + public static > TreeSet treeSet(Iterable iterable) { + return treeSet(iterable.iterator()); } /** - * Return a set corresponding to the specified stack, draining the stack - * in the process. - * The specified stack size is a performance hint. - */ - public static HashSet set(Stack stack, int stackSize) { - return set(stack, new HashSet(stackSize)); - } - - private static HashSet set(Stack stack, HashSet set) { - while ( ! stack.isEmpty()) { - set.add(stack.pop()); - } - return set; - } - - - // ********** sorted set factory methods ********** - - /** - * Return a sorted set corresponding to the specified iterable. - */ - public static > TreeSet sortedSet(Iterable iterable) { - return sortedSet(iterable.iterator()); - } - - /** - * Return a sorted set corresponding to the specified iterable. + * Return a new tree (sorted) set corresponding to the specified iterable. * The specified iterable size is a performance hint. */ - public static > TreeSet sortedSet(Iterable iterable, int iterableSize) { - return sortedSet(iterable.iterator(), iterableSize); + public static > TreeSet treeSet(Iterable iterable, int iterableSize) { + return treeSet(iterable.iterator(), iterableSize); } /** - * Return a sorted set corresponding to the specified iterable + * Return a new tree (sorted) set corresponding to the specified iterable * and comparator. */ - public static TreeSet sortedSet(Iterable iterable, Comparator comparator) { - return sortedSet(iterable.iterator(), comparator); + public static TreeSet treeSet(Iterable iterable, Comparator comparator) { + return treeSet(iterable.iterator(), comparator); } /** - * Return a sorted set corresponding to the specified iterable + * Return a new tree (sorted) set corresponding to the specified iterable * and comparator. * The specified iterable size is a performance hint. */ - public static TreeSet sortedSet(Iterable iterable, Comparator comparator, int iterableSize) { - return sortedSet(iterable.iterator(), comparator, iterableSize); + public static TreeSet treeSet(Iterable iterable, Comparator comparator, int iterableSize) { + return treeSet(iterable.iterator(), comparator, iterableSize); } /** - * Return a sorted set corresponding to the specified iterator. + * Return a new tree (sorted) set corresponding to the specified iterator. */ - public static > TreeSet sortedSet(Iterator iterator) { - return sortedSet(iterator, null); + public static > TreeSet treeSet(Iterator iterator) { + return treeSet(iterator, null); } /** - * Return a sorted set corresponding to the specified iterator. + * Return a new tree (sorted) set corresponding to the specified iterator. * The specified iterator size is a performance hint. */ - public static > TreeSet sortedSet(Iterator iterator, int iteratorSize) { - return sortedSet(iterator, null, iteratorSize); + public static > TreeSet treeSet(Iterator iterator, int iteratorSize) { + return treeSet(iterator, null, iteratorSize); } /** - * Return a sorted set corresponding to the specified iterator + * Return a new tree (sorted) set corresponding to the specified iterator * and comparator. */ - public static TreeSet sortedSet(Iterator iterator, Comparator comparator) { - return sortedSet(ListTools.list(iterator), comparator); + public static TreeSet treeSet(Iterator iterator, Comparator comparator) { + return treeSet(ListTools.arrayList(iterator), comparator); } /** - * Return a sorted set corresponding to the specified iterator + * Return a new tree (sorted) set corresponding to the specified iterator * and comparator. * The specified iterator size is a performance hint. */ - public static TreeSet sortedSet(Iterator iterator, Comparator comparator, int iteratorSize) { - return sortedSet(ListTools.list(iterator, iteratorSize), comparator); + public static TreeSet treeSet(Iterator iterator, Comparator comparator, int iteratorSize) { + return treeSet(ListTools.arrayList(iterator, iteratorSize), comparator); } - private static TreeSet sortedSet(List list, Comparator comparator) { + private static TreeSet treeSet(ArrayList list, Comparator comparator) { TreeSet sortedSet = new TreeSet(comparator); sortedSet.addAll(list); return sortedSet; } /** - * Return a sorted set corresponding to the specified array. + * Return a new tree (sorted) set corresponding to the specified array. */ - public static > TreeSet sortedSet(E... array) { - return sortedSet(array, null); + public static > TreeSet treeSet(E... array) { + return treeSet(array, null); } /** - * Return a sorted set corresponding to the specified array + * Return a new tree (sorted) set corresponding to the specified array * and comparator. */ - public static TreeSet sortedSet(E[] array, Comparator comparator) { + public static TreeSet treeSet(E[] array, Comparator comparator) { TreeSet sortedSet = new TreeSet(comparator); sortedSet.addAll(Arrays.asList(array)); return sortedSet; } - /** - * Return a sorted set corresponding to the specified queue, - * draining the queue in the process. - */ - public static TreeSet sortedSet(Queue queue) { - return sortedSet(queue, null); - } - - /** - * Return a sorted set corresponding to the specified queue, - * draining the queue in the process. - * The specified queue size is a performance hint. - */ - public static TreeSet sortedSet(Queue queue, int queueSize) { - return sortedSet(queue, null, queueSize); - } - - /** - * Return a sorted set corresponding to the specified queue and comparator, - * draining the queue in the process. - * The specified queue size is a performance hint. - */ - public static TreeSet sortedSet(Queue queue, Comparator comparator) { - return sortedSet(ListTools.list(queue), comparator); - } - - /** - * Return a sorted set corresponding to the specified queue and comparator, - * draining the queue in the process. - * The specified queue size is a performance hint. - */ - public static TreeSet sortedSet(Queue queue, Comparator comparator, int queueSize) { - return sortedSet(ListTools.list(queue, queueSize), comparator); - } - - /** - * Return a sorted set corresponding to the specified stack, - * draining the stack in the process. - */ - public static TreeSet sortedSet(Stack stack) { - return sortedSet(stack, null); - } - - /** - * Return a sorted set corresponding to the specified stack, - * draining the stack in the process. - * The specified stack size is a performance hint. - */ - public static TreeSet sortedSet(Stack stack, int stackSize) { - return sortedSet(stack, null, stackSize); - } - - /** - * Return a sorted set corresponding to the specified stack and comparator, - * draining the stack in the process. - */ - public static TreeSet sortedSet(Stack stack, Comparator comparator) { - return sortedSet(ListTools.list(stack), comparator); - } - - /** - * Return a sorted set corresponding to the specified stack and comparator, - * draining the stack in the process. - * The specified stack size is a performance hint. - */ - public static TreeSet sortedSet(Stack stack, Comparator comparator, int stackSize) { - return sortedSet(ListTools.list(stack, stackSize), comparator); - } - // ********** Old School Vector factory methods ********** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyQueue.java deleted file mode 100644 index 074e885f3e..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyQueue.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; - -/** - * Empty implementation of the {@link Queue} interface. - * @param the type of elements maintained by the queue - * @see QueueTools - */ -public final class EmptyQueue - implements Queue, Serializable -{ - @SuppressWarnings("rawtypes") - public static final Queue INSTANCE = new EmptyQueue(); - @SuppressWarnings("unchecked") - public static Queue instance() { - return INSTANCE; - } - - // ensure single instance - private EmptyQueue() { - super(); - } - - public void enqueue(E o) { - throw new UnsupportedOperationException(); - } - - public E dequeue() { - throw new NoSuchElementException(); - } - - public E peek() { - throw new NoSuchElementException(); - } - - public boolean isEmpty() { - return true; - } - - @Override - public String toString() { - return "[]"; //$NON-NLS-1$ - } - - private static final long serialVersionUID = 1L; - private Object readResolve() { - // replace this object with the singleton - return INSTANCE; - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyStack.java deleted file mode 100644 index e1ed4b3027..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/EmptyStack.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.EmptyStackException; -import org.eclipse.jpt.common.utility.collection.Stack; - -/** - * Empty implementation of the {@link Stack} interface. - * @param the type of elements maintained by the stack - * @see StackTools - */ -public final class EmptyStack - implements Stack, Serializable -{ - @SuppressWarnings("rawtypes") - public static final Stack INSTANCE = new EmptyStack(); - @SuppressWarnings("unchecked") - public static Stack instance() { - return INSTANCE; - } - - // ensure single instance - private EmptyStack() { - super(); - } - - public void push(E element) { - throw new UnsupportedOperationException(); - } - - public E pop() { - throw new EmptyStackException(); - } - - public E peek() { - throw new EmptyStackException(); - } - - public boolean isEmpty() { - return true; - } - - @Override - public String toString() { - return "[]"; //$NON-NLS-1$ - } - - private static final long serialVersionUID = 1L; - private Object readResolve() { - // replace this object with the singleton - return INSTANCE; - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayQueue.java deleted file mode 100644 index 1308adf523..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayQueue.java +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.ObjectTools; - -/** - * Fixed-sized array FIFO implementation of the {@link Queue} interface. - * This implementation will throw an exception if its capacity is exceeded. - * @param the type of elements maintained by the queue - * @see ArrayQueue - * @see QueueTools - */ -public class FixedSizeArrayQueue - implements Queue, Cloneable, Serializable -{ - private final E[] elements; - - /** Index of next element to be "dequeued". */ - private int head = 0; - - /** Index of next element to be "enqueued". */ - private int tail = 0; - - private int size = 0; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct an empty queue with the specified capacity. - */ - @SuppressWarnings("unchecked") - public FixedSizeArrayQueue(int capacity) { - super(); - if (capacity < 0) { - throw new IllegalArgumentException("Illegal capacity: " + capacity); //$NON-NLS-1$ - } - this.elements = (E[]) new Object[capacity]; - } - - - // ********** Queue implementation ********** - - /** - * @exception IllegalStateException if the queue is full - */ - public void enqueue(E element) { - if (this.isFull()) { - throw new IllegalStateException("Queue is full."); //$NON-NLS-1$ - } - this.elements[this.tail] = element; - if (++this.tail == this.elements.length) { - this.tail = 0; - } - this.size++; - } - - public E dequeue() { - if (this.size == 0) { - throw new NoSuchElementException(); - } - E element = this.elements[this.head]; - this.elements[this.head] = null; // allow GC to work - if (++this.head == this.elements.length) { - this.head = 0; - } - this.size--; - return element; - } - - public E peek() { - if (this.size == 0) { - throw new NoSuchElementException(); - } - return this.elements[this.head]; - } - - public boolean isEmpty() { - return this.size == 0; - } - - /** - * Return whether the queue is full, - * as its capacity is fixed. - */ - public boolean isFull() { - return this.size == this.elements.length; - } - - - // ********** standard methods ********** - - @Override - public FixedSizeArrayQueue clone() { - int len = this.elements.length; - FixedSizeArrayQueue clone = new FixedSizeArrayQueue(len); - System.arraycopy(this.elements, 0, clone.elements, 0, len); - clone.head = this.head; - clone.tail = this.tail; - clone.size = this.size; - return clone; - } - - @Override - public String toString() { - return Arrays.toString(this.copyElements()); - } - - private Object[] copyElements() { - if (this.size == 0) { - return ObjectTools.EMPTY_OBJECT_ARRAY; - } - Object[] result = new Object[this.size]; - if ((this.head == 0) || (this.head < this.tail) || (this.tail == 0)) { - // elements are contiguous - System.arraycopy(this.elements, this.head, result, 0, this.size); - } else { - // elements wrap past end of array - int fragmentSize = this.elements.length - this.head; - System.arraycopy(this.elements, this.head, result, 0, fragmentSize); - System.arraycopy(this.elements, 0, result, fragmentSize, (this.size - fragmentSize)); - } - return result; - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayStack.java deleted file mode 100644 index 3eec5f9028..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/FixedSizeArrayStack.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.EmptyStackException; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.ObjectTools; - -/** - * Fixed-size array LIFO implementation of the {@link Stack} interface. - * This implementation will throw an exception if its capacity is exceeded. - * @param the type of elements maintained by the stack - * @see ArrayStack - * @see StackTools - */ -public class FixedSizeArrayStack - implements Stack, Cloneable, Serializable -{ - private E[] elements; - - /** The index of where the next "pushed" element will go. */ - private int next = 0; - - private int size = 0; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct an empty stack with the specified capacity. - */ - @SuppressWarnings("unchecked") - public FixedSizeArrayStack(int capacity) { - super(); - if (capacity < 0) { - throw new IllegalArgumentException("Illegal capacity: " + capacity); //$NON-NLS-1$ - } - this.elements = (E[]) new Object[capacity]; - } - - - // ********** Stack implementation ********** - - public void push(E element) { - if (this.isFull()) { - throw new IllegalStateException("Stack is full."); //$NON-NLS-1$ - } - this.elements[this.next] = element; - if (++this.next == this.elements.length) { - this.next = 0; - } - this.size++; - } - - public E pop() { - if (this.size == 0) { - throw new EmptyStackException(); - } - int index = this.next; - if (index == 0) { - index = this.elements.length; - } - index--; - E element = this.elements[index]; - this.elements[index] = null; // allow GC to work - this.next = index; - this.size--; - return element; - } - - public E peek() { - if (this.size == 0) { - throw new EmptyStackException(); - } - int index = this.next; - if (index == 0) { - index = this.elements.length; - } - index--; - return this.elements[index]; - } - - public boolean isEmpty() { - return this.size == 0; - } - - /** - * Return whether the stack is full, - * as its capacity is fixed. - */ - public boolean isFull() { - return this.size == this.elements.length; - } - - - // ********** standard methods ********** - - @Override - public FixedSizeArrayStack clone() { - int len = this.elements.length; - FixedSizeArrayStack clone = new FixedSizeArrayStack(len); - System.arraycopy(this.elements, 0, clone.elements, 0, len); - clone.next = this.next; - clone.size = this.size; - return clone; - } - - /** - * Print the elements in the order in which they are "pushed" on to - * the stack (as opposed to the order in which they will be "popped" - * off of the stack). - */ - @Override - public String toString() { - return Arrays.toString(this.copyElements()); - } - - private Object[] copyElements() { - if (this.size == 0) { - return ObjectTools.EMPTY_OBJECT_ARRAY; - } - Object[] result = new Object[this.size]; - if (this.next >= this.size) { - // elements are contiguous, but not to end of array - System.arraycopy(this.elements, (this.next - this.size), result, 0, this.size); - } else if (this.next == 0) { - // elements are contiguous to end of array - System.arraycopy(this.elements, (this.elements.length - this.size), result, 0, this.size); - } else { - // elements wrap past end of array - int fragmentSize = this.size - this.next; - System.arraycopy(this.elements, (this.elements.length - fragmentSize), result, 0, fragmentSize); - System.arraycopy(this.elements, 0, result, fragmentSize, (this.size - fragmentSize)); - } - return result; - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/HashBag.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/HashBag.java index cacf9d5715..4c98665bfb 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/HashBag.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/HashBag.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -76,7 +76,7 @@ public class HashBag implements Bag, Cloneable, Serializable { /** The hash table. Resized as necessary. Length MUST Always be a power of two. */ - transient Entry[] table; + transient Entry[] table; /** The total number of entries in the bag. */ transient int size = 0; @@ -254,7 +254,7 @@ public class HashBag private void add_(E o, int cnt) { int hash = this.hash(o); int index = this.index(hash); - for (Entry e = this.table[index]; e != null; e = e.next) { + for (Entry e = this.table[index]; e != null; e = e.next) { Object eo; if ((e.hash == hash) && (((eo = e.object) == o) || ((o != null) && o.equals(eo)))) { e.count += cnt; @@ -264,7 +264,7 @@ public class HashBag } // create the new entry and put it in the table - Entry e = this.buildEntry(hash, o, cnt, this.table[index]); + Entry e = this.buildEntry(hash, o, cnt, this.table[index]); this.table[index] = e; this.size += cnt; this.uniqueCount++; @@ -291,9 +291,9 @@ public class HashBag * the object's hash code and examining the entries in the corresponding hash * table bucket. */ - private Entry getEntry(Object o) { + private Entry getEntry(Object o) { int hash = this.hash(o); - for (Entry e = this.table[this.index(hash)]; e != null; e = e.next) { + for (Entry e = this.table[this.index(hash)]; e != null; e = e.next) { Object eo; if ((e.hash == hash) && (((eo = e.object) == o) || ((o != null) && o.equals(eo)))) { return e; @@ -308,7 +308,7 @@ public class HashBag } public int count(Object o) { - Entry e = this.getEntry(o); + Entry e = this.getEntry(o); return (e == null) ? 0 : e.count; } @@ -319,7 +319,7 @@ public class HashBag * capacity and load factor. */ private void rehash() { - Entry[] oldTable = this.table; + Entry[] oldTable = this.table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { @@ -328,11 +328,11 @@ public class HashBag } int newCapacity = 2 * oldCapacity; - Entry[] newTable = this.buildTable(newCapacity); + Entry[] newTable = this.buildTable(newCapacity); for (int i = oldCapacity; i-- > 0; ) { - for (Entry old = oldTable[i]; old != null; ) { - Entry e = old; + for (Entry old = oldTable[i]; old != null; ) { + Entry e = old; old = old.next; int index = this.index(e.hash, newCapacity); @@ -347,8 +347,8 @@ public class HashBag // minimize scope of suppressed warnings @SuppressWarnings("unchecked") - private Entry[] buildTable(int capacity) { - return new Entry[capacity]; + private Entry[] buildTable(int capacity) { + return new HashBag.Entry[capacity]; } /** @@ -375,7 +375,7 @@ public class HashBag int index = this.index(hash); // if the object is already in the bag, simply bump its count - for (Entry e = this.table[index]; e != null; e = e.next) { + for (Entry e = this.table[index]; e != null; e = e.next) { Object eo; if ((e.hash == hash) && (((eo = e.object) == o) || ((o != null) && o.equals(eo)))) { e.count += cnt; @@ -391,7 +391,7 @@ public class HashBag } // create the new entry and put it in the table - Entry e = this.buildEntry(hash, o, cnt, this.table[index]); + Entry e = this.buildEntry(hash, o, cnt, this.table[index]); this.table[index] = e; this.size += cnt; this.uniqueCount++; @@ -399,9 +399,9 @@ public class HashBag } // minimize scope of suppressed warnings - @SuppressWarnings({ "rawtypes", "unchecked" } ) - private Entry buildEntry(int hash, Object o, int cnt, Entry next) { - return new Entry(hash, (E) o, cnt, (Entry) next); + @SuppressWarnings("unchecked") + private Entry buildEntry(int hash, Object o, int cnt, Entry next) { + return new Entry(hash, (E) o, cnt, next); } /** @@ -426,7 +426,7 @@ public class HashBag int hash = this.hash(o); int index = this.index(hash); - for (Entry e = this.table[index], prev = null; e != null; prev = e, e = e.next) { + for (Entry e = this.table[index], prev = null; e != null; prev = e, e = e.next) { Object eo; if ((e.hash == hash) && (((eo = e.object) == o) || ((o != null) && o.equals(eo)))) { this.modCount++; @@ -454,7 +454,7 @@ public class HashBag */ @Override public void clear() { - Entry[] tab = this.table; + Entry[] tab = this.table; this.modCount++; for (int i = tab.length; i-- > 0; ) { tab[i] = null; @@ -489,15 +489,15 @@ public class HashBag /** * Hash table collision list entry. */ - private static class Entry + private class Entry implements Bag.Entry { final int hash; final E object; int count; - Entry next; + Entry next; - Entry(int hash, E object, int count, Entry next) { + Entry(int hash, E object, int count, Entry next) { this.hash = hash; this.object = object; this.count = count; @@ -519,6 +519,7 @@ public class HashBag } int old = this.count; this.count = count; + HashBag.this.size += (count - old); return old; } @@ -599,9 +600,9 @@ public class HashBag implements Iterator { private int index = HashBag.this.table.length; // start at the end of the table - private Entry nextEntry = null; + private Entry nextEntry = null; private int nextEntryCount = 0; - private Entry lastReturnedEntry = null; + private Entry lastReturnedEntry = null; /** * The modCount value that the iterator believes that the backing @@ -615,9 +616,9 @@ public class HashBag } public boolean hasNext() { - Entry e = this.nextEntry; + Entry e = this.nextEntry; int i = this.index; - Entry[] tab = HashBag.this.table; + Entry[] tab = HashBag.this.table; // Use locals for faster loop iteration while ((e == null) && (i > 0)) { e = tab[--i]; // move backwards through the table @@ -631,9 +632,9 @@ public class HashBag if (HashBag.this.modCount != this.expectedModCount) { throw new ConcurrentModificationException(); } - Entry et = this.nextEntry; + Entry et = this.nextEntry; int i = this.index; - Entry[] tab = HashBag.this.table; + Entry[] tab = HashBag.this.table; // Use locals for faster loop iteration while ((et == null) && (i > 0)) { et = tab[--i]; // move backwards through the table @@ -643,7 +644,7 @@ public class HashBag if (et == null) { throw new NoSuchElementException(); } - Entry e = this.lastReturnedEntry = this.nextEntry; + Entry e = this.lastReturnedEntry = this.nextEntry; this.nextEntryCount++; if (this.nextEntryCount == e.count) { this.nextEntry = e.next; @@ -660,7 +661,7 @@ public class HashBag throw new ConcurrentModificationException(); } int slot = HashBag.this.index(this.lastReturnedEntry.hash, HashBag.this.table.length); - for (Entry e = HashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { + for (Entry e = HashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { if (e == this.lastReturnedEntry) { HashBag.this.modCount++; this.expectedModCount++; @@ -688,11 +689,11 @@ public class HashBag private class EntryIterator - implements Iterator> + implements Iterator { private int index = HashBag.this.table.length; // start at the end of the table - private Entry nextEntry = null; - private Entry lastReturnedEntry = null; + private Entry nextEntry = null; + private Entry lastReturnedEntry = null; /** * The modCount value that the iterator believes that the backing @@ -706,9 +707,9 @@ public class HashBag } public boolean hasNext() { - Entry e = this.nextEntry; + Entry e = this.nextEntry; int i = this.index; - Entry[] tab = HashBag.this.table; + Entry[] tab = HashBag.this.table; // Use locals for faster loop iteration while ((e == null) && (i > 0)) { e = tab[--i]; // move backwards through the table @@ -718,13 +719,13 @@ public class HashBag return e != null; } - public Entry next() { + public Entry next() { if (HashBag.this.modCount != this.expectedModCount) { throw new ConcurrentModificationException(); } - Entry et = this.nextEntry; + Entry et = this.nextEntry; int i = this.index; - Entry[] tab = HashBag.this.table; + Entry[] tab = HashBag.this.table; // Use locals for faster loop iteration while ((et == null) && (i > 0)) { et = tab[--i]; // move backwards through the table @@ -734,7 +735,7 @@ public class HashBag if (et == null) { throw new NoSuchElementException(); } - Entry e = this.lastReturnedEntry = this.nextEntry; + Entry e = this.lastReturnedEntry = this.nextEntry; this.nextEntry = e.next; return e; } @@ -747,7 +748,7 @@ public class HashBag throw new ConcurrentModificationException(); } int slot = HashBag.this.index(this.lastReturnedEntry.hash, HashBag.this.table.length); - for (Entry e = HashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { + for (Entry e = HashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { if (e == this.lastReturnedEntry) { HashBag.this.modCount++; this.expectedModCount++; @@ -848,7 +849,7 @@ public class HashBag // write out elements and counts (alternating) if (this.uniqueCount > 0) { - for (Entry entry : this.table) { + for (Entry entry : this.table) { while (entry != null) { s.writeObject(entry.object); s.writeInt(entry.count); diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/IdentityHashBag.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/IdentityHashBag.java index ef7b4135ee..203bb140ca 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/IdentityHashBag.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/IdentityHashBag.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -92,7 +92,7 @@ public class IdentityHashBag implements Bag, Cloneable, Serializable { /** The hash table. Resized as necessary. Length MUST Always be a power of two. */ - transient Entry[] table; + transient Entry[] table; /** The total number of entries in the bag. */ transient int size = 0; @@ -277,7 +277,7 @@ public class IdentityHashBag private void add_(E o, int cnt) { int hash = this.hash(o); int index = this.index(hash); - for (Entry e = this.table[index]; e != null; e = e.next) { + for (Entry e = this.table[index]; e != null; e = e.next) { if (e.object == o) { e.count += cnt; this.size += cnt; @@ -286,7 +286,7 @@ public class IdentityHashBag } // create the new entry and put it in the table - Entry e = this.buildEntry(hash, o, cnt, this.table[index]); + Entry e = this.buildEntry(hash, o, cnt, this.table[index]); this.table[index] = e; this.size += cnt; this.uniqueCount++; @@ -313,8 +313,8 @@ public class IdentityHashBag * the object's identity hash code and examining the entries in the corresponding hash * table bucket. */ - private Entry getEntry(Object o) { - for (Entry e = this.table[this.index(o)]; e != null; e = e.next) { + private Entry getEntry(Object o) { + for (Entry e = this.table[this.index(o)]; e != null; e = e.next) { if (e.object == o) { return e; } @@ -328,7 +328,7 @@ public class IdentityHashBag } public int count(Object o) { - Entry e = this.getEntry(o); + Entry e = this.getEntry(o); return (e == null) ? 0 : e.count; } @@ -339,7 +339,7 @@ public class IdentityHashBag * capacity and load factor. */ private void rehash() { - Entry[] oldTable = this.table; + Entry[] oldTable = this.table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { @@ -348,11 +348,11 @@ public class IdentityHashBag } int newCapacity = 2 * oldCapacity; - Entry[] newTable = this.buildTable(newCapacity); + Entry[] newTable = this.buildTable(newCapacity); for (int i = oldCapacity; i-- > 0; ) { - for (Entry old = oldTable[i]; old != null; ) { - Entry e = old; + for (Entry old = oldTable[i]; old != null; ) { + Entry e = old; old = old.next; int index = this.index(e.hash, newCapacity); @@ -367,8 +367,8 @@ public class IdentityHashBag // minimize scope of suppressed warnings @SuppressWarnings("unchecked") - private Entry[] buildTable(int capacity) { - return new Entry[capacity]; + private Entry[] buildTable(int capacity) { + return new IdentityHashBag.Entry[capacity]; } /** @@ -395,7 +395,7 @@ public class IdentityHashBag int index = this.index(hash); // if the object is already in the bag, simply bump its count - for (Entry e = this.table[index]; e != null; e = e.next) { + for (Entry e = this.table[index]; e != null; e = e.next) { if (e.object == o) { e.count += cnt; this.size += cnt; @@ -410,7 +410,7 @@ public class IdentityHashBag } // create the new entry and put it in the table - Entry e = this.buildEntry(hash, o, cnt, this.table[index]); + Entry e = this.buildEntry(hash, o, cnt, this.table[index]); this.table[index] = e; this.size += cnt; this.uniqueCount++; @@ -418,9 +418,9 @@ public class IdentityHashBag } // minimize scope of suppressed warnings - @SuppressWarnings({ "unchecked", "rawtypes" }) - private Entry buildEntry(int hash, Object o, int cnt, Entry next) { - return new Entry(hash, (E) o, cnt, (Entry) next); + @SuppressWarnings("unchecked") + private Entry buildEntry(int hash, Object o, int cnt, Entry next) { + return new Entry(hash, (E) o, cnt, next); } /** @@ -444,7 +444,7 @@ public class IdentityHashBag } int index = this.index(o); - for (Entry e = this.table[index], prev = null; e != null; prev = e, e = e.next) { + for (Entry e = this.table[index], prev = null; e != null; prev = e, e = e.next) { if (e.object == o) { this.modCount++; cnt = (cnt < e.count) ? cnt : e.count; @@ -489,7 +489,7 @@ public class IdentityHashBag */ @Override public void clear() { - Entry[] tab = this.table; + Entry[] tab = this.table; this.modCount++; for (int i = tab.length; i-- > 0; ) { tab[i] = null; @@ -524,15 +524,15 @@ public class IdentityHashBag /** * Hash table collision list entry. */ - private static class Entry + private class Entry implements Bag.Entry { final int hash; // cache the hash for re-hashes final E object; int count; - Entry next; + Entry next; - Entry(int hash, E object, int count, Entry next) { + Entry(int hash, E object, int count, Entry next) { this.hash = hash; this.object = object; this.count = count; @@ -554,6 +554,7 @@ public class IdentityHashBag } int old = this.count; this.count = count; + IdentityHashBag.this.size += (count - old); return old; } @@ -634,9 +635,9 @@ public class IdentityHashBag implements Iterator { private int index = IdentityHashBag.this.table.length; // start at the end of the table - private Entry nextEntry = null; + private Entry nextEntry = null; private int nextEntryCount = 0; - private Entry lastReturnedEntry = null; + private Entry lastReturnedEntry = null; /** * The modCount value that the iterator believes that the backing @@ -650,9 +651,9 @@ public class IdentityHashBag } public boolean hasNext() { - Entry e = this.nextEntry; + Entry e = this.nextEntry; int i = this.index; - Entry[] tab = IdentityHashBag.this.table; + Entry[] tab = IdentityHashBag.this.table; // Use locals for faster loop iteration while ((e == null) && (i > 0)) { e = tab[--i]; // move backwards through the table @@ -666,9 +667,9 @@ public class IdentityHashBag if (IdentityHashBag.this.modCount != this.expectedModCount) { throw new ConcurrentModificationException(); } - Entry et = this.nextEntry; + Entry et = this.nextEntry; int i = this.index; - Entry[] tab = IdentityHashBag.this.table; + Entry[] tab = IdentityHashBag.this.table; // Use locals for faster loop iteration while ((et == null) && (i > 0)) { et = tab[--i]; // move backwards through the table @@ -678,7 +679,7 @@ public class IdentityHashBag if (et == null) { throw new NoSuchElementException(); } - Entry e = this.lastReturnedEntry = this.nextEntry; + Entry e = this.lastReturnedEntry = this.nextEntry; this.nextEntryCount++; if (this.nextEntryCount == e.count) { this.nextEntry = e.next; @@ -695,7 +696,7 @@ public class IdentityHashBag throw new ConcurrentModificationException(); } int slot = IdentityHashBag.this.index(this.lastReturnedEntry.hash, IdentityHashBag.this.table.length); - for (Entry e = IdentityHashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { + for (Entry e = IdentityHashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { if (e == this.lastReturnedEntry) { IdentityHashBag.this.modCount++; this.expectedModCount++; @@ -723,11 +724,11 @@ public class IdentityHashBag private class EntryIterator - implements Iterator> + implements Iterator { private int index = IdentityHashBag.this.table.length; // start at the end of the table - private Entry nextEntry = null; - private Entry lastReturnedEntry = null; + private Entry nextEntry = null; + private Entry lastReturnedEntry = null; /** * The modCount value that the iterator believes that the backing @@ -741,9 +742,9 @@ public class IdentityHashBag } public boolean hasNext() { - Entry e = this.nextEntry; + Entry e = this.nextEntry; int i = this.index; - Entry[] tab = IdentityHashBag.this.table; + Entry[] tab = IdentityHashBag.this.table; // Use locals for faster loop iteration while ((e == null) && (i > 0)) { e = tab[--i]; // move backwards through the table @@ -753,13 +754,13 @@ public class IdentityHashBag return e != null; } - public Entry next() { + public Entry next() { if (IdentityHashBag.this.modCount != this.expectedModCount) { throw new ConcurrentModificationException(); } - Entry et = this.nextEntry; + Entry et = this.nextEntry; int i = this.index; - Entry[] tab = IdentityHashBag.this.table; + Entry[] tab = IdentityHashBag.this.table; // Use locals for faster loop iteration while ((et == null) && (i > 0)) { et = tab[--i]; // move backwards through the table @@ -769,7 +770,7 @@ public class IdentityHashBag if (et == null) { throw new NoSuchElementException(); } - Entry e = this.lastReturnedEntry = this.nextEntry; + Entry e = this.lastReturnedEntry = this.nextEntry; this.nextEntry = e.next; return e; } @@ -782,7 +783,7 @@ public class IdentityHashBag throw new ConcurrentModificationException(); } int slot = IdentityHashBag.this.index(this.lastReturnedEntry.hash, IdentityHashBag.this.table.length); - for (Entry e = IdentityHashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { + for (Entry e = IdentityHashBag.this.table[slot], prev = null; e != null; prev = e, e = e.next) { if (e == this.lastReturnedEntry) { IdentityHashBag.this.modCount++; this.expectedModCount++; @@ -887,7 +888,7 @@ public class IdentityHashBag // write out elements and counts (alternating) if (this.uniqueCount > 0) { - for (Entry entry : this.table) { + for (Entry entry : this.table) { while (entry != null) { s.writeObject(entry.object); s.writeInt(entry.count); diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedQueue.java deleted file mode 100644 index ee07946479..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedQueue.java +++ /dev/null @@ -1,273 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.ObjectTools; - -/** - * Linked FIFO implementation of the {@link Queue} interface. - * @param the type of elements maintained by the queue - * @see QueueTools - */ -public class LinkedQueue - implements Queue, Cloneable, Serializable -{ - private final NodeFactory nodeFactory; - private transient Node head; // next element to dequeue - private transient Node tail; // last element - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct an empty queue with no node cache. - */ - public LinkedQueue() { - this(0); - } - - /** - * Construct an empty queue with a node cache with the specified size. - * Specify a cache size of -1 for an unlimited cache. - */ - public LinkedQueue(int cacheSize) { - this(LinkedQueue.buildNodeFactory(cacheSize)); - this.head = null; - } - - private static NodeFactory buildNodeFactory(int cacheSize) { - if (cacheSize < -1) { - throw new IllegalArgumentException("Cache size must be greater than or equal to -1: " + cacheSize); //$NON-NLS-1$ - } - return (cacheSize == 0) ? SimpleNodeFactory.instance() : new CachingNodeFactory(cacheSize); - } - - private LinkedQueue(NodeFactory nodeFactory) { - super(); - this.nodeFactory = nodeFactory; - this.head = null; - this.tail = null; - } - - - // ********** Queue implementation ********** - - public void enqueue(E element) { - Node newNode = this.nodeFactory.buildNode(element, null); - if (this.tail == null) { - this.head = newNode; // first node - } else { - this.tail.next = newNode; - } - this.tail = newNode; - } - - public E dequeue() { - if (this.head == null) { - throw new NoSuchElementException(); - } - Node node = this.head; - this.head = node.next; - if (this.head == null) { - this.tail = null; // last node - } - E element = node.element; - this.nodeFactory.release(node); - return element; - } - - public E peek() { - if (this.head == null) { - throw new NoSuchElementException(); - } - return this.head.element; - } - - public boolean isEmpty() { - return this.head == null; - } - - - // ********** standard methods ********** - - @Override - public LinkedQueue clone() { - LinkedQueue clone = new LinkedQueue(this.nodeFactory.copy()); - E[] elements = this.buildElements(); - for (E element : elements) { - clone.enqueue(element); - } - return clone; - } - - @SuppressWarnings("unchecked") - private E[] buildElements() { - int size = this.size(); - if (size == 0) { - return (E[]) ObjectTools.EMPTY_OBJECT_ARRAY; - } - E[] elements = (E[]) new Object[size]; - int i = 0; - for (Node node = this.head; node != null; node = node.next) { - elements[i++] = node.element; - } - return elements; - } - - private int size() { - int size = 0; - for (Node node = this.head; node != null; node = node.next) { - size++; - } - return size; - } - - @Override - public String toString() { - return Arrays.toString(this.buildElements()); - } - - - // ********** Serializable "implementation" ********** - - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { - // write nodeFactory (and any hidden stuff) - stream.defaultWriteObject(); - Object[] elements = this.buildElements(); - stream.writeInt(elements.length); - for (Object element : elements) { - stream.writeObject(element); - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { - // read nodeFactory (and any hidden stuff) - stream.defaultReadObject(); - int len = stream.readInt(); - for (int i = len; i-- > 0; ) { - this.enqueue((E) stream.readObject()); - } - } - - - // ********** Node classes ********** - - private static final class Node { - E element; - Node next; - - Node(E element, Node next) { - super(); - this.element = element; - this.next = next; - } - - @Override - public String toString() { - return ObjectTools.toString(this, this.element); - } - } - - private abstract static class NodeFactory { - NodeFactory() { - super(); - } - - Node buildNode(E element, Node next) { - return new Node(element, next); - } - - abstract void release(Node node); - - abstract NodeFactory copy(); - } - - private static class SimpleNodeFactory - extends NodeFactory - implements Serializable - { - @SuppressWarnings("rawtypes") - public static final NodeFactory INSTANCE = new SimpleNodeFactory(); - @SuppressWarnings("unchecked") - public static NodeFactory instance() { - return INSTANCE; - } - - private SimpleNodeFactory() { - super(); - } - - @Override - void release(Node node) { - // NOP - } - - @Override - NodeFactory copy() { - return this; - } - - private static final long serialVersionUID = 1L; - private Object readResolve() { - // replace this object with the singleton - return INSTANCE; - } - } - - private static final class CachingNodeFactory - extends NodeFactory - implements Serializable - { - private final int maxCacheSize; - private transient int cacheSize = 0; - private transient Node cacheHead; - private static final long serialVersionUID = 1L; - - CachingNodeFactory(int maxCacheSize) { - super(); - this.maxCacheSize = maxCacheSize; - } - - @Override - Node buildNode(E element, Node next) { - if (this.cacheHead == null) { - return super.buildNode(element, next); - } - Node node = this.cacheHead; - this.cacheHead = node.next; - this.cacheSize--; - node.element = element; - node.next = next; - return node; - } - - @Override - void release(Node node) { - if ((this.maxCacheSize == -1) || (this.cacheSize < this.maxCacheSize)) { - node.element = null; // allow GC to work - node.next = this.cacheHead; - this.cacheHead = node; - this.cacheSize++; - } - } - - @Override - NodeFactory copy() { - return new CachingNodeFactory(this.maxCacheSize); - } - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedStack.java deleted file mode 100644 index 97456c6753..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/LinkedStack.java +++ /dev/null @@ -1,264 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.EmptyStackException; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.ObjectTools; - -/** - * Linked LIFO implementation of the {@link Stack} interface. - * @param the type of elements maintained by the stack - * @see StackTools - */ -public class LinkedStack - implements Stack, Cloneable, Serializable -{ - private final NodeFactory nodeFactory; - private transient Node head; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct an empty stack with no node cache. - */ - public LinkedStack() { - this(0); - } - - /** - * Construct an empty stack with a node cache with the specified size. - * Specify a cache size of -1 for an unlimited cache. - */ - public LinkedStack(int cacheSize) { - this(LinkedStack.buildNodeFactory(cacheSize)); - this.head = null; - } - - private static NodeFactory buildNodeFactory(int cacheSize) { - if (cacheSize < -1) { - throw new IllegalArgumentException("Cache size must be greater than or equal to -1: " + cacheSize); //$NON-NLS-1$ - } - return (cacheSize == 0) ? SimpleNodeFactory.instance() : new CachingNodeFactory(cacheSize); - } - - private LinkedStack(NodeFactory nodeFactory) { - super(); - this.nodeFactory = nodeFactory; - this.head = null; - } - - - // ********** Stack implementation ********** - - public void push(E element) { - this.head = this.nodeFactory.buildNode(element, this.head); - } - - public E pop() { - if (this.head == null) { - throw new EmptyStackException(); - } - Node node = this.head; - this.head = node.next; - E element = node.element; - this.nodeFactory.release(node); - return element; - } - - public E peek() { - if (this.head == null) { - throw new EmptyStackException(); - } - return this.head.element; - } - - public boolean isEmpty() { - return this.head == null; - } - - - // ********** standard methods ********** - - @Override - public LinkedStack clone() { - LinkedStack clone = new LinkedStack(this.nodeFactory.copy()); - E[] elements = this.buildElements(); - for (int i = elements.length; i-- > 0; ) { - clone.push(elements[i]); - } - return clone; - } - - @SuppressWarnings("unchecked") - private E[] buildElements() { - int size = this.size(); - if (size == 0) { - return (E[]) ObjectTools.EMPTY_OBJECT_ARRAY; - } - E[] elements = (E[]) new Object[size]; - int i = 0; - for (Node node = this.head; node != null; node = node.next) { - elements[i++] = node.element; - } - return elements; - } - - private int size() { - int size = 0; - for (Node node = this.head; node != null; node = node.next) { - size++; - } - return size; - } - - @Override - public String toString() { - return Arrays.toString(this.buildElements()); - } - - - // ********** Serializable "implementation" ********** - - private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { - // write nodeFactory (and any hidden stuff) - stream.defaultWriteObject(); - Object[] elements = this.buildElements(); - int len = elements.length; - stream.writeInt(len); - // write elements in reverse order so they can be pushed as read - for (int i = len; i-- > 0; ) { - stream.writeObject(elements[i]); - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { - // read nodeFactory (and any hidden stuff) - stream.defaultReadObject(); - int len = stream.readInt(); - for (int i = len; i-- > 0; ) { - this.push((E) stream.readObject()); - } - } - - - // ********** Node classes ********** - - private static final class Node { - E element; - Node next; - - Node(E element, Node next) { - super(); - this.element = element; - this.next = next; - } - - @Override - public String toString() { - return ObjectTools.toString(this, this.element); - } - } - - private abstract static class NodeFactory { - NodeFactory() { - super(); - } - - Node buildNode(E element, Node next) { - return new Node(element, next); - } - - abstract void release(Node node); - - abstract NodeFactory copy(); - } - - private static class SimpleNodeFactory - extends NodeFactory - implements Serializable - { - @SuppressWarnings("rawtypes") - public static final NodeFactory INSTANCE = new SimpleNodeFactory(); - @SuppressWarnings("unchecked") - public static NodeFactory instance() { - return INSTANCE; - } - - private SimpleNodeFactory() { - super(); - } - - @Override - void release(Node node) { - // NOP - } - - @Override - NodeFactory copy() { - return this; - } - - private static final long serialVersionUID = 1L; - private Object readResolve() { - // replace this object with the singleton - return INSTANCE; - } - } - - private static final class CachingNodeFactory - extends NodeFactory - implements Serializable - { - private final int maxCacheSize; - private transient int cacheSize = 0; - private transient Node cacheHead; - private static final long serialVersionUID = 1L; - - CachingNodeFactory(int maxCacheSize) { - super(); - this.maxCacheSize = maxCacheSize; - } - - @Override - Node buildNode(E element, Node next) { - if (this.cacheHead == null) { - return super.buildNode(element, next); - } - Node node = this.cacheHead; - this.cacheHead = node.next; - this.cacheSize--; - node.element = element; - node.next = next; - return node; - } - - @Override - void release(Node node) { - if ((this.maxCacheSize == -1) || (this.cacheSize < this.maxCacheSize)) { - node.element = null; // allow GC to work - node.next = this.cacheHead; - this.cacheHead = node; - this.cacheSize++; - } - } - - @Override - NodeFactory copy() { - return new CachingNodeFactory(this.maxCacheSize); - } - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListQueue.java deleted file mode 100644 index c119164dd1..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListQueue.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.List; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; - -/** - * Adapt a {@link List} to the {@link Queue} interface. - * Elements are dequeued from the front of the list (i.e. index 0). - * @param the type of elements maintained by the queue - * @see QueueTools - */ -public class ListQueue - implements Queue, Serializable -{ - private List list; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct a queue, adapting the specified list. - * The queue will dequeue its elements in the same - * order they are returned by the list's iterator (i.e. the - * first element returned by the list's iterator will be the - * first element returned by {@link #dequeue()}). - */ - public ListQueue(List list) { - super(); - this.list = list; - } - - - // ********** Queue implementation ********** - - public void enqueue(E element) { - this.list.add(element); - } - - public E dequeue() { - if (this.list.size() == 0) { - throw new NoSuchElementException(); - } - return this.list.remove(0); - } - - public E peek() { - if (this.list.size() == 0) { - throw new NoSuchElementException(); - } - return this.list.get(0); - } - - public boolean isEmpty() { - return this.list.isEmpty(); - } - - - // ********** standard methods ********** - - @Override - public String toString() { - return this.list.toString(); - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListStack.java deleted file mode 100644 index b9a08fd845..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListStack.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.EmptyStackException; -import java.util.List; -import org.eclipse.jpt.common.utility.collection.Stack; - -/** - * Adapt a {@link List} to the {@link Stack} interface. - * Elements are popped from the end of the list (i.e. index size - 1). - * @param the type of elements maintained by the stack - * @see StackTools - */ -public class ListStack - implements Stack, Serializable -{ - private List list; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct a stack, adapting the specified list. - * The stack will pop its elements in the reverse - * order they are returned by the list's iterator (i.e. the - * last element returned by the list's iterator will be the - * first element returned by {@link #pop()}). - */ - public ListStack(List list) { - super(); - this.list = list; - } - - - // ********** Stack implementation ********** - - public void push(E element) { - this.list.add(element); - } - - public E pop() { - int size = this.list.size(); - if (size == 0) { - throw new EmptyStackException(); - } - return this.list.remove(size - 1); - } - - public E peek() { - int size = this.list.size(); - if (size == 0) { - throw new EmptyStackException(); - } - return this.list.get(size - 1); - } - - public boolean isEmpty() { - return this.list.isEmpty(); - } - - - // ********** standard methods ********** - - @Override - public String toString() { - return this.list.toString(); - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListTools.java index 5192bf1480..1864caebd3 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/ListTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -20,8 +20,6 @@ import java.util.List; import java.util.ListIterator; import java.util.Random; import java.util.RandomAccess; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.internal.Range; import org.eclipse.jpt.common.utility.internal.iterable.IterableTools; import org.eclipse.jpt.common.utility.internal.iterator.IteratorTools; @@ -61,7 +59,14 @@ public final class ListTools { * Return whether the list changed as a result. */ public static boolean addAll(List list, int index, Iterator iterator) { - return iterator.hasNext() && list.addAll(index, list(iterator)); + return iterator.hasNext() && addAll_(list, index, iterator); + } + + /** + * assume the iterator is not empty + */ + private static boolean addAll_(List list, int index, Iterator iterator) { + return (index == list.size()) ? CollectionTools.addAll_(list, iterator) : list.addAll(index, arrayList(iterator)); } /** @@ -71,7 +76,7 @@ public final class ListTools { * The specified iterator size is a performance hint. */ public static boolean addAll(List list, int index, Iterator iterator, int iteratorSize) { - return iterator.hasNext() && list.addAll(index, list(iterator, iteratorSize)); + return iterator.hasNext() && list.addAll(index, arrayList(iterator, iteratorSize)); } /** @@ -83,48 +88,6 @@ public final class ListTools { return (array.length != 0) && list.addAll(index, Arrays.asList(array)); } - /** - * Add all the elements in the specified queue - * to the specified list at the specified index, - * draining the queue in the process. - * Return whether the list changed as a result. - */ - public static boolean addAll(List list, int index, Queue queue) { - return ( ! queue.isEmpty()) && list.addAll(index, list(queue)); - } - - /** - * Add all the elements in the specified queue - * to the specified list at the specified index, - * draining the queue in the process. - * Return whether the list changed as a result. - * The specified queue size is a performance hint. - */ - public static boolean addAll(List list, int index, Queue queue, int queueSize) { - return ( ! queue.isEmpty()) && list.addAll(index, list(queue, queueSize)); - } - - /** - * Add all the elements in the specified stack - * to the specified list at the specified index, - * draining the stack in the process. - * Return whether the list changed as a result. - */ - public static boolean addAll(List list, int index, Stack stack) { - return ( ! stack.isEmpty()) && list.addAll(index, list(stack)); - } - - /** - * Add all the elements in the specified stack - * to the specified list at the specified index, - * draining the stack in the process. - * Return whether the list changed as a result. - * The specified stack size is a performance hint. - */ - public static boolean addAll(List list, int index, Stack stack, int stackSize) { - return ( ! stack.isEmpty()) && list.addAll(index, list(stack, stackSize)); - } - // ********** diff ********** @@ -585,7 +548,7 @@ public final class ListTools { * Return a new list with transformations of the * elements in the specified list. */ - public static ArrayList transform(List list, Transformer transformer) { + public static ArrayList transform(Collection list, Transformer transformer) { ArrayList result = new ArrayList(list.size()); for (I each : list) { result.add(transformer.transform(each)); @@ -683,36 +646,36 @@ public final class ListTools { // ********** factory methods ********** /** - * Return a list corresponding to the specified iterable. + * Return an array list corresponding to the specified iterable. */ - public static ArrayList list(Iterable iterable) { - return list(iterable.iterator()); + public static ArrayList arrayList(Iterable iterable) { + return arrayList(iterable.iterator()); } /** - * Return a list corresponding to the specified iterable. + * Return an array list corresponding to the specified iterable. * The specified iterable size is a performance hint. */ - public static ArrayList list(Iterable iterable, int iterableSize) { - return list(iterable.iterator(), iterableSize); + public static ArrayList arrayList(Iterable iterable, int iterableSize) { + return arrayList(iterable.iterator(), iterableSize); } /** - * Return a list corresponding to the specified iterator. + * Return an array list corresponding to the specified iterator. */ - public static ArrayList list(Iterator iterator) { - return list(iterator, new ArrayList()); + public static ArrayList arrayList(Iterator iterator) { + return arrayList(iterator, new ArrayList()); } /** - * Return a list corresponding to the specified iterator. + * Return an array list corresponding to the specified iterator. * The specified iterator size is a performance hint. */ - public static ArrayList list(Iterator iterator, int iteratorSize) { - return list(iterator, new ArrayList(iteratorSize)); + public static ArrayList arrayList(Iterator iterator, int iteratorSize) { + return arrayList(iterator, new ArrayList(iteratorSize)); } - private static ArrayList list(Iterator iterator, ArrayList list) { + private static ArrayList arrayList(Iterator iterator, ArrayList list) { while (iterator.hasNext()) { list.add(iterator.next()); } @@ -720,11 +683,11 @@ public final class ListTools { } /** - * Return a list corresponding to the specified array. + * Return an array list corresponding to the specified array. * Unlike {@link Arrays#asList(Object[])}, the list * is modifiable and is not backed by the array. */ - public static ArrayList list(E... array) { + public static ArrayList arrayList(E... array) { ArrayList list = new ArrayList(array.length); for (E e : array) { list.add(e); @@ -732,54 +695,6 @@ public final class ListTools { return list; } - /** - * Return a list corresponding to the specified queue, - * draining the queue in the process. - */ - public static ArrayList list(Queue queue) { - return list(queue, new ArrayList()); - } - - /** - * Return a list corresponding to the specified queue, - * draining the queue in the process. - * The specified queue size is a performance hint. - */ - public static ArrayList list(Queue queue, int queueSize) { - return list(queue, new ArrayList(queueSize)); - } - - private static ArrayList list(Queue queue, ArrayList list) { - while ( ! queue.isEmpty()) { - list.add(queue.dequeue()); - } - return list; - } - - /** - * Return a list corresponding to the specified stack, - * draining the stack in the process. - */ - public static ArrayList list(Stack stack) { - return list(stack, new ArrayList()); - } - - /** - * Return a list corresponding to the specified stack, - * draining the stack in the process. - * The specified stack size is a performance hint. - */ - public static ArrayList list(Stack stack, int stackSize) { - return list(stack, new ArrayList(stackSize)); - } - - private static ArrayList list(Stack stack, ArrayList list) { - while ( ! stack.isEmpty()) { - list.add(stack.pop()); - } - return list; - } - // ********** transformers ********** @@ -820,7 +735,7 @@ public final class ListTools { * read-only {@link ListIterator}. */ @SuppressWarnings("unchecked") - public static Transformer, ListIterator> readOnlyListIteratorTransformer() { + public static Transformer, ListIterator> readOnlyListIteratorTransformer() { return READ_ONLY_LIST_ITERATOR_TRANSFORMER; } @@ -836,10 +751,10 @@ public final class ListTools { * read-only {@link ListIterator}. */ public static class ReadOnlyListIteratorTransformer - implements Transformer, ListIterator> + implements Transformer, ListIterator> { - public ListIterator transform(List list) { - return IteratorTools.readOnly(list.listIterator()); + public ListIterator transform(List list) { + return IteratorTools.readOnly(list.listIterator()); } @Override public String toString() { @@ -884,7 +799,7 @@ public final class ListTools { * read-only {@link ListIterable}. */ @SuppressWarnings("unchecked") - public static Transformer, ListIterable> readOnlyListIterableTransformer() { + public static Transformer, ListIterable> readOnlyListIterableTransformer() { return READ_ONLY_LIST_ITERABLE_TRANSFORMER; } @@ -900,10 +815,10 @@ public final class ListTools { * read-only {@link ListIterable}. */ public static class ReadOnlyListIterableTransformer - implements Transformer, ListIterable> + implements Transformer, ListIterable> { - public ListIterable transform(List list) { - return IterableTools.listIterable(list); + public ListIterable transform(List list) { + return IterableTools.readOnly(IterableTools.listIterable(list)); } @Override public String toString() { diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/MapTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/MapTools.java index 812b8f03f9..109b38bf02 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/MapTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/MapTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Oracle. All rights reserved. + * Copyright (c) 2013, 2015 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. @@ -14,8 +14,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.factory.Factory; import org.eclipse.jpt.common.utility.internal.ClassTools; import org.eclipse.jpt.common.utility.internal.ObjectTools; @@ -117,7 +115,7 @@ public final class MapTools { * @see Map#get(Object) * @see Map#containsKey(Object) */ - public static V get(Map map, K key, Class clazz, Class parameterType, Object argument) { + public static V get(Map map, K key, Class clazz, Class parameterType, Object argument) { return get(map, key, clazz, new Class[] {parameterType}, new Object[] {argument}); } @@ -125,8 +123,8 @@ public final class MapTools { * Assume the map does not contain any null values. * @see #get(Map, Object, Class, Class, Object) */ - public static V get_(Map map, K key, Class clazz, Class parameterType, Object argument) { - return get(map, key, clazz, new Class[] {parameterType}, new Object[] {argument}); + public static V get_(Map map, K key, Class clazz, Class parameterType, Object argument) { + return get_(map, key, clazz, new Class[] {parameterType}, new Object[] {argument}); } /** @@ -207,30 +205,6 @@ public final class MapTools { } } - /** - * With the specified map, map the values dequeued from the specified queue - * to the keys generated by passing the values to the specified key - * transformer. - * @see Map#putAll(Map) - */ - public static void addAll(Map map, Queue values, Transformer keyTransformer) { - while ( ! values.isEmpty()) { - add(map, values.dequeue(), keyTransformer); - } - } - - /** - * With the specified map, map the values popped from the specified stack - * to the keys generated by passing the values to the specified key - * transformer. - * @see Map#putAll(Map) - */ - public static void addAll(Map map, Stack values, Transformer keyTransformer) { - while ( ! values.isEmpty()) { - add(map, values.pop(), keyTransformer); - } - } - /** * With the specified map, map the specified values to the keys generated by * passing the values to the specified key transformer. @@ -264,32 +238,6 @@ public final class MapTools { } } - /** - * With the specified map, map the values generated by passing the elements - * dequeued from the specified queue to the specified value transformer to - * the key generated by passing the elements to the specified key - * transformer. - * @see Map#putAll(Map) - */ - public static void addAll(Map map, Queue elements, Transformer keyTransformer, Transformer valueTransformer) { - while ( ! elements.isEmpty()) { - add(map, elements.dequeue(), keyTransformer, valueTransformer); - } - } - - /** - * With the specified map, map the values generated by passing the elements - * popped from the specified stack to the specified value transformer to - * the key generated by passing the elements to the specified key - * transformer. - * @see Map#putAll(Map) - */ - public static void addAll(Map map, Stack elements, Transformer keyTransformer, Transformer valueTransformer) { - while ( ! elements.isEmpty()) { - add(map, elements.pop(), keyTransformer, valueTransformer); - } - } - /** * With the specified map, map the values generated by passing the specified * elements to the specified value transformer to the key generated by @@ -378,36 +326,6 @@ public final class MapTools { return true; } - /** - * Return whether the specified map contains all of the - * keys in the specified queue, dequeueing elements from the queue - * until one is not found in the map. - * @see Map#containsKey(Object) - */ - public static boolean containsAllKeys(Map map, Queue keys) { - while ( ! keys.isEmpty()) { - if ( ! map.containsKey(keys.dequeue())) { - return false; - } - } - return true; - } - - /** - * Return whether the specified map contains all of the - * keys in the specified stack, popping elements from the stack - * until one is not found in the map. - * @see Map#containsKey(Object) - */ - public static boolean containsAllKeys(Map map, Stack keys) { - while ( ! keys.isEmpty()) { - if ( ! map.containsKey(keys.pop())) { - return false; - } - } - return true; - } - // ********** contains all values ********** @@ -449,36 +367,6 @@ public final class MapTools { return true; } - /** - * Return whether the specified map contains all of the - * values in the specified queue, dequeueing elements from the queue - * until one is not found in the map. - * @see Map#containsValue(Object) - */ - public static boolean containsAllValues(Map map, Queue values) { - while ( ! values.isEmpty()) { - if ( ! map.containsValue(values.dequeue())) { - return false; - } - } - return true; - } - - /** - * Return whether the specified map contains all of the - * values in the specified stack, popping elements from the stack - * until one is not found in the map. - * @see Map#containsValue(Object) - */ - public static boolean containsAllValues(Map map, Stack values) { - while ( ! values.isEmpty()) { - if ( ! map.containsValue(values.pop())) { - return false; - } - } - return true; - } - // ********** remove all ********** @@ -513,28 +401,6 @@ public final class MapTools { } } - /** - * Remove from the specified map all of the - * keys dequeued from the specified queue. - * @see Map#remove(Object) - */ - public static void removeAll(Map map, Queue keys) { - while ( ! keys.isEmpty()) { - map.remove(keys.dequeue()); - } - } - - /** - * Remove from the specified map all of the - * keys popped from the specified stack. - * @see Map#remove(Object) - */ - public static void removeAll(Map map, Stack keys) { - while ( ! keys.isEmpty()) { - map.remove(keys.pop()); - } - } - // ********** retain all ********** @@ -573,7 +439,7 @@ public final class MapTools { */ public static void retainAll(Map map, Iterator keys) { if (keys.hasNext()) { - retainAll_(map, CollectionTools.set(keys)); + retainAll_(map, CollectionTools.hashSet(keys)); } else { map.clear(); } @@ -586,7 +452,7 @@ public final class MapTools { */ public static void retainAll(Map map, Iterator keys, int keysSize) { if (keys.hasNext()) { - retainAll_(map, CollectionTools.set(keys, keysSize)); + retainAll_(map, CollectionTools.hashSet(keys, keysSize)); } else { map.clear(); } @@ -598,36 +464,12 @@ public final class MapTools { */ public static void retainAll(Map map, Object... keys) { if (keys.length > 0) { - retainAll_(map, CollectionTools.set(keys)); + retainAll_(map, CollectionTools.hashSet(keys)); } else { map.clear(); } } - /** - * Retain in the specified map only the - * keys dequeued from the specified queue. - */ - public static void retainAll(Map map, Queue keys) { - if (keys.isEmpty()) { - map.clear(); - } else { - retainAll_(map, CollectionTools.set(keys)); - } - } - - /** - * Retain in the specified map only the - * keys popped from the specified stack. - */ - public static void retainAll(Map map, Stack keys) { - if (keys.isEmpty()) { - map.clear(); - } else { - retainAll_(map, CollectionTools.set(keys)); - } - } - /** * no empty check */ diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/NullList.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/NullList.java index 85926244b8..a44cea694f 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/NullList.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/NullList.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -100,7 +100,10 @@ public final class NullList } public ListIterator listIterator(int index) { - return EmptyListIterator.instance(); + if (index == 0) { + return EmptyListIterator.instance(); + } + throw new IndexOutOfBoundsException("Index: " + index + ", Size: 0"); //$NON-NLS-1$ //$NON-NLS-2$ } public boolean remove(Object o) { @@ -128,7 +131,10 @@ public final class NullList } public List subList(int fromIndex, int toIndex) { - return this; + if ((fromIndex == 0) && (toIndex == 0)) { + return this; + } + throw new IndexOutOfBoundsException("Index: " + fromIndex + ", Size: 0"); //$NON-NLS-1$ //$NON-NLS-2$ } public Object[] toArray() { @@ -141,7 +147,7 @@ public final class NullList @Override public String toString() { - return this.getClass().getSimpleName(); + return "[]"; //$NON-NLS-1$ } private static final long serialVersionUID = 1L; diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/PriorityQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/PriorityQueue.java deleted file mode 100644 index e928ab2434..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/PriorityQueue.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.SortedSet; -import org.eclipse.jpt.common.utility.collection.Queue; - -/** - * Adapt a {@link SortedSet} to create a priority implementation of the - * {@link Queue} interface. Elements will dequeue in the order determined by - * wrapped sorted set (i.e. {@link #dequeue} will return the element returned - * by {@link SortedSet#first}. - * @param the type of elements maintained by the queue - * @see QueueTools - */ -public class PriorityQueue - implements Queue, Serializable -{ - private final SortedSet elements; - - private static final long serialVersionUID = 1L; - - - public PriorityQueue(SortedSet elements) { - super(); - if (elements == null) { - throw new NullPointerException(); - } - this.elements = elements; - } - - public void enqueue(E element) { - this.elements.add(element); - } - - public E dequeue() { - E result = this.elements.first(); - this.elements.remove(result); - return result; - } - - public E peek() { - return this.elements.first(); - } - - public boolean isEmpty() { - return this.elements.isEmpty(); - } - - @Override - public String toString() { - return this.elements.toString(); - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/QueueTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/QueueTools.java deleted file mode 100644 index 9de1eab2e3..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/QueueTools.java +++ /dev/null @@ -1,403 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 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.internal.collection; - -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 org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; - -/** - * {@link Queue} utility methods. - */ -public final class QueueTools { - - // ********** enqueue all ********** - - /** - * Enqueue all the elements returned by the specified iterable - * on the specified queue. - * Return the queue. - */ - public static , E> Q enqueueAll(Q queue, Iterable iterable) { - return enqueueAll(queue, iterable.iterator()); - } - - /** - * Enqueue all the elements returned by the specified iterator - * on the specified queue. - * Return the queue. - */ - public static , E> Q enqueueAll(Q queue, Iterator iterator) { - while (iterator.hasNext()) { - queue.enqueue(iterator.next()); - } - return queue; - } - - /** - * Enqueue all the elements in the specified array - * on the specified queue. - * Return the queue. - */ - public static , E> Q enqueueAll(Q queue, E... array) { - for (E element : array) { - queue.enqueue(element); - } - return queue; - } - - /** - * Pop all the elements from the specified stack and enqueue them - * on the specified queue. - * Return the queue. - */ - public static , E> Q enqueueAll(Q queue, Stack stack) { - while ( ! stack.isEmpty()) { - queue.enqueue(stack.pop()); - } - return queue; - } - - /** - * Dequeue all the elements from the second specified queue and enqueue them - * on the first specified queue. - * Return the first queue. - * @see #drainTo(Queue, Queue) - */ - public static , E> Q enqueueAll(Q queue1, Queue queue2) { - while ( ! queue2.isEmpty()) { - queue1.enqueue(queue2.dequeue()); - } - return queue1; - } - - - // ********** drain ********** - - /** - * Drain all the elements from the specified queue and return them in a - * list. - */ - public static ArrayList drain(Queue queue) { - return drainTo(queue, new ArrayList()); - } - - /** - * Drain all the elements from the specified queue and add them to the - * specified collection. - * Return the collection. - */ - public static , E> C drainTo(Queue queue, C collection) { - while ( ! queue.isEmpty()) { - collection.add(queue.dequeue()); - } - return collection; - } - - /** - * Drain all the elements from the specified queue and push them on the - * specified stack. - * Return the stack. - */ - public static , E> S drainTo(Queue queue, S stack) { - while ( ! queue.isEmpty()) { - stack.push(queue.dequeue()); - } - return stack; - } - - /** - * Drain all the elements from the first specified queue and enqueue them - * on the second specified queue. - * Return the second queue. - * @see #enqueueAll(Queue, Queue) - */ - public static , E> Q drainTo(Queue queue1, Q queue2) { - while ( ! queue1.isEmpty()) { - queue2.enqueue(queue1.dequeue()); - } - return queue2; - } - - - // ********** factory methods ********** - - /** - * Return an empty array-based FIFO queue. - */ - public static ArrayQueue queue() { - return arrayQueue(); - } - - /** - * Return an empty array-based FIFO queue with specified initial capacity. - */ - public static ArrayQueue queue(int initialCapacity) { - return arrayQueue(initialCapacity); - } - - /** - * Return a FIFO queue corresponding to the specified iterable. - */ - public static ArrayQueue queue(Iterable iterable) { - return arrayQueue(iterable); - } - - /** - * Return a FIFO queue corresponding to the specified iterable. - * The specified iterable size is a performance hint. - */ - public static ArrayQueue queue(Iterable iterable, int iterableSize) { - return arrayQueue(iterable, iterableSize); - } - - /** - * Return a FIFO queue corresponding to the specified iterator. - */ - public static ArrayQueue queue(Iterator iterator) { - return arrayQueue(iterator); - } - - /** - * Return a FIFO queue corresponding to the specified iterator. - * The specified iterator size is a performance hint. - */ - public static ArrayQueue queue(Iterator iterator, int iteratorSize) { - return arrayQueue(iterator, iteratorSize); - } - - /** - * Return a FIFO queue corresponding to the specified array. - */ - public static ArrayQueue queue(E... array) { - return arrayQueue(array); - } - - /** - * Return an empty array-based FIFO queue. - */ - public static ArrayQueue arrayQueue() { - return arrayQueue(10); - } - - /** - * Return an empty array-based FIFO queue with specified initial capacity. - */ - public static ArrayQueue arrayQueue(int initialCapacity) { - return new ArrayQueue(initialCapacity); - } - - /** - * Return an array-based FIFO queue corresponding to the specified iterable. - */ - public static ArrayQueue arrayQueue(Iterable iterable) { - return arrayQueue(iterable.iterator()); - } - - /** - * Return an array-based FIFO queue corresponding to the specified iterable. - * The specified iterable size is a performance hint. - */ - public static ArrayQueue arrayQueue(Iterable iterable, int iterableSize) { - return arrayQueue(iterable.iterator(), iterableSize); - } - - /** - * Return an array-based FIFO queue corresponding to the specified iterator. - */ - public static ArrayQueue arrayQueue(Iterator iterator) { - return enqueueAll(QueueTools.arrayQueue(), iterator); - } - - /** - * Return an array-based FIFO queue corresponding to the specified iterator. - * The specified iterator size is a performance hint. - */ - public static ArrayQueue arrayQueue(Iterator iterator, int iteratorSize) { - return enqueueAll(QueueTools.arrayQueue(iteratorSize), iterator); - } - - /** - * Return an array-based FIFO queue corresponding to the specified array. - */ - public static ArrayQueue arrayQueue(E... array) { - return enqueueAll(QueueTools.arrayQueue(array.length), array); - } - - /** - * Return an empty link-based FIFO queue with no node cache. - */ - public static LinkedQueue linkedQueue() { - return linkedQueue(0); - } - - /** - * Return an empty link-based FIFO queue - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedQueue linkedQueue(int cacheSize) { - return new LinkedQueue(cacheSize); - } - - /** - * Return a link-based FIFO queue corresponding to the specified iterable. - */ - public static LinkedQueue linkedQueue(Iterable iterable) { - return linkedQueue(iterable, 0); - } - - /** - * Return a link-based FIFO queue corresponding to the specified iterable - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedQueue linkedQueue(Iterable iterable, int cacheSize) { - return linkedQueue(iterable.iterator(), cacheSize); - } - - /** - * Return a link-based FIFO queue corresponding to the specified iterator. - */ - public static LinkedQueue linkedQueue(Iterator iterator) { - return linkedQueue(iterator, 0); - } - - /** - * Return a link-based FIFO queue corresponding to the specified iterator - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedQueue linkedQueue(Iterator iterator, int cacheSize) { - return enqueueAll(QueueTools.linkedQueue(cacheSize), iterator); - } - - /** - * Return a link-based FIFO queue corresponding to the specified array. - */ - public static LinkedQueue linkedQueue(E... array) { - return linkedQueue(array, 0); - } - - /** - * Return a link-based FIFO queue corresponding to the specified array - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedQueue linkedQueue(E[] array, int cacheSize) { - return enqueueAll(QueueTools.linkedQueue(cacheSize), array); - } - - /** - * Return a fixed-size queue with the specified capacity. - */ - public static FixedSizeArrayQueue fixedSizeQueue(int capacity) { - return new FixedSizeArrayQueue(capacity); - } - - /** - * Return a fized-size queue containing the elements of the specified - * collection. The queue will dequeue its elements in the same - * order they are returned by the collection's iterator (i.e. the - * first element returned by the collection's iterator will be the - * first element returned by {@link Queue#dequeue()}). - * The queue's capacity will be match the collection's size. - */ - public static FixedSizeArrayQueue fixedSizeQueue(Collection collection) { - return enqueueAll(QueueTools.fixedSizeQueue(collection.size()), collection); - } - - /** - * Return a LIFO queue. - */ - public static StackQueue stackQueue() { - return queue(new ArrayStack()); - } - - /** - * Adapt the specified stack to the {@link Queue} interface, - * implementing a LIFO queue. - */ - public static StackQueue queue(Stack stack) { - return new StackQueue(stack); - } - - /** - * Return a priority queue that returns its elements in - * {@linkplain Comparable natural order}. - */ - public static PriorityQueue priorityQueue() { - return queue((Comparator) null); - } - - /** - * Return a priority queue whose elements are returned in - * the order determined by the specified comparator. - * If the specified comparator is null, the elements will be - * returned in {@linkplain Comparable natural order}. - */ - public static PriorityQueue queue(Comparator comparator) { - return queue(new TreeSet(comparator)); - } - - /** - * Adapt the specified sorted set to the {@link Queue} interface, - * implementing a priority queue. - */ - public static PriorityQueue queue(SortedSet elements) { - return new PriorityQueue(elements); - } - - /** - * Adapt the specified list to the {@link Queue} interface. - */ - public static ListQueue wrap(List list) { - return new ListQueue(list); - } - - /** - * Return a queue that synchronizes the specified queue - * with specified mutex. - */ - public static SynchronizedQueue synchronizedQueue(Queue queue, Object mutex) { - return new SynchronizedQueue(queue, mutex); - } - - /** - * Return a queue that synchronizes the specified queue. - */ - public static SynchronizedQueue synchronizedQueue(Queue queue) { - return new SynchronizedQueue(queue); - } - - /** - * Return an unmodifiable empty queue. - */ - public static Queue emptyQueue() { - return EmptyQueue.instance(); - } - - - // ********** constructor ********** - - /** - * Suppress default constructor, ensuring non-instantiability. - */ - private QueueTools() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackQueue.java deleted file mode 100644 index 4239a829b3..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackQueue.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 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.internal.collection; - -import java.io.Serializable; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; - -/** - * Adapt a {@link Stack} to create a LIFO implementation of the {@link Queue} - * interface. - * @param the type of elements maintained by the queue - * @see QueueTools - */ -public class StackQueue - implements Queue, Serializable -{ - private final Stack stack; - - private static final long serialVersionUID = 1L; - - - public StackQueue(Stack stack) { - super(); - if (stack == null) { - throw new NullPointerException(); - } - this.stack = stack; - } - - public void enqueue(E element) { - this.stack.push(element); - } - - public E dequeue() { - return this.stack.pop(); - } - - public E peek() { - return this.stack.peek(); - } - - public boolean isEmpty() { - return this.stack.isEmpty(); - } - - @Override - public String toString() { - return this.stack.toString(); - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackTools.java deleted file mode 100644 index 57eb050ba0..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/StackTools.java +++ /dev/null @@ -1,374 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, 2015 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.internal.collection; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; - -/** - * {@link Stack} utility methods. - */ -public class StackTools { - - // ********** push all ********** - - /** - * Push all the elements returned by the specified iterable - * on the specified stack. - * Return the stack. - */ - public static , E> S pushAll(S stack, Iterable iterable) { - return pushAll(stack, iterable.iterator()); - } - - /** - * Push all the elements returned by the specified iterator - * on the specified stack. - * Return the stack. - */ - public static , E> S pushAll(S stack, Iterator iterator) { - while (iterator.hasNext()) { - stack.push(iterator.next()); - } - return stack; - } - - /** - * Push all the elements in the specified array - * on the specified stack. - * Return the stack. - */ - public static , E> S pushAll(S stack, E... array) { - for (E element : array) { - stack.push(element); - } - return stack; - } - - /** - * Dequeue all the elements from the specified queue and push them - * on the specified stack. - * Return the stack. - */ - public static , E> S pushAll(S stack, Queue queue) { - while ( ! queue.isEmpty()) { - stack.push(queue.dequeue()); - } - return stack; - } - - /** - * Pop all the elements from the second specified stack and push them - * on the first specified stack. - * Return the first stack. - * @see #popAllTo(Stack, Stack) - */ - public static , E> S pushAll(S stack1, Stack stack2) { - while ( ! stack2.isEmpty()) { - stack1.push(stack2.pop()); - } - return stack1; - } - - - // ********** pop all ********** - - /** - * Pop all the elements from the specified stack and return them in a - * list. - */ - public static ArrayList popAll(Stack stack) { - return popAllTo(stack, new ArrayList()); - } - - /** - * Pop all the elements from the specified stack and add them to the - * specified collection. - * Return the collection. - */ - public static , E> C popAllTo(Stack stack, C collection) { - while ( ! stack.isEmpty()) { - collection.add(stack.pop()); - } - return collection; - } - - /** - * Pop all the elements from the specified stack and enqueue them on the - * specified queue. - * Return the queue. - */ - public static , E> Q popAllTo(Stack stack, Q queue) { - while ( ! stack.isEmpty()) { - queue.enqueue(stack.pop()); - } - return queue; - } - - /** - * Pop all the elements from the first specified stack and push them - * on the second specified stack. - * Return the second stack. - * @see #pushAll(Stack, Stack) - */ - public static , E> S popAllTo(Stack stack1, S stack2) { - while ( ! stack1.isEmpty()) { - stack2.push(stack1.pop()); - } - return stack2; - } - - - // ********** factory methods ********** - - /** - * Return an empty LIFO stack. - */ - public static ArrayStack stack() { - return arrayStack(); - } - - /** - * Return an empty LIFO stack with the specified initial capacity. - */ - public static ArrayStack stack(int initialCapacity) { - return arrayStack(initialCapacity); - } - - /** - * Return a LIFO stack corresponding to the specified iterable. - */ - public static ArrayStack stack(Iterable iterable) { - return arrayStack(iterable); - } - - /** - * Return a LIFO stack corresponding to the specified iterable. - * The specified iterable size is a performance hint. - */ - public static ArrayStack stack(Iterable iterable, int iterableSize) { - return arrayStack(iterable, iterableSize); - } - - /** - * Return a LIFO stack corresponding to the specified iterator. - */ - public static ArrayStack stack(Iterator iterator) { - return arrayStack(iterator); - } - - /** - * Return a LIFO stack corresponding to the specified iterator. - * The specified iterator size is a performance hint. - */ - public static ArrayStack stack(Iterator iterator, int iteratorSize) { - return arrayStack(iterator, iteratorSize); - } - - /** - * Return a LIFO stack corresponding to the specified array. - */ - public static ArrayStack stack(E... array) { - return arrayStack(array); - } - - /** - * Return an array-based LIFO stack corresponding. - */ - public static ArrayStack arrayStack() { - return arrayStack(10); - } - - /** - * Return an array-based LIFO stack corresponding with the specified initial capacity. - */ - public static ArrayStack arrayStack(int initialCapacity) { - return new ArrayStack(initialCapacity); - } - - /** - * Return an array-based LIFO stack corresponding to the specified iterable. - * The stack will pop its elements in reverse of the - * order they are returned by the iterable's iterator (i.e. the - * last element returned by the iterable's iterator will be the - * first element returned by {@link Stack#pop()}; the first, last.). - */ - public static ArrayStack arrayStack(Iterable iterable) { - return arrayStack(iterable.iterator()); - } - - /** - * Return an array-based LIFO stack corresponding to the specified iterable. - * The stack will pop its elements in reverse of the - * order they are returned by the iterable's iterator (i.e. the - * last element returned by the iterable's iterator will be the - * first element returned by {@link Stack#pop()}; the first, last.). - * The specified iterable size is a performance hint. - */ - public static ArrayStack arrayStack(Iterable iterable, int iterableSize) { - return arrayStack(iterable.iterator(), iterableSize); - } - - /** - * Return an array-based LIFO stack corresponding to the specified iterator. - * The stack will pop its elements in reverse of the - * order they are returned by the iterator (i.e. the - * last element returned by the iterator will be the - * first element returned by {@link Stack#pop()}; the first, last.). - */ - public static ArrayStack arrayStack(Iterator iterator) { - return pushAll(StackTools.arrayStack(), iterator); - } - - /** - * Return an array-based LIFO stack corresponding to the specified iterator. - * The stack will pop its elements in reverse of the - * order they are returned by the iterator (i.e. the - * last element returned by the iterator will be the - * first element returned by {@link Stack#pop()}; the first, last.). - * The specified iterator size is a performance hint. - */ - public static ArrayStack arrayStack(Iterator iterator, int iteratorSize) { - return pushAll(StackTools.arrayStack(iteratorSize), iterator); - } - - /** - * Return an array-based LIFO stack corresponding to the specified array. - */ - public static ArrayStack arrayStack(E... array) { - return pushAll(StackTools.arrayStack(array.length), array); - } - - /** - * Return an empty link-based LIFO stack with no node cache. - */ - public static LinkedStack linkedStack() { - return linkedStack(0); - } - - /** - * Return an empty link-based LIFO stack - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedStack linkedStack(int cacheSize) { - return new LinkedStack(cacheSize); - } - - /** - * Return a link-based LIFO stack corresponding to the specified iterable. - */ - public static LinkedStack linkedStack(Iterable iterable) { - return linkedStack(iterable.iterator()); - } - - /** - * Return a link-based LIFO stack corresponding to the specified iterable - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedStack linkedStack(Iterable iterable, int cacheSize) { - return linkedStack(iterable.iterator(), cacheSize); - } - - /** - * Return a link-based LIFO stack corresponding to the specified iterator. - */ - public static LinkedStack linkedStack(Iterator iterator) { - return pushAll(StackTools.linkedStack(), iterator); - } - - /** - * Return a link-based LIFO stack corresponding to the specified iterator - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedStack linkedStack(Iterator iterator, int cacheSize) { - return pushAll(StackTools.linkedStack(cacheSize), iterator); - } - - /** - * Return a link-based LIFO stack corresponding to the specified array. - */ - public static LinkedStack linkedStack(E... array) { - return pushAll(StackTools.linkedStack(), array); - } - - /** - * Return a link-based LIFO stack corresponding to the specified array - * with the specified node cache size. - * Specify a cache size of -1 for an unlimited cache. - */ - public static LinkedStack linkedStack(E[] array, int cacheSize) { - return pushAll(StackTools.linkedStack(cacheSize), array); - } - - /** - * Return a fixed-size stack with the specified capacity. - */ - public static FixedSizeArrayStack fixedSizeStack(int capacity) { - return new FixedSizeArrayStack(capacity); - } - - /** - * Return a fized-size stack containing the elements of the specified - * collection. The stack will pop its elements in reverse of the - * order they are returned by the collection's iterator (i.e. the - * last element returned by the collection's iterator will be the - * first element returned by {@link Stack#pop()}; the first, last.). - */ - public static FixedSizeArrayStack fixedSizeStack(Collection collection) { - return pushAll(StackTools.fixedSizeStack(collection.size()), collection); - } - - /** - * Adapt the specified list to the {@link Stack} interface. - */ - public static ListStack wrap(List list) { - return new ListStack(list); - } - - /** - * Return a stack that synchronizes the specified stack - * with specified mutex. - */ - public static SynchronizedStack synchronizedStack(Stack stack, Object mutex) { - return new SynchronizedStack(stack, mutex); - } - - /** - * Return a stack that synchronizes the specified stack. - */ - public static SynchronizedStack synchronizedStack(Stack stack) { - return new SynchronizedStack(stack); - } - - /** - * Return an unmodifiable empty LIFO stack. - */ - public static Stack emptyStack() { - return EmptyStack.instance(); - } - - - // ********** constructor ********** - - /** - * Suppress default constructor, ensuring non-instantiability. - */ - private StackTools() { - super(); - throw new UnsupportedOperationException(); - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedBag.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedBag.java index 42d882900e..d85b62ed0b 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedBag.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedBag.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -59,20 +59,6 @@ public class SynchronizedBag this.mutex = this; } - /** - * Construct a synchronized bag that locks on the specified mutex. - */ - public SynchronizedBag(Object mutex) { - this(new HashBag(), mutex); - } - - /** - * Construct a synchronized bag that locks on itself. - */ - public SynchronizedBag() { - this(new HashBag()); - } - // ********** Bag implementation ********** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedQueue.java deleted file mode 100644 index 769deb4ffa..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedQueue.java +++ /dev/null @@ -1,494 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.command.Command; - -/** - * Thread-safe implementation of the {@link Queue} interface. - * This also provides protocol for suspending a thread until the - * queue is empty or not empty, with optional time-outs. - * @param the type of elements maintained by the queue - * @see QueueTools - */ -public class SynchronizedQueue - implements Queue, Serializable -{ - /** Backing queue. */ - private final Queue queue; - - /** Object to synchronize on. */ - private final Object mutex; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct a synchronized queue that wraps the - * specified queue and locks on the specified mutex. - */ - public SynchronizedQueue(Queue queue, Object mutex) { - super(); - if ((queue == null) || (mutex == null)) { - throw new NullPointerException(); - } - this.queue = queue; - this.mutex = mutex; - } - - /** - * Construct a synchronized queue that wraps the - * specified queue and locks on itself. - */ - public SynchronizedQueue(Queue queue) { - super(); - if (queue == null) { - throw new NullPointerException(); - } - this.queue = queue; - this.mutex = this; - } - - /** - * Construct an empty synchronized queue that locks on the specified mutex. - */ - public SynchronizedQueue(Object mutex) { - this(new LinkedQueue(), mutex); - } - - /** - * Construct an empty synchronized queue that locks on itself. - */ - public SynchronizedQueue() { - this(new LinkedQueue()); - } - - - // ********** Queue implementation ********** - - public void enqueue(E element) { - synchronized (this.mutex) { - this.enqueue_(element); - } - } - - /** - * Pre-condition: synchronized - */ - private void enqueue_(E element) { - this.queue.enqueue(element); - this.mutex.notifyAll(); - } - - public E dequeue() { - synchronized (this.mutex) { - return this.dequeue_(); - } - } - - /** - * Pre-condition: synchronized - */ - private E dequeue_() { - E element = this.queue.dequeue(); - this.mutex.notifyAll(); - return element; - } - - public E peek() { - synchronized (this.mutex) { - return this.queue.peek(); - } - } - - public boolean isEmpty() { - synchronized (this.mutex) { - return this.queue.isEmpty(); - } - } - - - // ********** indefinite waits ********** - - /** - * Suspend the current thread until the queue's empty status changes - * to the specified value. - */ - public void waitUntilEmptyIs(boolean empty) throws InterruptedException { - synchronized (this.mutex) { - this.waitUntilEmptyIs_(empty); - } - } - - /** - * Pre-condition: synchronized - */ - private void waitUntilEmptyIs_(boolean empty) throws InterruptedException { - while (this.queue.isEmpty() != empty) { - this.mutex.wait(); - } - } - - /** - * Suspend the current thread until the queue is empty. - */ - public void waitUntilEmpty() throws InterruptedException { - this.waitUntilEmptyIs(true); - } - - /** - * Suspend the current thread until the queue has something on it. - */ - public void waitUntilNotEmpty() throws InterruptedException { - this.waitUntilEmptyIs(false); - } - - /** - * Suspend the current thread until the queue is empty, - * then "enqueue" the specified item to the tail of the queue - * and continue executing. - */ - public void waitToEnqueue(E element) throws InterruptedException { - synchronized (this.mutex) { - this.waitUntilEmptyIs_(true); - this.enqueue_(element); - } - } - - /** - * Suspend the current thread until the queue has something on it, - * then "dequeue" an item from the head of the queue and return it. - */ - public Object waitToDequeue() throws InterruptedException { - synchronized (this.mutex) { - this.waitUntilEmptyIs_(false); - return this.dequeue_(); - } - } - - - // ********** timed waits ********** - - /** - * Suspend the current thread until the queue's empty status changes - * to the specified value or the specified time-out occurs. - * The time-out is specified in milliseconds. Return true if the specified - * empty status was achieved; return false if a time-out occurred. - * If the queue's empty status is already the specified value, - * return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitUntilEmptyIs(boolean empty, long timeout) throws InterruptedException { - synchronized (this.mutex) { - return this.waitUntilEmptyIs_(empty, timeout); - } - } - - /** - * Pre-condition: synchronized - */ - private boolean waitUntilEmptyIs_(boolean empty, long timeout) throws InterruptedException { - if (timeout == 0L) { - this.waitUntilEmptyIs_(empty); // wait indefinitely until notified - return true; // if it ever comes back, the condition was met - } - - long stop = System.currentTimeMillis() + timeout; - long remaining = timeout; - while ((this.queue.isEmpty() != empty) && (remaining > 0L)) { - this.mutex.wait(remaining); - remaining = stop - System.currentTimeMillis(); - } - return (this.queue.isEmpty() == empty); - } - - /** - * Suspend the current thread until the queue is empty - * or the specified time-out occurs. - * The time-out is specified in milliseconds. Return true if - * the queue is empty; return false if a time-out occurred. - * If the queue is already empty, return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitUntilEmpty(long timeout) throws InterruptedException { - return this.waitUntilEmptyIs(true, timeout); - } - - /** - * Suspend the current thread until the queue has something on it. - * or the specified time-out occurs. - * The time-out is specified in milliseconds. Return true if - * the queue is not empty; return false if a time-out occurred. - * If the queue already has something on it, return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitUntilNotEmpty(long timeout) throws InterruptedException { - return this.waitUntilEmptyIs(false, timeout); - } - - /** - * Suspend the current thread until the queue is empty, - * then "enqueue" the specified item to the tail of the queue - * and continue executing. If the queue is not emptied out - * before the time-out, simply continue executing without - * "enqueueing" the item. - * The time-out is specified in milliseconds. Return true if the - * item was enqueued; return false if a time-out occurred. - * If the queue is already empty, "enqueue" the specified item and - * return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitToEnqueue(E element, long timeout) throws InterruptedException { - synchronized (this.mutex) { - boolean success = this.waitUntilEmptyIs_(true, timeout); - if (success) { - this.enqueue_(element); - } - return success; - } - } - - /** - * Suspend the current thread until the queue has something on it, - * then "dequeue" an item from the head of the queue and return it. - * If the queue is empty and nothing is "enqueued" on to it before the - * time-out, throw a no such element exception. - * The time-out is specified in milliseconds. - * If the queue is not empty, "dequeue" an item and - * return it immediately. - * If the time-out is zero, wait indefinitely. - */ - public Object waitToDequeue(long timeout) throws InterruptedException { - synchronized (this.mutex) { - boolean success = this.waitUntilEmptyIs_(false, timeout); - if (success) { - return this.dequeue_(); - } - throw new NoSuchElementException(); - } - } - - - // ********** synchronized behavior ********** - - /** - * If the current thread is not interrupted, execute the specified command - * with the mutex locked. This is useful for initializing the queue in another - * thread. - */ - public void execute(Command command) throws InterruptedException { - if (Thread.currentThread().isInterrupted()) { - throw new InterruptedException(); - } - synchronized (this.mutex) { - command.execute(); - } - } - - - // ********** additional public protocol ********** - - /** - * "Enqueue" all the elements returned by the specified iterable. - */ - public void enqueueAll(Iterable iterable) { - this.enqueueAll(iterable.iterator()); - } - - /** - * "Enqueue" all the elements returned by the specified iterator. - */ - public void enqueueAll(Iterator iterator) { - synchronized (this.mutex) { - this.enqueueAll_(iterator); - } - } - - /** - * Pre-condition: synchronized - */ - private void enqueueAll_(Iterator iterator) { - while (iterator.hasNext()) { - this.enqueue_(iterator.next()); - } - } - - /** - * "Enqueue" all the elements in the specified array. - */ - public void enqueueAll(E... array) { - synchronized (this.mutex) { - this.enqueueAll_(array); - } - } - - /** - * Pre-condition: synchronized - */ - private void enqueueAll_(E[] array) { - for (E element : array) { - this.enqueue_(element); - } - } - - /** - * Pop all the elements from the specified stack and "enqueue" them. - */ - public void enqueueAll(Stack stack) { - synchronized (this.mutex) { - this.enqueueAll_(stack); - } - } - - /** - * Pre-condition: synchronized - */ - private void enqueueAll_(Stack stack) { - while ( ! stack.isEmpty()) { - this.enqueue_(stack.pop()); - } - } - - /** - * "Dequeue" all the elements from the second specified queue and - * "enqueue" them. - * @see #drainTo(Queue) - */ - public void enqueueAll(Queue q) { - synchronized (this.mutex) { - this.enqueueAll_(q); - } - } - - /** - * Pre-condition: synchronized - */ - private void enqueueAll_(Queue q) { - while ( ! q.isEmpty()) { - this.enqueue_(q.dequeue()); - } - } - - /** - * "Drain" all the current items from the queue and return them in a list. - */ - public Iterable drain() { - return this.drainTo(new ArrayList()); - } - - /** - * "Drain" all the current items from the queue into specified collection. - * Return the collection. - */ - public > C drainTo(C c) { - synchronized (this.mutex) { - return this.drainTo_(c); - } - } - - /** - * Pre-condition: synchronized - */ - private > C drainTo_(C c) { - boolean changed = false; - while ( ! this.queue.isEmpty()) { - c.add(this.queue.dequeue()); - changed = true; - } - if (changed) { - this.mutex.notifyAll(); - } - return c; - } - - /** - * "Drain" all the current items from the queue into specified stack. - * Return the stack. - */ - public > S drainTo(S stack) { - synchronized (this.mutex) { - return this.drainTo_(stack); - } - } - - /** - * Pre-condition: synchronized - */ - private > S drainTo_(S stack) { - boolean changed = false; - while ( ! this.queue.isEmpty()) { - stack.push(this.queue.dequeue()); - changed = true; - } - if (changed) { - this.mutex.notifyAll(); - } - return stack; - } - - /** - * "Drain" all the current items from the queue into specified queue. - * Return the specified queue. - * @see #enqueueAll(Queue) - */ - public > Q drainTo(Q q) { - synchronized (this.mutex) { - return this.drainTo_(q); - } - } - - /** - * Pre-condition: synchronized - */ - private > Q drainTo_(Q q) { - boolean changed = false; - while ( ! this.queue.isEmpty()) { - q.enqueue(this.queue.dequeue()); - changed = true; - } - if (changed) { - this.mutex.notifyAll(); - } - return q; - } - - /** - * Return the object the queue locks on while performing - * its operations. - */ - public Object getMutex() { - return this.mutex; - } - - - // ********** standard methods ********** - - @Override - public String toString() { - synchronized (this.mutex) { - return this.queue.toString(); - } - } - - private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { - synchronized (this.mutex) { - s.defaultWriteObject(); - } - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedStack.java deleted file mode 100644 index 4f4381512c..0000000000 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/collection/SynchronizedStack.java +++ /dev/null @@ -1,494 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2015 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.internal.collection; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EmptyStackException; -import java.util.Iterator; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.command.Command; - -/** - * Thread-safe implementation of the {@link Stack} interface. - * This also provides protocol for suspending a thread until the - * stack is empty or not empty, with optional time-outs. - * @param the type of elements maintained by the stack - * @see StackTools - */ -public class SynchronizedStack - implements Stack, Serializable -{ - /** Backing stack. */ - private final Stack stack; - - /** Object to synchronize on. */ - private final Object mutex; - - private static final long serialVersionUID = 1L; - - - // ********** constructors ********** - - /** - * Construct a synchronized stack that wraps the - * specified stack and locks on the specified mutex. - */ - public SynchronizedStack(Stack stack, Object mutex) { - super(); - if ((stack == null) || (mutex == null)) { - throw new NullPointerException(); - } - this.stack = stack; - this.mutex = mutex; - } - - /** - * Construct a synchronized stack that wraps the - * specified stack and locks on itself. - */ - public SynchronizedStack(Stack stack) { - super(); - if (stack == null) { - throw new NullPointerException(); - } - this.stack = stack; - this.mutex = this; - } - - /** - * Construct an empty synchronized stack that locks on the specified mutex. - */ - public SynchronizedStack(Object mutex) { - this(new LinkedStack(), mutex); - } - - /** - * Construct an empty synchronized stack that locks on itself. - */ - public SynchronizedStack() { - this(new LinkedStack()); - } - - - // ********** Stack implementation ********** - - public void push(E element) { - synchronized (this.mutex) { - this.push_(element); - } - } - - /** - * Pre-condition: synchronized - */ - private void push_(E element) { - this.stack.push(element); - this.mutex.notifyAll(); - } - - public E pop() { - synchronized (this.mutex) { - return this.pop_(); - } - } - - /** - * Pre-condition: synchronized - */ - private E pop_() { - E o = this.stack.pop(); - this.mutex.notifyAll(); - return o; - } - - public E peek() { - synchronized (this.mutex) { - return this.stack.peek(); - } - } - - public boolean isEmpty() { - synchronized (this.mutex) { - return this.stack.isEmpty(); - } - } - - - // ********** indefinite waits ********** - - /** - * Suspend the current thread until the stack's empty status changes - * to the specified value. - */ - public void waitUntilEmptyIs(boolean empty) throws InterruptedException { - synchronized (this.mutex) { - this.waitUntilEmptyIs_(empty); - } - } - - /** - * Pre-condition: synchronized - */ - private void waitUntilEmptyIs_(boolean empty) throws InterruptedException { - while (this.stack.isEmpty() != empty) { - this.mutex.wait(); - } - } - - /** - * Suspend the current thread until the stack is empty. - */ - public void waitUntilEmpty() throws InterruptedException { - this.waitUntilEmptyIs(true); - } - - /** - * Suspend the current thread until the stack has something on it. - */ - public void waitUntilNotEmpty() throws InterruptedException { - this.waitUntilEmptyIs(false); - } - - /** - * Suspend the current thread until the stack is empty, - * then "push" the specified item on to the top of the stack - * and continue executing. - */ - public void waitToPush(E element) throws InterruptedException { - synchronized (this.mutex) { - this.waitUntilEmptyIs_(true); - this.push_(element); - } - } - - /** - * Suspend the current thread until the stack has something on it, - * then "pop" an item from the top of the stack and return it. - */ - public Object waitToPop() throws InterruptedException { - synchronized (this.mutex) { - this.waitUntilEmptyIs_(false); - return this.pop_(); - } - } - - - // ********** timed waits ********** - - /** - * Suspend the current thread until the stack's empty status changes - * to the specified value or the specified time-out occurs. - * The time-out is specified in milliseconds. Return true if the specified - * empty status was achieved; return false if a time-out occurred. - * If the stack's empty status is already the specified value, - * return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitUntilEmptyIs(boolean empty, long timeout) throws InterruptedException { - synchronized (this.mutex) { - return this.waitUntilEmptyIs_(empty, timeout); - } - } - - /** - * Pre-condition: synchronized - */ - private boolean waitUntilEmptyIs_(boolean empty, long timeout) throws InterruptedException { - if (timeout == 0L) { - this.waitUntilEmptyIs_(empty); // wait indefinitely until notified - return true; // if it ever comes back, the condition was met - } - - long stop = System.currentTimeMillis() + timeout; - long remaining = timeout; - while ((this.stack.isEmpty() != empty) && (remaining > 0L)) { - this.mutex.wait(remaining); - remaining = stop - System.currentTimeMillis(); - } - return (this.stack.isEmpty() == empty); - } - - /** - * Suspend the current thread until the stack is empty - * or the specified time-out occurs. - * The time-out is specified in milliseconds. Return true if - * the stack is empty; return false if a time-out occurred. - * If the stack is already empty, return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitUntilEmpty(long timeout) throws InterruptedException { - return this.waitUntilEmptyIs(true, timeout); - } - - /** - * Suspend the current thread until the stack has something on it. - * or the specified time-out occurs. - * The time-out is specified in milliseconds. Return true if - * the stack is not empty; return false if a time-out occurred. - * If the stack already has something on it, return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitUntilNotEmpty(long timeout) throws InterruptedException { - return this.waitUntilEmptyIs(false, timeout); - } - - /** - * Suspend the current thread until the stack is empty, - * then "push" the specified item on to the top of the stack - * and continue executing. If the stack is not emptied out - * before the time-out, simply continue executing without - * "pushing" the item. - * The time-out is specified in milliseconds. Return true if the - * item was pushed; return false if a time-out occurred. - * If the stack is already empty, "push" the specified item and - * return true immediately. - * If the time-out is zero, wait indefinitely. - */ - public boolean waitToPush(E element, long timeout) throws InterruptedException { - synchronized (this.mutex) { - boolean success = this.waitUntilEmptyIs_(true, timeout); - if (success) { - this.push_(element); - } - return success; - } - } - - /** - * Suspend the current thread until the stack has something on it, - * then "pop" an item from the top of the stack and return it. - * If the stack is empty and nothing is "pushed" on to it before the - * time-out, throw an empty stack exception. - * The time-out is specified in milliseconds. - * If the stack is not empty, "pop" an item and - * return it immediately. - * If the time-out is zero, wait indefinitely. - */ - public Object waitToPop(long timeout) throws InterruptedException { - synchronized (this.mutex) { - boolean success = this.waitUntilEmptyIs_(false, timeout); - if (success) { - return this.pop_(); - } - throw new EmptyStackException(); - } - } - - - // ********** synchronized behavior ********** - - /** - * If the current thread is not interrupted, execute the specified command - * with the mutex locked. This is useful for initializing the stack in another - * thread. - */ - public void execute(Command command) throws InterruptedException { - if (Thread.currentThread().isInterrupted()) { - throw new InterruptedException(); - } - synchronized (this.mutex) { - command.execute(); - } - } - - - // ********** additional public protocol ********** - - /** - * "Push" all the elements returned by the specified iterable. - */ - public void pushAll(Iterable iterable) { - this.pushAll(iterable.iterator()); - } - - /** - * "Push" all the elements returned by the specified iterator. - */ - public void pushAll(Iterator iterator) { - synchronized (this.mutex) { - this.pushAll_(iterator); - } - } - - /** - * Pre-condition: synchronized - */ - private void pushAll_(Iterator iterator) { - while (iterator.hasNext()) { - this.push_(iterator.next()); - } - } - - /** - * "Push" all the elements in the specified array. - */ - public void pushAll(E... array) { - synchronized (this.mutex) { - this.pushAll_(array); - } - } - - /** - * Pre-condition: synchronized - */ - private void pushAll_(E[] array) { - for (E element : array) { - this.push_(element); - } - } - - /** - * Pop all the elements from the specified stack and "push" them. - */ - public void pushAll(Stack s) { - synchronized (this.mutex) { - this.pushAll_(s); - } - } - - /** - * Pre-condition: synchronized - */ - private void pushAll_(Stack s) { - while ( ! s.isEmpty()) { - this.push_(s.pop()); - } - } - - /** - * "Dequeue" all the elements from the second specified queue and - * "push" them. - * @see #popAllTo(Queue) - */ - public void pushAll(Queue queue) { - synchronized (this.mutex) { - this.pushAll_(queue); - } - } - - /** - * Pre-condition: synchronized - */ - private void pushAll_(Queue queue) { - while ( ! queue.isEmpty()) { - this.push_(queue.dequeue()); - } - } - - /** - * Pop all the current items from the stack and return them in a list. - */ - public Iterable popAll() { - return this.popAllTo(new ArrayList()); - } - - /** - * Pop all the current items from the stack into specified collection. - * Return the collection. - */ - public > C popAllTo(C c) { - synchronized (this.mutex) { - return this.popAllTo_(c); - } - } - - /** - * Pre-condition: synchronized - */ - private > C popAllTo_(C c) { - boolean changed = false; - while ( ! this.stack.isEmpty()) { - c.add(this.stack.pop()); - changed = true; - } - if (changed) { - this.mutex.notifyAll(); - } - return c; - } - - /** - * Pop all the current items from the stack into specified stack. - * Return the stack. - */ - public > S popAllTo(S s) { - synchronized (this.mutex) { - return this.popAllTo_(s); - } - } - - /** - * Pre-condition: synchronized - */ - private > S popAllTo_(S s) { - boolean changed = false; - while ( ! this.stack.isEmpty()) { - s.push(this.stack.pop()); - changed = true; - } - if (changed) { - this.mutex.notifyAll(); - } - return s; - } - - /** - * Pop all the current items from the stack into specified queue. - * Return the specified queue. - * @see #pushAll(Queue) - */ - public > Q popAllTo(Q queue) { - synchronized (this.mutex) { - return this.popAllTo_(queue); - } - } - - /** - * Pre-condition: synchronized - */ - private > Q popAllTo_(Q queue) { - boolean changed = false; - while ( ! this.stack.isEmpty()) { - queue.enqueue(this.stack.pop()); - changed = true; - } - if (changed) { - this.mutex.notifyAll(); - } - return queue; - } - - /** - * Return the object the stack locks on while performing - * its operations. - */ - public Object getMutex() { - return this.mutex; - } - - - // ********** standard methods ********** - - @Override - public String toString() { - synchronized (this.mutex) { - return this.stack.toString(); - } - } - - private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { - synchronized (this.mutex) { - s.defaultWriteObject(); - } - } -} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractAsynchronousCommandContext.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractAsynchronousCommandContext.java index 09c0ff9547..cc4bf69ee3 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractAsynchronousCommandContext.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractAsynchronousCommandContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -16,8 +16,9 @@ import org.eclipse.jpt.common.utility.exception.ExceptionHandler; import org.eclipse.jpt.common.utility.internal.ConsumerThreadCoordinator; import org.eclipse.jpt.common.utility.internal.ObjectTools; import org.eclipse.jpt.common.utility.internal.SimpleThreadFactory; -import org.eclipse.jpt.common.utility.internal.collection.SynchronizedQueue; import org.eclipse.jpt.common.utility.internal.exception.RuntimeExceptionHandler; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.queue.SynchronizedQueue; /** * This command context will dispatch commands to be executed in a separate @@ -44,7 +45,7 @@ public abstract class AbstractAsynchronousCommandContext commands = new SynchronizedQueue(); + private final SynchronizedQueue commands = QueueTools.synchronizedQueue(); /** * Most of the thread-related behavior is delegated to this coordinator. diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractQueueingCommandContext.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractQueueingCommandContext.java index 0373d7ff94..71d7c77a03 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractQueueingCommandContext.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractQueueingCommandContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2013 Oracle. All rights reserved. + * Copyright (c) 2012, 2015 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. @@ -12,7 +12,7 @@ package org.eclipse.jpt.common.utility.internal.command; import org.eclipse.jpt.common.utility.command.Command; import org.eclipse.jpt.common.utility.command.StatefulCommandContext; import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.internal.collection.LinkedQueue; +import org.eclipse.jpt.common.utility.internal.queue.LinkedQueue; import org.eclipse.jpt.common.utility.internal.reference.SynchronizedBoolean; /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractSingleUseQueueingCommandContext.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractSingleUseQueueingCommandContext.java index 25df4431fd..b2a71b9c92 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractSingleUseQueueingCommandContext.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/command/AbstractSingleUseQueueingCommandContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2013 Oracle. All rights reserved. + * Copyright (c) 2012, 2015 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. @@ -12,7 +12,7 @@ package org.eclipse.jpt.common.utility.internal.command; import org.eclipse.jpt.common.utility.command.Command; import org.eclipse.jpt.common.utility.command.StatefulCommandContext; import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.internal.collection.LinkedQueue; +import org.eclipse.jpt.common.utility.internal.queue.LinkedQueue; /** * This is a command context that queues up any commands that are diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractArrayDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractArrayDeque.java new file mode 100644 index 0000000000..e894d76821 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractArrayDeque.java @@ -0,0 +1,203 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; + +/** + * Abstract array implementation of the {@link Deque} interface. + * @param the type of elements maintained by the deque + */ +public abstract class AbstractArrayDeque + implements Deque, Cloneable, Serializable +{ + protected transient E[] elements; + + /** Index of head element */ + protected transient int head = 0; + + /** Index of the next tail element. */ + protected transient int tail = 0; + + protected int size = 0; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty deque with the specified initial capacity. + */ + @SuppressWarnings("unchecked") + protected AbstractArrayDeque(int initialCapacity) { + super(); + if (initialCapacity < 0) { + throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ + } + this.elements = (E[]) new Object[initialCapacity]; + } + + + // ********** Deque implementation ********** + + public void enqueueTail(E element) { + this.elements[this.tail] = element; + if (++this.tail == this.elements.length) { + this.tail = 0; + } + this.size++; + } + + public void enqueueHead(E element) { + if (this.head == 0) { + this.head = this.elements.length; + } + this.elements[--this.head] = element; + this.size++; + } + + public E dequeueHead() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + E element = this.elements[this.head]; + this.elements[this.head] = null; // allow GC to work + if (++this.head == this.elements.length) { + this.head = 0; + } + this.size--; + return element; + } + + public E dequeueTail() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + if (this.tail == 0) { + this.tail = this.elements.length; + } + E element = this.elements[--this.tail]; + this.elements[this.tail] = null; // allow GC to work + this.size--; + return element; + } + + public E peekHead() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + return this.elements[this.head]; + } + + public E peekTail() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + int index = (this.tail == 0) ? this.elements.length : this.tail; + return this.elements[--index]; + } + + public boolean isEmpty() { + return this.size == 0; + } + + + // ********** standard methods ********** + + @Override + public AbstractArrayDeque clone() { + try { + @SuppressWarnings("unchecked") + AbstractArrayDeque clone = (AbstractArrayDeque) super.clone(); + @SuppressWarnings("cast") + E[] array = (E[]) this.elements.clone(); + clone.elements = array; + return clone; + } catch (CloneNotSupportedException ex) { + throw new InternalError(); + } + } + + @Override + public String toString() { + return Arrays.toString(this.copyElements(this.size)); + } + + protected E[] copyElements(int newCapacity) { + @SuppressWarnings("unchecked") + E[] newElements = (E[]) new Object[newCapacity]; + if (this.size != 0) { + Object oldElements[] = this.elements; + int t = this.tail; + if (t == 0) { + t = oldElements.length; + } + if (this.head < t) { + // elements are contiguous + System.arraycopy(oldElements, this.head, newElements, 0, this.size); + } else { + // elements wrap past end of array + int fragmentSize = oldElements.length - this.head; + System.arraycopy(oldElements, this.head, newElements, 0, fragmentSize); + System.arraycopy(oldElements, 0, newElements, fragmentSize, (this.size - fragmentSize)); + } + } + return newElements; + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write size (and any hidden stuff) + stream.defaultWriteObject(); + Object[] array = this.elements; + int elementsLength = array.length; + stream.writeInt(elementsLength); + if (this.size == 0) { + return; + } + // save the elements in contiguous order + int t = this.tail; + if (t == 0) { + t = elementsLength; + } + if (this.head < t) { // elements are contiguous + for (int i = this.head; i < t; i++) { + stream.writeObject(array[i]); + } + } else { // (this.head >= t) - elements wrap past end of array + for (int i = this.head; i < elementsLength; i++) { + stream.writeObject(array[i]); + } + for (int i = 0; i < this.tail; i++) { + stream.writeObject(array[i]); + } + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read size (and any hidden stuff) + stream.defaultReadObject(); + int elementsLength = stream.readInt(); + Object[] array = new Object[elementsLength]; + for (int i = 0; i < this.size; i++) { + array[i] = stream.readObject(); + } + this.elements = (E[]) array; + this.head = 0; + this.tail = this.size; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractPriorityDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractPriorityDeque.java new file mode 100644 index 0000000000..e2b01d7776 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/AbstractPriorityDeque.java @@ -0,0 +1,396 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.deque; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Comparator; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.InputRestrictedDeque; +import org.eclipse.jpt.common.utility.internal.ArrayTools; + +/** + * Abstract priority implementation of the {@link InputRestrictedDeque} interface. + * Elements will dequeue from the deque's head in the order determined by a comparator + * (i.e. {@link #dequeueHead} will return the element sorted first + * while {@link #dequeueTail} will return the element sorted last). + * @param the type of elements maintained by the deque + */ +public abstract class AbstractPriorityDeque + implements InputRestrictedDeque, Cloneable, Serializable +{ + protected final Comparator comparator; + + /** + * Standard min-max heap implementation. + * To simplify our math, we leave the first slot [0] empty. + */ + protected transient E[] elements; + + protected int size = 0; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty priority deque with the specified comparator + * and initial capacity. + */ + @SuppressWarnings("unchecked") + protected AbstractPriorityDeque(Comparator comparator, int initialCapacity) { + super(); + if (comparator == null) { + throw new NullPointerException(); + } + this.comparator = comparator; + if (initialCapacity < 0) { + throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ + } + + this.elements = (E[]) new Object[initialCapacity + 1]; + } + + + // ********** Deque implementation ********** + + /** + * The element is not enqueued strictly to the deque's tail; + * it is placed in its proper position, as determined by the + * deque's priority comparator. + */ + public void enqueueTail(E element) { + this.enqueue(element); + } + + public void enqueue(E element) { + this.size++; + int current = this.size; + this.elements[current] = element; + int parent = current >> 1; + if (parent == 0) { + return; + } + + int level = 31 - Integer.numberOfLeadingZeros(current); // 'current' is never zero + if ((level & 1) == 0) { // even levels are min levels (top level is zero) + if (this.comparator.compare(this.elements[current], this.elements[parent]) > 0) { + // move to max level before bubbling up + ArrayTools.swap(this.elements, current, parent); + current = parent; + int gp = current >> 2; + while ((gp != 0) && this.comparator.compare(this.elements[current], this.elements[gp]) > 0) { + ArrayTools.swap(this.elements, current, gp); + current = gp; + gp = current >> 2; + } + } else { + // bubble up min levels + int gp = current >> 2; + while ((gp != 0) && this.comparator.compare(this.elements[current], this.elements[gp]) < 0) { + ArrayTools.swap(this.elements, current, gp); + current = gp; + gp = current >> 2; + } + } + } else { // max level + if (this.comparator.compare(this.elements[current], this.elements[parent]) < 0) { + // move to min level before bubbling up + ArrayTools.swap(this.elements, current, parent); + current = parent; + int gp = current >> 2; + while ((gp != 0) && this.comparator.compare(this.elements[current], this.elements[gp]) < 0) { + ArrayTools.swap(this.elements, current, gp); + current = gp; + gp = current >> 2; + } + } else { + // bubble up max levels + int gp = current >> 2; + while ((gp != 0) && this.comparator.compare(this.elements[current], this.elements[gp]) > 0) { + ArrayTools.swap(this.elements, current, gp); + current = gp; + gp = current >> 2; + } + } + } + } + +// reduce the redundant code, but add more conditional logic +// public void enqueue(E element) { +// this.size++; +// int current = this.size; +// this.elements[current] = element; +// int parent = current >> 1; +// if (parent == 0) { +// return; +// } +// +// int level = 31 - Integer.numberOfLeadingZeros(current); // 'current' is never zero +// boolean minLevel = (level & 1) == 0; +// int first = minLevel ? current : parent; +// int second = minLevel ? parent : current; +// if (this.comparator.compare(this.elements[first], this.elements[second]) > 0) { +// ArrayTools.swap(this.elements, current, parent); +// minLevel = ! minLevel; +// current = parent; +// } +// int gp = current >> 2; +// while (gp != 0) { +// first = minLevel ? current : gp; +// second = minLevel ? gp : current; +// if (this.comparator.compare(this.elements[first], this.elements[second]) > 0) { +// break; +// } +// ArrayTools.swap(this.elements, current, gp); +// current = gp; +// gp = current >> 2; +// } +// } + + /** + * Dequeue first/min element. + */ + public E dequeueHead() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + E element = this.elements[1]; + if (this.size != 1) { + // replace root with last node and move it to its new position + ArrayTools.swap(this.elements, 1, this.size); + this.trickleDownMin(1, this.size - 1); + } + this.elements[this.size] = null; // allow GC to work + this.size--; + return element; + } + + private void trickleDownMin(int index, int newSize) { + int minChildIndex = index << 1; // left child + if (minChildIndex > newSize) { + return; // no children + } + + E element = this.elements[index]; + E minChild = this.elements[minChildIndex]; + int rightChildIndex = minChildIndex + 1; + if (rightChildIndex > newSize) { + // no right child; and, therefore, no possible grandchildren + if (this.comparator.compare(minChild, element) < 0) { + ArrayTools.swap(this.elements, minChildIndex, index); + } + return; + } + + E rightChild = this.elements[rightChildIndex]; + if (this.comparator.compare(rightChild, minChild) < 0) { + // right child exists and is less than left + minChildIndex = rightChildIndex; + minChild = rightChild; + } + + // now find min grandchild + int minGCIndex = -1; + E minGC = null; + int i = index << 2; // leftmost grandchild + if (i <= newSize) { + minGCIndex = i; + minGC = this.elements[i]; + int last = Math.min(i + 3, newSize); + while (++i <= last) { + E temp = this.elements[i]; + if (this.comparator.compare(temp, minGC) < 0) { + minGCIndex = i; + minGC = temp; + } + } + } + + if ((minGC != null) && (this.comparator.compare(minGC, minChild) < 0)) { + // min descendant is a grandchild + if (this.comparator.compare(minGC, element) < 0) { + ArrayTools.swap(this.elements, minGCIndex, index); + int parentIndex = minGCIndex >> 1; // 'element' is now at 'minGCIndex' + if (this.comparator.compare(element, this.elements[parentIndex]) > 0) { + // move element to max level + ArrayTools.swap(this.elements, minGCIndex, parentIndex); + } + this.trickleDownMin(minGCIndex, newSize); // recurse - still on a min level + } + } else { + // min is a direct child and, therefore, has no children itself (since it would have to be greater than its children) + if (this.comparator.compare(minChild, element) < 0) { + ArrayTools.swap(this.elements, minChildIndex, index); + } + } + } + + /** + * Dequeue last/max element. + */ + public E dequeueTail() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + int index = (this.size == 1) ? 1 : (this.size == 2) ? 2 : (this.comparator.compare(this.elements[2], this.elements[3]) > 0) ? 2 : 3; + E element = this.elements[index]; + if (this.size != 1) { + // replace removed element with last node and move it to its new position + ArrayTools.swap(this.elements, index, this.size); + this.trickleDownMax(index, this.size - 1); + } + this.elements[this.size] = null; // allow GC to work + this.size--; + return element; + } + + private void trickleDownMax(int index, int newSize) { + int maxChildIndex = index << 1; // left child + if (maxChildIndex > newSize) { + return; // no children + } + + E element = this.elements[index]; + E maxChild = this.elements[maxChildIndex]; + int rightChildIndex = maxChildIndex + 1; + if (rightChildIndex > newSize) { + // no right child; and, therefore, no possible grandchildren + if (this.comparator.compare(maxChild, element) > 0) { + ArrayTools.swap(this.elements, maxChildIndex, index); + } + return; + } + + E rightChild = this.elements[rightChildIndex]; + if (this.comparator.compare(rightChild, maxChild) > 0) { + // right child exists and is greater than left + maxChildIndex = rightChildIndex; + maxChild = rightChild; + } + + // now find max grandchild + int maxGCIndex = -1; + E maxGC = null; + int i = index << 2; // leftmost grandchild + if (i <= newSize) { + maxGCIndex = i; + maxGC = this.elements[i]; + int last = Math.min(i + 3, newSize); + while (++i <= last) { + E temp = this.elements[i]; + if (this.comparator.compare(temp, maxGC) > 0) { + maxGCIndex = i; + maxGC = temp; + } + } + } + + if ((maxGC != null) && (this.comparator.compare(maxGC, maxChild) > 0)) { + // max descendant is a grandchild + if (this.comparator.compare(maxGC, element) > 0) { + ArrayTools.swap(this.elements, maxGCIndex, index); + int parentIndex = maxGCIndex >> 1; // 'element' is now at 'maxGCIndex' + if (this.comparator.compare(element, this.elements[parentIndex]) < 0) { + // move element to min level + ArrayTools.swap(this.elements, maxGCIndex, parentIndex); + } + this.trickleDownMax(maxGCIndex, newSize); // recurse - still on a max level + } + } else { + // max is a direct child and, therefore, has no children itself (since it would have to be less than its children) + if (this.comparator.compare(maxChild, element) > 0) { + ArrayTools.swap(this.elements, maxChildIndex, index); + } + } + } + + /** + * Return first/min element. + */ + public E peekHead() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + return this.elements[1]; + } + + /** + * Return last/max element. + */ + public E peekTail() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + if (this.size == 1) { + return this.elements[1]; + } + E left = this.elements[2]; + if (this.size == 2) { + return left; + } + E right = this.elements[3]; + return (this.comparator.compare(left, right) > 0) ? left : right; + } + + public boolean isEmpty() { + return this.size == 0; + } + + + // ********** standard methods ********** + + @Override + public AbstractPriorityDeque clone() { + try { + @SuppressWarnings("unchecked") + AbstractPriorityDeque clone = (AbstractPriorityDeque) super.clone(); + @SuppressWarnings("cast") + E[] array = (E[]) this.elements.clone(); + clone.elements = array; + return clone; + } catch (CloneNotSupportedException ex) { + throw new InternalError(); + } + } + + @Override + public String toString() { + return Arrays.toString(ArrayTools.subArray(this.elements, 1, this.size + 1)); + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write comparator and size (and any hidden stuff) + stream.defaultWriteObject(); + stream.writeInt(this.elements.length); + if (this.size == 0) { + return; + } + for (int i = 1; i <= this.size; i++) { // skip 0 + stream.writeObject(this.elements[i]); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read comparator and size (and any hidden stuff) + stream.defaultReadObject(); + int elementsLength = stream.readInt(); + Object[] array = new Object[elementsLength]; + for (int i = 1; i <= this.size; i++) { // skip 0 + array[i] = stream.readObject(); + } + this.elements = (E[]) array; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ArrayDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ArrayDeque.java new file mode 100644 index 0000000000..4e29e598ca --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ArrayDeque.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import org.eclipse.jpt.common.utility.deque.Deque; + +/** + * Resizable-array implementation of the {@link Deque} interface. + * @param the type of elements maintained by the deque + * @see FixedCapacityArrayDeque + * @see DequeTools + */ +public class ArrayDeque + extends AbstractArrayDeque +{ + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty deque with the specified initial capacity. + */ + public ArrayDeque(int initialCapacity) { + super(initialCapacity); + } + + + // ********** Deque implementation ********** + + @Override + public void enqueueTail(E element) { + this.ensureCapacity(this.size + 1); + super.enqueueTail(element); + } + + @Override + public void enqueueHead(E element) { + this.ensureCapacity(this.size + 1); + super.enqueueHead(element); + } + + /** + * Increase the deque's capacity, if necessary, to ensure it has at least + * the specified minimum capacity. + */ + public void ensureCapacity(int minCapacity) { + int oldCapacity = this.elements.length; + if (oldCapacity < minCapacity) { + int newCapacity = ((oldCapacity * 3) >> 1) + 1; + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + this.elements = this.copyElements(newCapacity); + this.head = 0; + this.tail = this.size; + } + } + + /** + * Decrease the deque's capacity, if necessary, to match its current size. + */ + public void trimToSize() { + if (this.elements.length > this.size) { + this.elements = this.copyElements(this.size); + this.head = 0; + this.tail = this.size; + } + } + + + // ********** standard methods ********** + + @Override + public ArrayDeque clone() { + return (ArrayDeque) super.clone(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/DequeTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/DequeTools.java new file mode 100644 index 0000000000..aedc7296db --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/DequeTools.java @@ -0,0 +1,799 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.deque; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.collection.MapTools; +import org.eclipse.jpt.common.utility.internal.comparator.ComparatorTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; + +/** + * {@link Deque} utility methods. + */ +public final class DequeTools { + + // ********** enqueue all ********** + + /** + * Enqueue all the elements returned by the specified iterable + * on the specified deque's tail. + * Return whether the deque changed as a result. + */ + public static boolean enqueueTailAll(Deque deque, Iterable iterable) { + return enqueueTailAll(deque, iterable.iterator()); + } + + /** + * Enqueue all the elements returned by the specified iterable + * on the specified deque's head. + * Return whether the deque changed as a result. + */ + public static boolean enqueueHeadAll(Deque deque, Iterable iterable) { + return enqueueHeadAll(deque, iterable.iterator()); + } + + /** + * Enqueue all the elements returned by the specified iterator + * on the specified deque's tail. + * Return whether the deque changed as a result. + */ + public static boolean enqueueTailAll(Deque deque, Iterator iterator) { + return iterator.hasNext() && enqueueTailAll_(deque, iterator); + } + + /** + * assume the iterator is not empty + */ + private static boolean enqueueTailAll_(Deque deque, Iterator iterator) { + do { + deque.enqueueTail(iterator.next()); + } while (iterator.hasNext()); + return true; + } + + /** + * Enqueue all the elements returned by the specified iterator + * on the specified deque's head. + * Return whether the deque changed as a result. + */ + public static boolean enqueueHeadAll(Deque deque, Iterator iterator) { + return iterator.hasNext() && enqueueHeadAll_(deque, iterator); + } + + /** + * assume the iterator is not empty + */ + private static boolean enqueueHeadAll_(Deque deque, Iterator iterator) { + do { + deque.enqueueHead(iterator.next()); + } while (iterator.hasNext()); + return true; + } + + /** + * Enqueue all the elements in the specified array + * on the specified deque's tail. + * Return whether the deque changed as a result. + */ + public static boolean enqueueTailAll(Deque deque, E... array) { + int len = array.length; + return (len != 0) && enqueueTailAll_(deque, array, len); + } + + /** + * assume the array is not empty + */ + private static boolean enqueueTailAll_(Deque deque, E[] array, int arrayLength) { + int i = 0; + do { + deque.enqueueTail(array[i++]); + } while (i < arrayLength); + return true; + } + + /** + * Enqueue all the elements in the specified array + * on the specified deque's head. + * Return whether the deque changed as a result. + */ + public static boolean enqueueHeadAll(Deque deque, E... array) { + int len = array.length; + return (len != 0) && enqueueHeadAll_(deque, array, len); + } + + /** + * assume the array is not empty + */ + private static boolean enqueueHeadAll_(Deque deque, E[] array, int arrayLength) { + int i = 0; + do { + deque.enqueueHead(array[i++]); + } while (i < arrayLength); + return true; + } + + + // ********** drain ********** + + /** + * Drain all the elements from the specified deque's head and return them in a + * list. + */ + public static ArrayList drainHead(Deque deque) { + ArrayList result = new ArrayList(); + drainHeadTo(deque, result); + return result; + } + + /** + * Drain all the elements from the specified deque's tail and return them in a + * list. + */ + public static ArrayList drainTail(Deque deque) { + ArrayList result = new ArrayList(); + drainTailTo(deque, result); + return result; + } + + /** + * Drain all the elements from the specified deque's head and add them to the + * specified collection. + * Return whether the deque changed as a result. + */ + public static boolean drainHeadTo(Deque deque, Collection collection) { + return ( ! deque.isEmpty()) && drainHeadTo_(deque, collection); + } + + /** + * assume the deque is not empty + */ + private static boolean drainHeadTo_(Deque deque, Collection collection) { + do { + collection.add(deque.dequeueHead()); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's tail and add them to the + * specified collection. + * Return whether the deque changed as a result. + */ + public static boolean drainTailTo(Deque deque, Collection collection) { + return ( ! deque.isEmpty()) && drainTailTo_(deque, collection); + } + + /** + * assume the deque is not empty + */ + private static boolean drainTailTo_(Deque deque, Collection collection) { + do { + collection.add(deque.dequeueTail()); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's head + * to the specified list at the specified index. + * Return whether the deque changed as a result. + */ + public static boolean drainHeadTo(Deque deque, List list, int index) { + return ( ! deque.isEmpty()) && drainHeadTo_(deque, list, index); + } + + /** + * assume the deque is not empty + */ + private static boolean drainHeadTo_(Deque deque, List list, int index) { + return (index == list.size()) ? drainHeadTo_(deque, list) : list.addAll(index, drainHead(deque)); + } + + /** + * Drain all the elements from the specified deque's tail + * to the specified list at the specified index. + * Return whether the deque changed as a result. + */ + public static boolean drainTailTo(Deque deque, List list, int index) { + return ( ! deque.isEmpty()) && drainTailTo_(deque, list, index); + } + + /** + * assume the deque is not empty + */ + private static boolean drainTailTo_(Deque deque, List list, int index) { + return (index == list.size()) ? drainTailTo_(deque, list) : list.addAll(index, drainTail(deque)); + } + + /** + * Drain all the elements from the specified deque's head and push them on the + * specified stack. + * Return whether the deque changed as a result. + */ + public static boolean drainHeadTo(Deque deque, Stack stack) { + return ( ! deque.isEmpty()) && drainHeadTo_(deque, stack); + } + + /** + * assume the deque is not empty + */ + private static boolean drainHeadTo_(Deque deque, Stack stack) { + do { + stack.push(deque.dequeueHead()); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's tail and push them on the + * specified stack. + * Return whether the deque changed as a result. + */ + public static boolean drainTailTo(Deque deque, Stack stack) { + return ( ! deque.isEmpty()) && drainTailTo_(deque, stack); + } + + /** + * assume the deque is not empty + */ + private static boolean drainTailTo_(Deque deque, Stack stack) { + do { + stack.push(deque.dequeueTail()); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's head and enqueue them + * on the specified queue. + * Return whether the deque changed as a result. + */ + public static boolean drainHeadTo(Deque deque, Queue queue) { + return ( ! deque.isEmpty()) && drainHeadTo_(deque, queue); + } + + /** + * assume the deque is not empty + */ + private static boolean drainHeadTo_(Deque deque, Queue queue) { + do { + queue.enqueue(deque.dequeueHead()); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's tail and enqueue them + * on the specified queue. + * Return whether the first deque changed as a result. + */ + public static boolean drainTailTo(Deque deque, Queue queue) { + return ( ! deque.isEmpty()) && drainTailTo_(deque, queue); + } + + /** + * assume the deque is not empty + */ + private static boolean drainTailTo_(Deque deque, Queue queue) { + do { + queue.enqueue(deque.dequeueTail()); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the first specified deque's head and enqueue them + * on the second specified deque's tail. + * Return whether the first deque changed as a result. + */ + public static boolean drainHeadTo(Deque deque1, Deque deque2) { + return ( ! deque1.isEmpty()) && drainHeadTo_(deque1, deque2); + } + + /** + * assume deque 1 is not empty + */ + private static boolean drainHeadTo_(Deque deque1, Deque deque2) { + do { + deque2.enqueueTail(deque1.dequeueHead()); + } while ( ! deque1.isEmpty()); + return true; + } + + /** + * Drain all the elements from the first specified deque's tail and enqueue them + * on the second specified deque's head. + * Return whether the first deque changed as a result. + */ + public static boolean drainTailTo(Deque deque1, Deque deque2) { + return ( ! deque1.isEmpty()) && drainTailTo_(deque1, deque2); + } + + /** + * assume deque 1 is not empty + */ + private static boolean drainTailTo_(Deque deque1, Deque deque2) { + do { + deque2.enqueueHead(deque1.dequeueTail()); + } while ( ! deque1.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's head, passing each element to the + * specified key transformer. Map the generated key to its element. + */ + public static boolean drainHeadTo(Deque deque, Map map, Transformer keyTransformer) { + return ( ! deque.isEmpty()) && drainHeadTo_(deque, map, keyTransformer); + } + + /** + * assume the deque is not empty + */ + private static boolean drainHeadTo_(Deque deque, Map map, Transformer keyTransformer) { + do { + MapTools.add(map, deque.dequeueHead(), keyTransformer); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's tail, passing each element to the + * specified key transformer. Map the generated key to its element. + */ + public static boolean drainTailTo(Deque deque, Map map, Transformer keyTransformer) { + return ( ! deque.isEmpty()) && drainTailTo_(deque, map, keyTransformer); + } + + /** + * assume the deque is not empty + */ + private static boolean drainTailTo_(Deque deque, Map map, Transformer keyTransformer) { + do { + MapTools.add(map, deque.dequeueTail(), keyTransformer); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's head, passing each element to the + * specified key and value transformers. Add the generated key/value pairs + * to the specified map. + */ + public static boolean drainHeadTo(Deque deque, Map map, Transformer keyTransformer, Transformer valueTransformer) { + return ( ! deque.isEmpty()) && drainHeadTo_(deque, map, keyTransformer, valueTransformer); + } + + /** + * assume the deque is not empty + */ + private static boolean drainHeadTo_(Deque deque, Map map, Transformer keyTransformer, Transformer valueTransformer) { + do { + MapTools.add(map, deque.dequeueHead(), keyTransformer, valueTransformer); + } while ( ! deque.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified deque's tail, passing each element to the + * specified key and value transformers. Add the generated key/value pairs + * to the specified map. + */ + public static boolean drainTailTo(Deque deque, Map map, Transformer keyTransformer, Transformer valueTransformer) { + return ( ! deque.isEmpty()) && drainTailTo_(deque, map, keyTransformer, valueTransformer); + } + + /** + * assume the deque is not empty + */ + private static boolean drainTailTo_(Deque deque, Map map, Transformer keyTransformer, Transformer valueTransformer) { + do { + MapTools.add(map, deque.dequeueTail(), keyTransformer, valueTransformer); + } while ( ! deque.isEmpty()); + return true; + } + + + // ********** array deque factory methods ********** + + /** + * Return an empty array-based deque. + */ + public static ArrayDeque arrayDeque() { + return arrayDeque(10); + } + + /** + * Return an empty array-based deque with specified initial capacity. + */ + public static ArrayDeque arrayDeque(int initialCapacity) { + return new ArrayDeque(initialCapacity); + } + + /** + * Return an array-based deque corresponding to the specified iterable. + */ + public static ArrayDeque arrayDeque(Iterable iterable) { + return arrayDeque(iterable.iterator()); + } + + /** + * Return an array-based deque corresponding to the reverse of the specified iterable. + */ + public static ArrayDeque reverseArrayDeque(Iterable iterable) { + return reverseArrayDeque(iterable.iterator()); + } + + /** + * Return an array-based deque corresponding to the specified iterable. + * The specified iterable size is a performance hint. + */ + public static ArrayDeque arrayDeque(Iterable iterable, int iterableSize) { + return arrayDeque(iterable.iterator(), iterableSize); + } + + /** + * Return an array-based deque corresponding to the reverse of the specified iterable. + * The specified iterable size is a performance hint. + */ + public static ArrayDeque reverseArrayDeque(Iterable iterable, int iterableSize) { + return reverseArrayDeque(iterable.iterator(), iterableSize); + } + + /** + * Return an array-based deque corresponding to the specified iterator. + */ + public static ArrayDeque arrayDeque(Iterator iterator) { + ArrayDeque deque = arrayDeque(); + enqueueTailAll(deque, iterator); + return deque; + } + + /** + * Return an array-based deque corresponding to the reverse of the specified iterator. + */ + public static ArrayDeque reverseArrayDeque(Iterator iterator) { + ArrayDeque deque = arrayDeque(); + enqueueHeadAll(deque, iterator); + return deque; + } + + /** + * Return an array-based deque corresponding to the specified iterator. + * The specified iterator size is a performance hint. + */ + public static ArrayDeque arrayDeque(Iterator iterator, int iteratorSize) { + ArrayDeque deque = arrayDeque(iteratorSize); + enqueueTailAll(deque, iterator); + return deque; + } + + /** + * Return an array-based deque corresponding to the reverse of the specified iterator. + * The specified iterator size is a performance hint. + */ + public static ArrayDeque reverseArrayDeque(Iterator iterator, int iteratorSize) { + ArrayDeque deque = arrayDeque(iteratorSize); + enqueueHeadAll(deque, iterator); + return deque; + } + + /** + * Return an array-based deque corresponding to the specified array. + */ + public static ArrayDeque arrayDeque(E... array) { + ArrayDeque deque = arrayDeque(array.length); + enqueueTailAll(deque, array); + return deque; + } + + /** + * Return an array-based deque corresponding to the reverse of the specified array. + */ + public static ArrayDeque reverseArrayDeque(E... array) { + ArrayDeque deque = arrayDeque(array.length); + enqueueHeadAll(deque, array); + return deque; + } + + + // ********** linked deque factory methods ********** + + /** + * Return an empty link-based deque with no node cache. + */ + public static LinkedDeque linkedDeque() { + return linkedDeque(0); + } + + /** + * Return an empty link-based deque + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque linkedDeque(int cacheSize) { + return new LinkedDeque(cacheSize); + } + + /** + * Return a link-based deque corresponding to the specified iterable. + */ + public static LinkedDeque linkedDeque(Iterable iterable) { + return linkedDeque(iterable, 0); + } + + /** + * Return a link-based deque corresponding to the reverse of the specified iterable. + */ + public static LinkedDeque reverseLinkedDeque(Iterable iterable) { + return reverseLinkedDeque(iterable, 0); + } + + /** + * Return a link-based deque corresponding to the specified iterable + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque linkedDeque(Iterable iterable, int cacheSize) { + return linkedDeque(iterable.iterator(), cacheSize); + } + + /** + * Return a link-based deque corresponding to the reverse of the specified iterable + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque reverseLinkedDeque(Iterable iterable, int cacheSize) { + return reverseLinkedDeque(iterable.iterator(), cacheSize); + } + + /** + * Return a link-based deque corresponding to the specified iterator. + */ + public static LinkedDeque linkedDeque(Iterator iterator) { + return linkedDeque(iterator, 0); + } + + /** + * Return a link-based deque corresponding to the reverse of the specified iterator. + */ + public static LinkedDeque reverseLinkedDeque(Iterator iterator) { + return reverseLinkedDeque(iterator, 0); + } + + /** + * Return a link-based deque corresponding to the specified iterator + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque linkedDeque(Iterator iterator, int cacheSize) { + LinkedDeque deque = linkedDeque(cacheSize); + enqueueTailAll(deque, iterator); + return deque; + } + + /** + * Return a link-based deque corresponding to the reverse of the specified iterator + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque reverseLinkedDeque(Iterator iterator, int cacheSize) { + LinkedDeque deque = linkedDeque(cacheSize); + enqueueHeadAll(deque, iterator); + return deque; + } + + /** + * Return a link-based deque corresponding to the specified array. + */ + public static LinkedDeque linkedDeque(E... array) { + return linkedDeque(array, 0); + } + + /** + * Return a link-based deque corresponding to the reverse of the specified array. + */ + public static LinkedDeque reverseLinkedDeque(E... array) { + return reverseLinkedDeque(array, 0); + } + + /** + * Return a link-based deque corresponding to the specified array + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque linkedDeque(E[] array, int cacheSize) { + LinkedDeque deque = linkedDeque(cacheSize); + enqueueTailAll(deque, array); + return deque; + } + + /** + * Return a link-based deque corresponding to the reverse of the specified array + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedDeque reverseLinkedDeque(E[] array, int cacheSize) { + LinkedDeque deque = linkedDeque(cacheSize); + enqueueHeadAll(deque, array); + return deque; + } + + + // ********** fixed size array deque factory methods ********** + + /** + * Return a fixed-capacity array deque with the specified capacity. + */ + public static FixedCapacityArrayDeque fixedCapacityArrayDeque(int capacity) { + return new FixedCapacityArrayDeque(capacity); + } + + /** + * Return a fized-capacity array deque containing the elements of the specified + * collection. The deque will dequeue its head elements in the same + * order they are returned by the collection's iterator (i.e. the + * first element returned by the collection's iterator will be the + * first element returned by {@link Deque#dequeueHead()}). + * The deque's capacity will be match the collection's size. + */ + public static FixedCapacityArrayDeque fixedCapacityArrayDeque(Collection collection) { + FixedCapacityArrayDeque deque = fixedCapacityArrayDeque(collection.size()); + enqueueTailAll(deque, collection); + return deque; + } + + /** + * Return a fized-capacity array deque containing the elements of the specified + * collection. The deque will dequeue its tail elements in the same + * order they are returned by the collection's iterator (i.e. the + * first element returned by the collection's iterator will be the + * first element returned by {@link Deque#dequeueTail()}). + * The deque's capacity will be match the collection's size. + */ + public static FixedCapacityArrayDeque reverseFixedCapacityArrayDeque(Collection collection) { + FixedCapacityArrayDeque deque = fixedCapacityArrayDeque(collection.size()); + enqueueHeadAll(deque, collection); + return deque; + } + + + // ********** priority deque factory methods ********** + + /** + * Return a priority deque that returns its elements in + * {@linkplain Comparable natural order}. + */ + public static > PriorityDeque priorityDeque() { + return priorityDeque(10); + } + + /** + * Return a priority deque that returns its elements in + * {@linkplain Comparable natural order} and has the specified initial capacity. + */ + public static > PriorityDeque priorityDeque(int initialCapacity) { + return priorityDeque(ComparatorTools.naturalComparator(), initialCapacity); + } + + /** + * Return a priority deque whose elements are returned in + * the order determined by the specified comparator. + */ + public static PriorityDeque priorityDeque(Comparator comparator) { + return priorityDeque(comparator, 10); + } + + /** + * Return a priority deque whose elements are returned in + * the order determined by the specified comparator + * and has the specified initial capacity. + */ + public static PriorityDeque priorityDeque(Comparator comparator, int initialCapacity) { + return new PriorityDeque(comparator, initialCapacity); + } + + + // ********** fixed size priority deque factory methods ********** + + /** + * Return a fixed-capacity priority deque that returns its elements in + * {@linkplain Comparable natural order} and has the specified capacity. + */ + public static > FixedCapacityPriorityDeque fixedCapacityPriorityDeque(int capacity) { + return fixedCapacityPriorityDeque(ComparatorTools.naturalComparator(), capacity); + } + + /** + * Return a fixed-capacity priority deque whose elements are returned in + * the order determined by the specified comparator + * and has the specified capacity. + */ + public static FixedCapacityPriorityDeque fixedCapacityPriorityDeque(Comparator comparator, int capacity) { + return new FixedCapacityPriorityDeque(comparator, capacity); + } + + + // ********** synchronized deque factory methods ********** + + /** + * Return a synchronized deque. + */ + public static SynchronizedDeque synchronizedDeque() { + ArrayDeque deque = arrayDeque(); + return synchronizedDeque(deque); + } + + /** + * Return a deque that synchronizes the specified deque. + */ + public static SynchronizedDeque synchronizedDeque(Object mutex) { + ArrayDeque deque = arrayDeque(); + return synchronizedDeque(deque, mutex); + } + + /** + * Return a deque that synchronizes the specified deque. + */ + public static SynchronizedDeque synchronizedDeque(Deque deque) { + return new SynchronizedDeque(deque); + } + + /** + * Return a deque that synchronizes the specified deque + * with specified mutex. + */ + public static SynchronizedDeque synchronizedDeque(Deque deque, Object mutex) { + return new SynchronizedDeque(deque, mutex); + } + + + // ********** misc deque factory methods ********** + + /** + * Adapt the specified list to the {@link Deque} interface. + */ + public static ListDeque adapt(List list) { + return new ListDeque(list); + } + + /** + * Return a deque that reverses the specified deque. + */ + public static Deque reverse(Deque deque) { + return new ReverseDeque(deque); + } + + /** + * Return an unmodifiable empty deque. + */ + public static Deque emptyDeque() { + return EmptyDeque.instance(); + } + + + // ********** constructor ********** + + /** + * Suppress default constructor, ensuring non-instantiability. + */ + private DequeTools() { + super(); + throw new UnsupportedOperationException(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/EmptyDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/EmptyDeque.java new file mode 100644 index 0000000000..7408bfa5d9 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/EmptyDeque.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.io.Serializable; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; + +/** + * Empty implementation of the {@link Deque} interface. + * @param the type of elements maintained by the deque + * @see DequeTools + */ +public final class EmptyDeque + implements Deque, Serializable +{ + @SuppressWarnings("rawtypes") + public static final Deque INSTANCE = new EmptyDeque(); + @SuppressWarnings("unchecked") + public static Deque instance() { + return INSTANCE; + } + + // ensure single instance + private EmptyDeque() { + super(); + } + + public void enqueueTail(E o) { + throw new UnsupportedOperationException(); + } + + public void enqueueHead(E o) { + throw new UnsupportedOperationException(); + } + + public E dequeueHead() { + throw new NoSuchElementException(); + } + + public E dequeueTail() { + throw new NoSuchElementException(); + } + + public E peekHead() { + throw new NoSuchElementException(); + } + + public E peekTail() { + throw new NoSuchElementException(); + } + + public boolean isEmpty() { + return true; + } + + @Override + public String toString() { + return "[]"; //$NON-NLS-1$ + } + + private static final long serialVersionUID = 1L; + private Object readResolve() { + // replace this object with the singleton + return INSTANCE; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityArrayDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityArrayDeque.java new file mode 100644 index 0000000000..e225c55dc1 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityArrayDeque.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import org.eclipse.jpt.common.utility.deque.Deque; + +/** + * Fixed-capacity array implementation of the {@link Deque} interface. + * This implementation will throw an exception if its capacity is exceeded. + * @param the type of elements maintained by the queue + * @see ArrayDeque + * @see DequeTools + */ +public class FixedCapacityArrayDeque + extends AbstractArrayDeque +{ + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty deque with the specified capacity. + */ + public FixedCapacityArrayDeque(int capacity) { + super(capacity); + } + + + // ********** Deque implementation ********** + + /** + * @exception IllegalStateException if the deque is full + */ + @Override + public void enqueueTail(E element) { + if (this.isFull()) { + throw new IllegalStateException("Deque is full."); //$NON-NLS-1$ + } + super.enqueueTail(element); + } + + /** + * @exception IllegalStateException if the deque is full + */ + @Override + public void enqueueHead(E element) { + if (this.isFull()) { + throw new IllegalStateException("Deque is full."); //$NON-NLS-1$ + } + super.enqueueHead(element); + } + + /** + * Return whether the deque is full, + * as its capacity is fixed. + */ + public boolean isFull() { + return this.size == this.elements.length; + } + + + // ********** standard methods ********** + + @Override + public FixedCapacityArrayDeque clone() { + return (FixedCapacityArrayDeque) super.clone(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityPriorityDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityPriorityDeque.java new file mode 100644 index 0000000000..0934b18f28 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/FixedCapacityPriorityDeque.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.util.Comparator; +import org.eclipse.jpt.common.utility.deque.InputRestrictedDeque; + +/** + * Fixed capacity priority implementation of the {@link InputRestrictedDeque} interface. + * Elements will dequeue from the deque's head in the order determined by a comparator + * (i.e. {@link #dequeueHead} will return the element sorted first + * while {@link #dequeueTail} will return the element sorted last). + * @param the type of elements maintained by the deque + * @see PriorityDeque + * @see DequeTools + */ +public class FixedCapacityPriorityDeque + extends AbstractPriorityDeque +{ + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty, fixed-capacity priority deque with the specified comparator + * and capacity. + */ + public FixedCapacityPriorityDeque(Comparator comparator, int capacity) { + super(comparator, capacity); + } + + + // ********** Deque implementation ********** + + /** + * @exception IllegalStateException if the deque is full + */ + @Override + public void enqueue(E element) { + if (this.isFull()) { + throw new IllegalStateException("Deque is full."); //$NON-NLS-1$ + } + super.enqueue(element); + } + + /** + * Return whether the deque is full, + * as its capacity is fixed. + */ + public boolean isFull() { + return this.size == this.elements.length - 1; + } + + + // ********** standard methods ********** + + @Override + public FixedCapacityPriorityDeque clone() { + return (FixedCapacityPriorityDeque) super.clone(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/LinkedDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/LinkedDeque.java new file mode 100644 index 0000000000..937d38e079 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/LinkedDeque.java @@ -0,0 +1,321 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.ObjectTools; + +/** + * Linked implementation of the {@link Deque} interface. + * @param the type of elements maintained by the deque + * @see DequeTools + */ +public class LinkedDeque + implements Deque, Cloneable, Serializable +{ + private final NodeFactory nodeFactory; + private transient Node head; // next element to dequeue head + private transient Node tail; // next element to dequeue tail + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty deque with no node cache. + */ + public LinkedDeque() { + this(0); + } + + /** + * Construct an empty deque with a node cache with the specified size. + * Specify a cache size of -1 for an unlimited cache. + */ + public LinkedDeque(int cacheSize) { + this(LinkedDeque.buildNodeFactory(cacheSize)); + this.head = null; + } + + private static NodeFactory buildNodeFactory(int cacheSize) { + if (cacheSize < -1) { + throw new IllegalArgumentException("Cache size must be greater than or equal to -1: " + cacheSize); //$NON-NLS-1$ + } + return (cacheSize == 0) ? SimpleNodeFactory.instance() : new CachingNodeFactory(cacheSize); + } + + private LinkedDeque(NodeFactory nodeFactory) { + super(); + this.nodeFactory = nodeFactory; + this.head = null; + this.tail = null; + } + + + // ********** Deque implementation ********** + + public void enqueueTail(E element) { + Node newNode = this.nodeFactory.buildNode(element, null, this.tail); + if (this.tail == null) { + this.head = newNode; // first node + } else { + this.tail.next = newNode; + } + this.tail = newNode; + } + + public void enqueueHead(E element) { + Node newNode = this.nodeFactory.buildNode(element, this.head, null); + if (this.head == null) { + this.tail = newNode; // first node + } else { + this.head.prev = newNode; + } + this.head = newNode; + } + + public E dequeueHead() { + if (this.head == null) { + throw new NoSuchElementException(); + } + Node node = this.head; + this.head = node.next; + if (this.head == null) { + this.tail = null; // last node + } else { + this.head.prev = null; + } + E element = node.element; + this.nodeFactory.release(node); + return element; + } + + public E dequeueTail() { + if (this.tail == null) { + throw new NoSuchElementException(); + } + Node node = this.tail; + this.tail = node.prev; + if (this.tail == null) { + this.head = null; // last node + } else { + this.tail.next = null; + } + E element = node.element; + this.nodeFactory.release(node); + return element; + } + + public E peekHead() { + if (this.head == null) { + throw new NoSuchElementException(); + } + return this.head.element; + } + + public E peekTail() { + if (this.tail == null) { + throw new NoSuchElementException(); + } + return this.tail.element; + } + + public boolean isEmpty() { + return this.head == null; + } + + + // ********** standard methods ********** + + @Override + public LinkedDeque clone() { + LinkedDeque clone = new LinkedDeque(this.nodeFactory.copy()); + E[] elements = this.buildElements(); + for (E element : elements) { + clone.enqueueTail(element); + } + return clone; + } + + @SuppressWarnings("unchecked") + private E[] buildElements() { + int size = this.size(); + if (size == 0) { + return (E[]) ObjectTools.EMPTY_OBJECT_ARRAY; + } + E[] elements = (E[]) new Object[size]; + int i = 0; + for (Node node = this.head; node != null; node = node.next) { + elements[i++] = node.element; + } + return elements; + } + + private int size() { + int size = 0; + for (Node node = this.head; node != null; node = node.next) { + size++; + } + return size; + } + + @Override + public String toString() { + return Arrays.toString(this.buildElements()); + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write nodeFactory (and any hidden stuff) + stream.defaultWriteObject(); + Object[] elements = this.buildElements(); + stream.writeInt(elements.length); + for (Object element : elements) { + stream.writeObject(element); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read nodeFactory (and any hidden stuff) + stream.defaultReadObject(); + int len = stream.readInt(); + for (int i = len; i-- > 0; ) { + this.enqueueTail((E) stream.readObject()); + } + } + + + // ********** Node classes ********** + + private static final class Node { + E element; + Node next; + Node prev; + + Node(E element, Node next, Node prev) { + super(); + this.element = element; + this.next = next; + this.prev = prev; + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.element); + } + } + + private abstract static class NodeFactory { + NodeFactory() { + super(); + } + + Node buildNode(E element, Node next, Node prev) { + return new Node(element, next, prev); + } + + abstract void release(Node node); + + abstract NodeFactory copy(); + } + + private static class SimpleNodeFactory + extends NodeFactory + implements Serializable + { + @SuppressWarnings("rawtypes") + public static final NodeFactory INSTANCE = new SimpleNodeFactory(); + @SuppressWarnings("unchecked") + public static NodeFactory instance() { + return INSTANCE; + } + + private SimpleNodeFactory() { + super(); + } + + @Override + void release(Node node) { + // NOP + } + + @Override + NodeFactory copy() { + return this; + } + + @Override + public String toString() { + return ObjectTools.singletonToString(this); + } + + private static final long serialVersionUID = 1L; + private Object readResolve() { + // replace this object with the singleton + return INSTANCE; + } + } + + private static final class CachingNodeFactory + extends NodeFactory + implements Serializable + { + private final int maxCacheSize; + private transient int cacheSize = 0; + private transient Node cacheHead; + private static final long serialVersionUID = 1L; + + CachingNodeFactory(int maxCacheSize) { + super(); + this.maxCacheSize = maxCacheSize; + } + + @Override + Node buildNode(E element, Node next, Node prev) { + if (this.cacheHead == null) { + return super.buildNode(element, next, prev); + } + Node node = this.cacheHead; + this.cacheHead = node.next; + this.cacheSize--; + node.element = element; + node.next = next; + return node; + } + + @Override + void release(Node node) { + if ((this.maxCacheSize == -1) || (this.cacheSize < this.maxCacheSize)) { + node.element = null; // allow GC to work + node.next = this.cacheHead; + node.prev = null; + this.cacheHead = node; + this.cacheSize++; + } + } + + @Override + NodeFactory copy() { + return new CachingNodeFactory(this.maxCacheSize); + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.cacheSize); + } + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ListDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ListDeque.java new file mode 100644 index 0000000000..bd86cdf73b --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ListDeque.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.io.Serializable; +import java.util.List; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; + +/** + * Adapt a {@link List} to the {@link Deque} interface. + * Head elements are dequeueHeadd from the front of the list (i.e. index 0); + * while tail elements are dequeueHeadd from the end of the list. + * @param the type of elements maintained by the deque + * @see DequeTools + */ +public class ListDeque + implements Deque, Serializable +{ + private List list; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a deque, adapting the specified list. + * The deque's head will dequeueHead its elements in the same + * order they are returned by the list's iterator (i.e. the + * first element returned by the list's iterator will be the + * first element returned by {@link #dequeueHead()}). + */ + public ListDeque(List list) { + super(); + this.list = list; + } + + + // ********** Deque implementation ********** + + public void enqueueTail(E element) { + this.list.add(element); + } + + public void enqueueHead(E element) { + this.list.add(0, element); + } + + public E dequeueHead() { + if (this.list.size() == 0) { + throw new NoSuchElementException(); + } + return this.list.remove(0); + } + + public E dequeueTail() { + int size = this.list.size(); + if (size == 0) { + throw new NoSuchElementException(); + } + return this.list.remove(size - 1); + } + + public E peekHead() { + if (this.list.size() == 0) { + throw new NoSuchElementException(); + } + return this.list.get(0); + } + + public E peekTail() { + int size = this.list.size(); + if (size == 0) { + throw new NoSuchElementException(); + } + return this.list.get(size - 1); + } + + public boolean isEmpty() { + return this.list.isEmpty(); + } + + + // ********** standard methods ********** + + @Override + public String toString() { + return this.list.toString(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/PriorityDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/PriorityDeque.java new file mode 100644 index 0000000000..270b04af78 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/PriorityDeque.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.deque; + +import java.util.Comparator; +import org.eclipse.jpt.common.utility.deque.InputRestrictedDeque; + +/** + * Resizable priority implementation of the {@link InputRestrictedDeque} interface. + * Elements will dequeue from the deque's head in the order determined by a comparator + * (i.e. {@link #dequeueHead} will return the element sorted first + * while {@link #dequeueTail} will return the element sorted last). + * @param the type of elements maintained by the deque + * @see FixedCapacityPriorityDeque + * @see DequeTools + */ +public class PriorityDeque + extends AbstractPriorityDeque +{ + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty priority deque with the specified comparator + * and initial capacity. + */ + public PriorityDeque(Comparator comparator, int initialCapacity) { + super(comparator, initialCapacity); + } + + + // ********** Deque implementation ********** + + @Override + public void enqueue(E element) { + this.ensureCapacity(this.size + 1); + super.enqueue(element); + } + + /** + * Increase the deque's capacity, if necessary, to ensure it has at least + * the specified minimum capacity. + */ + public void ensureCapacity(int minCapacity) { + int oldCapacity = this.elements.length - 1; + if (oldCapacity < minCapacity) { + int newCapacity = ((oldCapacity * 3) >> 1) + 1; + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + this.elements = this.copyElements(newCapacity); + } + } + + /** + * Decrease the deque's capacity, if necessary, to match its current size. + */ + public void trimToSize() { + if (this.elements.length > this.size + 1) { + this.elements = this.copyElements(this.size); + } + } + + private E[] copyElements(int newCapacity) { + @SuppressWarnings("unchecked") + E[] newElements = (E[]) new Object[newCapacity + 1]; + System.arraycopy(this.elements, 1, newElements, 1, this.size); // skip 0 + return newElements; + } + + + // ********** standard methods ********** + + @Override + public PriorityDeque clone() { + return (PriorityDeque) super.clone(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ReverseDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ReverseDeque.java new file mode 100644 index 0000000000..e834b86bdd --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/ReverseDeque.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.io.Serializable; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.ObjectTools; + +/** + * This deque will reverse the order of the configured deque. + * @param the type of elements maintained by the deque + * @see DequeTools + */ +public class ReverseDeque + implements Deque, Serializable +{ + private Deque deque; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a deque that reverses the specified deque. + */ + public ReverseDeque(Deque deque) { + super(); + if (deque == null) { + throw new NullPointerException(); + } + this.deque = deque; + } + + + // ********** Deque implementation ********** + + public void enqueueTail(E element) { + this.deque.enqueueHead(element); + } + + public void enqueueHead(E element) { + this.deque.enqueueTail(element); + } + + public E dequeueHead() { + return this.deque.dequeueTail(); + } + + public E dequeueTail() { + return this.deque.dequeueHead(); + } + + public E peekHead() { + return this.deque.peekTail(); + } + + public E peekTail() { + return this.deque.peekHead(); + } + + public boolean isEmpty() { + return this.deque.isEmpty(); + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.deque); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/SynchronizedDeque.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/SynchronizedDeque.java new file mode 100644 index 0000000000..d89d60a07a --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/deque/SynchronizedDeque.java @@ -0,0 +1,984 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.deque; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.command.Command; +import org.eclipse.jpt.common.utility.internal.collection.MapTools; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; + +/** + * Thread-safe implementation of the {@link Deque} interface. + * This also provides protocol for suspending a thread until the + * deque is empty or not empty, with optional time-outs. + * @param the type of elements maintained by the deque + * @see DequeTools + */ +public class SynchronizedDeque + implements Deque, Serializable +{ + /** Backing deque. */ + private final Deque deque; + + /** Object to synchronize on. */ + private final Object mutex; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a synchronized deque that wraps the + * specified deque and locks on the specified mutex. + */ + public SynchronizedDeque(Deque deque, Object mutex) { + super(); + if ((deque == null) || (mutex == null)) { + throw new NullPointerException(); + } + this.deque = deque; + this.mutex = mutex; + } + + /** + * Construct a synchronized deque that wraps the + * specified deque and locks on itself. + */ + public SynchronizedDeque(Deque deque) { + super(); + if (deque == null) { + throw new NullPointerException(); + } + this.deque = deque; + this.mutex = this; + } + + + // ********** Deque implementation ********** + + public void enqueueTail(E element) { + synchronized (this.mutex) { + this.enqueueTail_(element); + } + } + + /** + * Pre-condition: synchronized + */ + private void enqueueTail_(E element) { + this.deque.enqueueTail(element); + this.mutex.notifyAll(); + } + + public void enqueueHead(E element) { + synchronized (this.mutex) { + this.enqueueHead_(element); + } + } + + /** + * Pre-condition: synchronized + */ + private void enqueueHead_(E element) { + this.deque.enqueueHead(element); + this.mutex.notifyAll(); + } + + public E dequeueHead() { + synchronized (this.mutex) { + return this.dequeueHead_(); + } + } + + /** + * Pre-condition: synchronized + */ + private E dequeueHead_() { + E element = this.deque.dequeueHead(); + this.mutex.notifyAll(); + return element; + } + + public E dequeueTail() { + synchronized (this.mutex) { + return this.dequeueTail_(); + } + } + + /** + * Pre-condition: synchronized + */ + private E dequeueTail_() { + E element = this.deque.dequeueTail(); + this.mutex.notifyAll(); + return element; + } + + public E peekHead() { + synchronized (this.mutex) { + return this.deque.peekHead(); + } + } + + public E peekTail() { + synchronized (this.mutex) { + return this.deque.peekTail(); + } + } + + public boolean isEmpty() { + synchronized (this.mutex) { + return this.deque.isEmpty(); + } + } + + + // ********** indefinite waits ********** + + /** + * Suspend the current thread until the deque's empty status changes + * to the specified value. + */ + public void waitUntilEmptyIs(boolean empty) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(empty); + } + } + + /** + * Pre-condition: synchronized + */ + private void waitUntilEmptyIs_(boolean empty) throws InterruptedException { + while (this.deque.isEmpty() != empty) { + this.mutex.wait(); + } + } + + /** + * Suspend the current thread until the deque is empty. + */ + public void waitUntilEmpty() throws InterruptedException { + this.waitUntilEmptyIs(true); + } + + /** + * Suspend the current thread until the deque has something on it. + */ + public void waitUntilNotEmpty() throws InterruptedException { + this.waitUntilEmptyIs(false); + } + + /** + * Suspend the current thread until the deque is empty, + * then "enqueue" the specified item to the tail of the deque + * and continue executing. + */ + public void waitToEnqueueTail(E element) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(true); + this.enqueueTail_(element); + } + } + + /** + * Suspend the current thread until the deque is empty, + * then "enqueue" the specified item to the head of the deque + * and continue executing. + */ + public void waitToEnqueueHead(E element) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(true); + this.enqueueHead_(element); + } + } + + /** + * Suspend the current thread until the deque has something on it, + * then "dequeue" an item from the head of the deque and return it. + */ + public Object waitToDequeueHead() throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(false); + return this.dequeueHead_(); + } + } + + /** + * Suspend the current thread until the deque has something on it, + * then "dequeue" an item from the tail of the deque and return it. + */ + public Object waitToDequeueTail() throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(false); + return this.dequeueTail_(); + } + } + + + // ********** timed waits ********** + + /** + * Suspend the current thread until the deque's empty status changes + * to the specified value or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if the specified + * empty status was achieved; return false if a time-out occurred. + * If the deque's empty status is already the specified value, + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilEmptyIs(boolean empty, long timeout) throws InterruptedException { + synchronized (this.mutex) { + return this.waitUntilEmptyIs_(empty, timeout); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean waitUntilEmptyIs_(boolean empty, long timeout) throws InterruptedException { + if (timeout == 0L) { + this.waitUntilEmptyIs_(empty); // wait indefinitely until notified + return true; // if it ever comes back, the condition was met + } + + long stop = System.currentTimeMillis() + timeout; + long remaining = timeout; + while ((this.deque.isEmpty() != empty) && (remaining > 0L)) { + this.mutex.wait(remaining); + remaining = stop - System.currentTimeMillis(); + } + return (this.deque.isEmpty() == empty); + } + + /** + * Suspend the current thread until the deque is empty + * or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if + * the deque is empty; return false if a time-out occurred. + * If the deque is already empty, return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilEmpty(long timeout) throws InterruptedException { + return this.waitUntilEmptyIs(true, timeout); + } + + /** + * Suspend the current thread until the deque has something on it. + * or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if + * the deque is not empty; return false if a time-out occurred. + * If the deque already has something on it, return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilNotEmpty(long timeout) throws InterruptedException { + return this.waitUntilEmptyIs(false, timeout); + } + + /** + * Suspend the current thread until the deque is empty, + * then "enqueue" the specified item to the tail of the deque + * and continue executing. If the deque is not emptied out + * before the time-out, simply continue executing without + * "enqueueing" the item. + * The time-out is specified in milliseconds. Return true if the + * item was enqueued; return false if a time-out occurred. + * If the deque is already empty, "enqueue" the specified item and + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitToEnqueueTail(E element, long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(true, timeout); + if (success) { + this.enqueueTail_(element); + } + return success; + } + } + + /** + * Suspend the current thread until the deque is empty, + * then "enqueue" the specified item to the head of the deque + * and continue executing. If the deque is not emptied out + * before the time-out, simply continue executing without + * "enqueueing" the item. + * The time-out is specified in milliseconds. Return true if the + * item was enqueued; return false if a time-out occurred. + * If the deque is already empty, "enqueue" the specified item and + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitToEnqueueHead(E element, long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(true, timeout); + if (success) { + this.enqueueHead_(element); + } + return success; + } + } + + /** + * Suspend the current thread until the deque has something on it, + * then "dequeue" an item from the head of the deque and return it. + * If the deque is empty and nothing is "enqueued" on to it before the + * time-out, throw a no such element exception. + * The time-out is specified in milliseconds. + * If the deque is not empty, "dequeue" an item and + * return it immediately. + * If the time-out is zero, wait indefinitely. + */ + public Object waitToDequeueHead(long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(false, timeout); + if (success) { + return this.dequeueHead_(); + } + throw new NoSuchElementException(); + } + } + + /** + * Suspend the current thread until the deque has something on it, + * then "dequeue" an item from the tail of the deque and return it. + * If the deque is empty and nothing is "enqueued" on to it before the + * time-out, throw a no such element exception. + * The time-out is specified in milliseconds. + * If the deque is not empty, "dequeue" an item and + * return it immediately. + * If the time-out is zero, wait indefinitely. + */ + public Object waitToDequeueTail(long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(false, timeout); + if (success) { + return this.dequeueTail_(); + } + throw new NoSuchElementException(); + } + } + + + // ********** synchronized behavior ********** + + /** + * If the current thread is not interrupted, execute the specified command + * with the mutex locked. This is useful for initializing the deque in another + * thread. + */ + public void execute(Command command) throws InterruptedException { + if (Thread.currentThread().isInterrupted()) { + throw new InterruptedException(); + } + synchronized (this.mutex) { + command.execute(); + } + } + + + // ********** additional public protocol ********** + + /** + * "Enqueue" all the elements returned by the specified iterable to the deque's tail. + * Return whether the deque changed as a result. + */ + public boolean enqueueTailAll(Iterable iterable) { + return this.enqueueTailAll(iterable.iterator()); + } + + /** + * "Enqueue" all the elements returned by the specified iterable to the deque's head. + * Return whether the deque changed as a result. + */ + public boolean enqueueHeadAll(Iterable iterable) { + return this.enqueueHeadAll(iterable.iterator()); + } + + /** + * "Enqueue" all the elements returned by the specified iterator to the deque's tail. + * Return whether the deque changed as a result. + */ + public boolean enqueueTailAll(Iterator iterator) { + if ( ! iterator.hasNext()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueTailAll_(iterator); + } + } + + /** + * Pre-condition: synchronized + * Assume the iterator is not empty. + */ + private boolean enqueueTailAll_(Iterator iterator) { + do { + this.deque.enqueueTail(iterator.next()); + } while (iterator.hasNext()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Enqueue" all the elements returned by the specified iterator to the deque's head. + * Return whether the deque changed as a result. + */ + public boolean enqueueHeadAll(Iterator iterator) { + if ( ! iterator.hasNext()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueHeadAll_(iterator); + } + } + + /** + * Pre-condition: synchronized + * Assume the iterator is not empty. + */ + private boolean enqueueHeadAll_(Iterator iterator) { + do { + this.deque.enqueueHead(iterator.next()); + } while (iterator.hasNext()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Enqueue" all the elements in the specified array to the deque's tail. + * Return whether the deque changed as a result. + */ + public boolean enqueueTailAll(E... array) { + int len = array.length; + if (len == 0) { + return false; + } + synchronized (this.mutex) { + return this.enqueueTailAll_(array, len); + } + } + + /** + * Pre-condition: synchronized + * Assume the array is not empty. + */ + private boolean enqueueTailAll_(E[] array, int arrayLength) { + int i = 0; + do { + this.deque.enqueueTail(array[i++]); + } while (i < arrayLength); + this.mutex.notifyAll(); + return true; + } + + /** + * "Enqueue" all the elements in the specified array to the deque's head. + * Return whether the deque changed as a result. + */ + public boolean enqueueHeadAll(E... array) { + int len = array.length; + if (len == 0) { + return false; + } + synchronized (this.mutex) { + return this.enqueueHeadAll_(array, len); + } + } + + /** + * Pre-condition: synchronized + * Assume the array is not empty. + */ + private boolean enqueueHeadAll_(E[] array, int arrayLength) { + int i = 0; + do { + this.deque.enqueueHead(array[i++]); + } while (i < arrayLength); + this.mutex.notifyAll(); + return true; + } + + /** + * Pop all the elements from the specified stack and "enqueue" them to the deque's tail. + * Return whether the deque changed as a result. + */ + public boolean enqueueTailAll(Stack stack) { + if (stack.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueTailAll_(stack); + } + } + + /** + * Pre-condition: synchronized + * Assume the stack is not empty. + */ + private boolean enqueueTailAll_(Stack stack) { + do { + this.deque.enqueueTail(stack.pop()); + } while ( ! stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * Pop all the elements from the specified stack and "enqueue" them to the deque's head. + * Return whether the deque changed as a result. + */ + public boolean enqueueHeadAll(Stack stack) { + if (stack.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueHeadAll_(stack); + } + } + + /** + * Pre-condition: synchronized + * Assume the stack is not empty. + */ + private boolean enqueueHeadAll_(Stack stack) { + do { + this.deque.enqueueHead(stack.pop()); + } while ( ! stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Dequeue" all the elements from the specified deque's head and + * "enqueue" them to the deque's tail. + * Return whether the deque changed as a result. + * @see #drainHeadTo(Deque) + */ + public boolean enqueueTailAll(Deque q) { + if (q.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueTailAll_(q); + } + } + + /** + * Pre-condition: synchronized + * Assume the deque is not empty. + */ + private boolean enqueueTailAll_(Deque q) { + do { + this.deque.enqueueTail(q.dequeueHead()); + } while ( ! q.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Dequeue" all the elements from the specified deque's tail and + * "enqueue" them to the deque's head. + * Return whether the deque changed as a result. + * @see #drainTailTo(Deque) + */ + public boolean enqueueHeadAll(Deque q) { + if (q.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueHeadAll_(q); + } + } + + /** + * Pre-condition: synchronized + * Assume the deque is not empty. + */ + private boolean enqueueHeadAll_(Deque q) { + do { + this.deque.enqueueHead(q.dequeueTail()); + } while ( ! q.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's head and return them in a list. + */ + public ArrayList drainHead() { + ArrayList result = new ArrayList(); + this.drainHeadTo(result); + return result; + } + + /** + * "Drain" all the current items from the deque's tail and return them in a list. + */ + public ArrayList drainTail() { + ArrayList result = new ArrayList(); + this.drainTailTo(result); + return result; + } + + /** + * "Drain" all the current items from the deque's head into specified collection. + * Return whether the deque changed as a result. + */ + public boolean drainHeadTo(Collection collection) { + synchronized (this.mutex) { + return this.drainHeadTo_(collection); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainHeadTo_(Collection collection) { + if (this.deque.isEmpty()) { + return false; + } + return this.drainHeadTo__(collection); + } + + /** + * Pre-condition: synchronized + * Assume the deque is not empty. + */ + private boolean drainHeadTo__(Collection collection) { + do { + collection.add(this.deque.dequeueHead()); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's tail into specified collection. + * Return whether the deque changed as a result. + */ + public boolean drainTailTo(Collection collection) { + synchronized (this.mutex) { + return this.drainTailTo_(collection); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTailTo_(Collection collection) { + if (this.deque.isEmpty()) { + return false; + } + return this.drainTailTo__(collection); + } + + /** + * Pre-condition: synchronized + * Assume the deque is not empty. + */ + private boolean drainTailTo__(Collection collection) { + do { + collection.add(this.deque.dequeueTail()); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's head into specified list + * at the specified index. + * Return whether the deque changed as a result. + */ + public boolean drainHeadTo(List list, int index) { + synchronized (this.mutex) { + return this.drainHeadTo_(list, index); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainHeadTo_(List list, int index) { + if (this.deque.isEmpty()) { + return false; + } + if (index == list.size()) { + return this.drainHeadTo__(list); + } + ArrayList temp = new ArrayList(); + this.drainHeadTo__(temp); + list.addAll(index, temp); + return true; + } + + /** + * "Drain" all the current items from the deque's tail into specified list + * at the specified index. + * Return whether the deque changed as a result. + */ + public boolean drainTailTo(List list, int index) { + synchronized (this.mutex) { + return this.drainTailTo_(list, index); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTailTo_(List list, int index) { + if (this.deque.isEmpty()) { + return false; + } + if (index == list.size()) { + return this.drainTailTo__(list); + } + ArrayList temp = new ArrayList(); + this.drainTailTo__(temp); + list.addAll(index, temp); + return true; + } + + /** + * "Drain" all the current items from the deque's head into specified stack. + * Return whether the deque changed as a result. + */ + public boolean drainHeadTo(Stack stack) { + synchronized (this.mutex) { + return this.drainHeadTo_(stack); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainHeadTo_(Stack stack) { + if (this.deque.isEmpty()) { + return false; + } + do { + stack.push(this.deque.dequeueHead()); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's tail into specified stack. + * Return whether the deque changed as a result. + */ + public boolean drainTailTo(Stack stack) { + synchronized (this.mutex) { + return this.drainTailTo_(stack); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTailTo_(Stack stack) { + if (this.deque.isEmpty()) { + return false; + } + do { + stack.push(this.deque.dequeueTail()); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's head into specified deque's tail. + * Return whether the deque changed as a result. + * @see #enqueueTailAll(Deque) + */ + public boolean drainHeadTo(Deque q) { + synchronized (this.mutex) { + return this.drainHeadTo_(q); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainHeadTo_(Deque q) { + if (this.deque.isEmpty()) { + return false; + } + do { + q.enqueueTail(this.deque.dequeueHead()); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's tail into specified deque's head. + * Return whether the deque changed as a result. + * @see #enqueueTailAll(Deque) + */ + public boolean drainTailTo(Deque q) { + synchronized (this.mutex) { + return this.drainTailTo_(q); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTailTo_(Deque q) { + if (this.deque.isEmpty()) { + return false; + } + do { + q.enqueueHead(this.deque.dequeueTail()); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's head + * and add them on the specified map, using the specified key transformer + * to generate the key for each item. + * Return whether the deque changed as a result. + */ + public boolean drainHeadTo(Map map, Transformer keyTransformer) { + synchronized (this.mutex) { + return this.drainHeadTo_(map, keyTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainHeadTo_(Map map, Transformer keyTransformer) { + if (this.deque.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.deque.dequeueHead(), keyTransformer); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's tail + * and add them on the specified map, using the specified key transformer + * to generate the key for each item. + * Return whether the deque changed as a result. + */ + public boolean drainTailTo(Map map, Transformer keyTransformer) { + synchronized (this.mutex) { + return this.drainTailTo_(map, keyTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTailTo_(Map map, Transformer keyTransformer) { + if (this.deque.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.deque.dequeueTail(), keyTransformer); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's head + * and add them on the specified map, using the specified key transformer + * to generate the key for each dequeued item and the specified value transformer + * to generator the value for each dequeued item. + * Return whether the deque changed as a result. + */ + public boolean drainHeadTo(Map map, Transformer keyTransformer, Transformer valueTransformer) { + synchronized (this.mutex) { + return this.drainHeadTo_(map, keyTransformer, valueTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainHeadTo_(Map map, Transformer keyTransformer, Transformer valueTransformer) { + if (this.deque.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.deque.dequeueHead(), keyTransformer, valueTransformer); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the deque's tail + * and add them on the specified map, using the specified key transformer + * to generate the key for each dequeued item and the specified value transformer + * to generator the value for each dequeued item. + * Return whether the deque changed as a result. + */ + public boolean drainTailTo(Map map, Transformer keyTransformer, Transformer valueTransformer) { + synchronized (this.mutex) { + return this.drainTailTo_(map, keyTransformer, valueTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTailTo_(Map map, Transformer keyTransformer, Transformer valueTransformer) { + if (this.deque.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.deque.dequeueTail(), keyTransformer, valueTransformer); + } while ( ! this.deque.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * Return the object the deque locks on while performing + * its operations. + */ + public Object getMutex() { + return this.mutex; + } + + + // ********** standard methods ********** + + @Override + public String toString() { + synchronized (this.mutex) { + return this.deque.toString(); + } + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + synchronized (this.mutex) { + s.defaultWriteObject(); + } + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/enumeration/EnumerationTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/enumeration/EnumerationTools.java index 9ce3de3ae4..6b2ca1ca5d 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/enumeration/EnumerationTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/enumeration/EnumerationTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -53,7 +53,7 @@ public final class EnumerationTools { * elements in the specified collection. */ public static boolean containsAll(Enumeration enumeration, Collection collection) { - return CollectionTools.set(iterator(enumeration)).containsAll(collection); + return CollectionTools.hashSet(iterator(enumeration)).containsAll(collection); } /** @@ -62,7 +62,7 @@ public final class EnumerationTools { * The specified enumeration size is a performance hint. */ public static boolean containsAll(Enumeration enumeration, int enumerationSize, Collection collection) { - return CollectionTools.set(iterator(enumeration), enumerationSize).containsAll(collection); + return CollectionTools.hashSet(iterator(enumeration), enumerationSize).containsAll(collection); } /** @@ -70,7 +70,7 @@ public final class EnumerationTools { * elements in the specified iterable. */ public static boolean containsAll(Enumeration enumeration, Iterable iterable) { - return CollectionTools.containsAll(CollectionTools.set(iterator(enumeration)), iterable); + return CollectionTools.containsAll(CollectionTools.hashSet(iterator(enumeration)), iterable); } /** @@ -79,7 +79,7 @@ public final class EnumerationTools { * The specified enumeration size is a performance hint. */ public static boolean containsAll(Enumeration enumeration, int enumerationSize, Iterable iterable) { - return CollectionTools.containsAll(CollectionTools.set(iterator(enumeration), enumerationSize), iterable); + return CollectionTools.containsAll(CollectionTools.hashSet(iterator(enumeration), enumerationSize), iterable); } /** @@ -87,7 +87,7 @@ public final class EnumerationTools { * elements in the specified enumeration 2. */ public static boolean containsAll(Enumeration enumeration1, Enumeration enumeration2) { - return CollectionTools.containsAll(CollectionTools.set(iterator(enumeration1)), iterator(enumeration2)); + return CollectionTools.containsAll(CollectionTools.hashSet(iterator(enumeration1)), iterator(enumeration2)); } /** @@ -96,7 +96,7 @@ public final class EnumerationTools { * The specified iterator 1 size is a performance hint. */ public static boolean containsAll(Enumeration enumeration1, int enumeration1Size, Enumeration enumeration2) { - return CollectionTools.containsAll(CollectionTools.set(iterator(enumeration1), enumeration1Size), iterator(enumeration2)); + return CollectionTools.containsAll(CollectionTools.hashSet(iterator(enumeration1), enumeration1Size), iterator(enumeration2)); } /** @@ -104,7 +104,7 @@ public final class EnumerationTools { * elements in the specified array. */ public static boolean containsAll(Enumeration enumeration, Object... array) { - return CollectionTools.containsAll(CollectionTools.set(iterator(enumeration)), array); + return CollectionTools.containsAll(CollectionTools.hashSet(iterator(enumeration)), array); } /** @@ -113,7 +113,7 @@ public final class EnumerationTools { * The specified enumeration size is a performance hint. */ public static boolean containsAll(Enumeration enumeration, int enumerationSize, Object... array) { - return CollectionTools.containsAll(CollectionTools.set(iterator(enumeration), enumerationSize), array); + return CollectionTools.containsAll(CollectionTools.hashSet(iterator(enumeration), enumerationSize), array); } /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ChainIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ChainIterable.java index 83bbe90373..babbca5401 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ChainIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ChainIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -56,6 +56,6 @@ public class ChainIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeIterable.java index 8170130fe8..cf84a8c404 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -66,6 +66,6 @@ public class CompositeIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeListIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeListIterable.java index cf85171468..45c7c5c265 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeListIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/CompositeListIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -68,6 +68,6 @@ public class CompositeListIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/FilteringIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/FilteringIterable.java index 2fceff8515..0d6274a9bf 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/FilteringIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/FilteringIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -50,6 +50,6 @@ public class FilteringIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/GraphIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/GraphIterable.java index aa994633b8..372860398e 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/GraphIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/GraphIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -72,6 +72,6 @@ public class GraphIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/IterableTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/IterableTools.java index 0b84ffbed0..8b45db23fc 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/IterableTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/IterableTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -18,8 +18,6 @@ import java.util.List; import java.util.ListIterator; import org.eclipse.jpt.common.utility.closure.Closure; import org.eclipse.jpt.common.utility.closure.InterruptibleClosure; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.exception.ExceptionHandler; import org.eclipse.jpt.common.utility.internal.closure.DisabledClosure; import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; @@ -30,6 +28,8 @@ import org.eclipse.jpt.common.utility.internal.iterator.IteratorTools; import org.eclipse.jpt.common.utility.internal.predicate.PredicateTools; import org.eclipse.jpt.common.utility.iterable.ListIterable; import org.eclipse.jpt.common.utility.predicate.Predicate; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; import org.eclipse.jpt.common.utility.transformer.Transformer; /** @@ -56,18 +56,18 @@ public final class IterableTools { } /** - * Return a collection corresponding to the specified iterable. + * Return a hash bag corresponding to the specified iterable. */ - public static HashBag collection(Iterable iterable) { - return IteratorTools.collection(iterable.iterator()); + public static HashBag hashBag(Iterable iterable) { + return IteratorTools.hashBag(iterable.iterator()); } /** - * Return a collection corresponding to the specified iterable. + * Return a hash bag corresponding to the specified iterable. * The specified iterable size is a performance hint. */ - public static HashBag collection(Iterable iterable, int iterableSize) { - return IteratorTools.collection(iterable.iterator(), iterableSize); + public static HashBag hashBag(Iterable iterable, int iterableSize) { + return IteratorTools.hashBag(iterable.iterator(), iterableSize); } /** @@ -388,7 +388,7 @@ public final class IterableTools { public static Iterable sort(Iterable iterable, Comparator comparator) { Iterator iterator = iterable.iterator(); if (iterator.hasNext()) { - return ListTools.sort(ListTools.list(iterator), comparator); + return ListTools.sort(ListTools.arrayList(iterator), comparator); } return emptyIterable(); } @@ -400,7 +400,7 @@ public final class IterableTools { public static Iterable sort(Iterable iterable, Comparator comparator, int iterableSize) { Iterator iterator = iterable.iterator(); if (iterator.hasNext()) { - return ListTools.sort(ListTools.list(iterator, iterableSize), comparator); + return ListTools.sort(ListTools.arrayList(iterator, iterableSize), comparator); } return emptyIterable(); } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/QueueIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/QueueIterable.java index 7831132475..42e2c1fc1b 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/QueueIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/QueueIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -10,8 +10,8 @@ package org.eclipse.jpt.common.utility.internal.iterable; import java.util.Iterator; -import org.eclipse.jpt.common.utility.collection.Queue; import org.eclipse.jpt.common.utility.internal.iterator.QueueIterator; +import org.eclipse.jpt.common.utility.queue.Queue; /** * A QueueIterable provides an {@link Iterable} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ReadOnlyCompositeListIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ReadOnlyCompositeListIterable.java index eddb200200..9459e1f873 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ReadOnlyCompositeListIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/ReadOnlyCompositeListIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -68,6 +68,6 @@ public class ReadOnlyCompositeListIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/StackIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/StackIterable.java index 32e7d61765..8281166013 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/StackIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/StackIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -10,8 +10,8 @@ package org.eclipse.jpt.common.utility.internal.iterable; import java.util.Iterator; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.internal.iterator.StackIterator; +import org.eclipse.jpt.common.utility.stack.Stack; /** * A StackIterable provides an {@link Iterable} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationIterable.java index ce2962332e..91ac5d96d2 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -52,6 +52,6 @@ public class TransformationIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationListIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationListIterable.java index a704681a49..e1b3a73f0e 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationListIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TransformationListIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -53,6 +53,6 @@ public class TransformationListIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TreeIterable.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TreeIterable.java index a9c62a7dd2..d4d6e75c0e 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TreeIterable.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterable/TreeIterable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -58,6 +58,6 @@ public class TreeIterable @Override public String toString() { - return ListTools.list(this).toString(); + return ListTools.arrayList(this).toString(); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/CloneListIterator.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/CloneListIterator.java index ce02223b35..80c63372dd 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/CloneListIterator.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/CloneListIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -68,7 +68,7 @@ public class CloneListIterator } // build a copy of the list and keep it in sync with original (if the mutator allows changes) // that way the nested list iterator will maintain some of our state - this.listIterator = ListTools.list(array).listIterator(); + this.listIterator = ListTools.arrayList(array).listIterator(); this.adapter = adapter; this.cursor = 0; this.state = State.UNKNOWN; diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/IteratorTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/IteratorTools.java index 2dc251b80d..1bdd506833 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/IteratorTools.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/IteratorTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -18,8 +18,6 @@ import java.util.List; import java.util.ListIterator; import org.eclipse.jpt.common.utility.closure.Closure; import org.eclipse.jpt.common.utility.closure.InterruptibleClosure; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.exception.ExceptionHandler; import org.eclipse.jpt.common.utility.internal.ArrayTools; import org.eclipse.jpt.common.utility.internal.ObjectTools; @@ -32,6 +30,8 @@ import org.eclipse.jpt.common.utility.internal.iterable.IterableTools; import org.eclipse.jpt.common.utility.internal.iterator.CloneListIterator.Adapter; import org.eclipse.jpt.common.utility.internal.predicate.PredicateTools; import org.eclipse.jpt.common.utility.predicate.Predicate; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; import org.eclipse.jpt.common.utility.transformer.Transformer; /** @@ -46,7 +46,7 @@ public final class IteratorTools { * Return a bag corresponding to the specified iterator. */ public static HashBag bag(Iterator iterator) { - return CollectionTools.bag(iterator); + return CollectionTools.hashBag(iterator); } /** @@ -54,22 +54,22 @@ public final class IteratorTools { * The specified iterator size is a performance hint. */ public static HashBag bag(Iterator iterator, int iteratorSize) { - return CollectionTools.bag(iterator, iteratorSize); + return CollectionTools.hashBag(iterator, iteratorSize); } /** - * Return a collection corresponding to the specified iterator. + * Return a hash bag corresponding to the specified iterator. */ - public static HashBag collection(Iterator iterator) { - return CollectionTools.collection(iterator); + public static HashBag hashBag(Iterator iterator) { + return CollectionTools.hashBag(iterator); } /** - * Return a collection corresponding to the specified iterator. + * Return a hash bag corresponding to the specified iterator. * The specified iterator size is a performance hint. */ - public static HashBag collection(Iterator iterator, int iteratorSize) { - return CollectionTools.collection(iterator, iteratorSize); + public static HashBag hashBag(Iterator iterator, int iteratorSize) { + return CollectionTools.hashBag(iterator, iteratorSize); } /** @@ -155,7 +155,7 @@ public final class IteratorTools { * elements in the specified collection. */ public static boolean containsAll(Iterator iterator, Collection collection) { - return collection.isEmpty() || CollectionTools.set(iterator).containsAll(collection); + return collection.isEmpty() || CollectionTools.hashSet(iterator).containsAll(collection); } /** @@ -164,7 +164,7 @@ public final class IteratorTools { * The specified iterator size is a performance hint. */ public static boolean containsAll(Iterator iterator, int iteratorSize, Collection collection) { - return collection.isEmpty() || CollectionTools.set(iterator, iteratorSize).containsAll(collection); + return collection.isEmpty() || CollectionTools.hashSet(iterator, iteratorSize).containsAll(collection); } /** @@ -189,7 +189,7 @@ public final class IteratorTools { * elements in the specified iterator 2. */ public static boolean containsAll(Iterator iterator1, Iterator iterator2) { - return isEmpty(iterator2) || CollectionTools.containsAll(CollectionTools.set(iterator1), iterator2); + return isEmpty(iterator2) || CollectionTools.containsAll(CollectionTools.hashSet(iterator1), iterator2); } /** @@ -198,7 +198,7 @@ public final class IteratorTools { * The specified iterator 1 size is a performance hint. */ public static boolean containsAll(Iterator iterator1, int iterator1Size, Iterator iterator2) { - return isEmpty(iterator2) || CollectionTools.containsAll(CollectionTools.set(iterator1, iterator1Size), iterator2); + return isEmpty(iterator2) || CollectionTools.containsAll(CollectionTools.hashSet(iterator1, iterator1Size), iterator2); } /** @@ -206,7 +206,7 @@ public final class IteratorTools { * elements in the specified array. */ public static boolean containsAll(Iterator iterator, Object... array) { - return (array.length == 0) || CollectionTools.containsAll(CollectionTools.set(iterator), array); + return (array.length == 0) || CollectionTools.containsAll(CollectionTools.hashSet(iterator), array); } /** @@ -215,7 +215,7 @@ public final class IteratorTools { * The specified iterator size is a performance hint. */ public static boolean containsAll(Iterator iterator, int iteratorSize, Object... array) { - return (array.length == 0) || CollectionTools.containsAll(CollectionTools.set(iterator, iteratorSize), array); + return (array.length == 0) || CollectionTools.containsAll(CollectionTools.hashSet(iterator, iteratorSize), array); } /** @@ -472,7 +472,7 @@ public final class IteratorTools { * Return a list corresponding to the specified iterator. */ public static ArrayList list(Iterator iterator) { - return ListTools.list(iterator); + return ListTools.arrayList(iterator); } /** @@ -480,7 +480,7 @@ public final class IteratorTools { * The specified iterator size is a performance hint. */ public static ArrayList list(Iterator iterator, int iteratorSize) { - return ListTools.list(iterator, iteratorSize); + return ListTools.arrayList(iterator, iteratorSize); } /** @@ -533,7 +533,7 @@ public final class IteratorTools { if (isEmpty(iterator)) { return emptyListIterator(); } - return ListTools.sort(ListTools.list(iterator), comparator).listIterator(); + return ListTools.sort(ListTools.arrayList(iterator), comparator).listIterator(); } /** @@ -544,7 +544,7 @@ public final class IteratorTools { if (isEmpty(iterator)) { return emptyListIterator(); } - return ListTools.sort(ListTools.list(iterator, iteratorSize), comparator).listIterator(); + return ListTools.sort(ListTools.arrayList(iterator, iteratorSize), comparator).listIterator(); } /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/QueueIterator.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/QueueIterator.java index 2f6a5ad834..12c59349fa 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/QueueIterator.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/QueueIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -10,9 +10,8 @@ package org.eclipse.jpt.common.utility.internal.iterator; import java.util.Iterator; - -import org.eclipse.jpt.common.utility.collection.Queue; import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.queue.Queue; /** * A QueueIterator provides an {@link Iterator} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/ReverseIterator.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/ReverseIterator.java index 256b69525f..4ee3b96243 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/ReverseIterator.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/ReverseIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2013 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -35,14 +35,14 @@ public class ReverseIterator * Construct a reverse iterator for the specified iterator. */ public ReverseIterator(Iterator iterator) { - this(ListTools.reverse(ListTools.list(iterator))); + this(ListTools.reverse(ListTools.arrayList(iterator))); } /** * Construct a reverse iterator for the specified iterator. */ public ReverseIterator(Iterator iterator, int size) { - this(ListTools.reverse(ListTools.list(iterator, size))); + this(ListTools.reverse(ListTools.arrayList(iterator, size))); } private ReverseIterator(ArrayList reverseList) { diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/StackIterator.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/StackIterator.java index e1108cf1bd..cc9dad4343 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/StackIterator.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/iterator/StackIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -10,9 +10,8 @@ package org.eclipse.jpt.common.utility.internal.iterator; import java.util.Iterator; - -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.stack.Stack; /** * A StackIterator provides an {@link Iterator} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/ChangeSupport.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/ChangeSupport.java index 269b4e9a2e..7b796ef4f2 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/ChangeSupport.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/ChangeSupport.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -1233,7 +1233,7 @@ public class ChangeSupport { * no empty checks */ protected boolean removeItemsFromCollection_(Iterator items, Collection collection, String collectionName) { - HashBag removedItems = CollectionTools.collection(items); + HashBag removedItems = CollectionTools.hashBag(items); removedItems.retainAll(collection); boolean changed = collection.removeAll(removedItems); @@ -1305,8 +1305,8 @@ public class ChangeSupport { * no empty checks */ protected boolean retainItemsInCollection_(Iterator items, Collection collection, String collectionName) { - HashBag retainedItems = CollectionTools.collection(items); - HashBag removedItems = CollectionTools.collection(collection); + HashBag retainedItems = CollectionTools.hashBag(items); + HashBag removedItems = CollectionTools.hashBag(collection); removedItems.removeAll(retainedItems); boolean changed = collection.retainAll(retainedItems); @@ -1378,7 +1378,7 @@ public class ChangeSupport { return this.addItemsToCollection_(newCollection, collection, collectionName); } - return this.synchronizeCollection_(CollectionTools.collection(newCollection), collection, collectionName); + return this.synchronizeCollection_(CollectionTools.hashBag(newCollection), collection, collectionName); } /** @@ -2191,7 +2191,7 @@ public class ChangeSupport { return false; } - ArrayList addedItems = ListTools.list(items); + ArrayList addedItems = ListTools.arrayList(items); if (list.addAll(index, addedItems)) { this.fireItemsAdded(listName, index, addedItems); return true; @@ -2264,7 +2264,7 @@ public class ChangeSupport { * no empty check */ protected boolean addItemsToList_(Iterator items, List list, String listName) { - ArrayList addedItems = ListTools.list(items); + ArrayList addedItems = ListTools.arrayList(items); int index = list.size(); if (list.addAll(addedItems)) { this.fireItemsAdded(listName, index, addedItems); @@ -2467,8 +2467,8 @@ public class ChangeSupport { * no empty checks */ protected boolean retainItemsInList_(Iterator items, List list, String listName) { - HashBag retainedItems = CollectionTools.collection(items); - HashBag removedItems = CollectionTools.collection(list); + HashBag retainedItems = CollectionTools.hashBag(items); + HashBag removedItems = CollectionTools.hashBag(list); removedItems.removeAll(retainedItems); return this.removeItemsFromList(removedItems, list, listName); } @@ -2642,7 +2642,7 @@ public class ChangeSupport { if (list.isEmpty()) { return this.addItemsToList_(newList, list, listName); } - return this.synchronizeList_(ListTools.list(newList), list, listName); + return this.synchronizeList_(ListTools.arrayList(newList), list, listName); } /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTPropertyChangeListenerWrapper.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTPropertyChangeListenerWrapper.java index 0f5ecad022..db3dd3da42 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTPropertyChangeListenerWrapper.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTPropertyChangeListenerWrapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -11,7 +11,8 @@ package org.eclipse.jpt.common.utility.internal.model.listener.awt; import java.awt.EventQueue; import org.eclipse.jpt.common.utility.internal.RunnableAdapter; -import org.eclipse.jpt.common.utility.internal.collection.SynchronizedQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.queue.SynchronizedQueue; import org.eclipse.jpt.common.utility.model.event.PropertyChangeEvent; import org.eclipse.jpt.common.utility.model.listener.PropertyChangeListener; @@ -32,7 +33,7 @@ public final class AWTPropertyChangeListenerWrapper implements PropertyChangeListener { private final PropertyChangeListener listener; - private final SynchronizedQueue events = new SynchronizedQueue(); + private final SynchronizedQueue events = QueueTools.synchronizedQueue(); public AWTPropertyChangeListenerWrapper(PropertyChangeListener listener) { diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTStateChangeListenerWrapper.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTStateChangeListenerWrapper.java index 600014f51d..3d78f7bbcd 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTStateChangeListenerWrapper.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/listener/awt/AWTStateChangeListenerWrapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -11,7 +11,8 @@ package org.eclipse.jpt.common.utility.internal.model.listener.awt; import java.awt.EventQueue; import org.eclipse.jpt.common.utility.internal.RunnableAdapter; -import org.eclipse.jpt.common.utility.internal.collection.SynchronizedQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.queue.SynchronizedQueue; import org.eclipse.jpt.common.utility.model.event.StateChangeEvent; import org.eclipse.jpt.common.utility.model.listener.StateChangeListener; @@ -30,7 +31,7 @@ public final class AWTStateChangeListenerWrapper implements StateChangeListener { private final StateChangeListener listener; - private final SynchronizedQueue events = new SynchronizedQueue(); + private final SynchronizedQueue events = QueueTools.synchronizedQueue(); public AWTStateChangeListenerWrapper(StateChangeListener listener) { diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AbstractTreeNodeValueModel.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AbstractTreeNodeValueModel.java index 6300294bfc..b4315334c0 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AbstractTreeNodeValueModel.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AbstractTreeNodeValueModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -114,7 +114,7 @@ public abstract class AbstractTreeNodeValueModel @SuppressWarnings("unchecked") public TreeNodeValueModel[] path() { - List> path = ListTools.reverse(ListTools.list(this.backPath())); + List> path = ListTools.reverse(ListTools.arrayList(this.backPath())); return path.toArray(new TreeNodeValueModel[path.size()]); } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectCollectionValueModelAdapter.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectCollectionValueModelAdapter.java index 4736f8fe2e..74bb555e15 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectCollectionValueModelAdapter.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectCollectionValueModelAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -147,7 +147,7 @@ public abstract class AspectCollectionValueModelAdapter } protected Collection buildValueCollection() { - return CollectionTools.collection(this.iterator()); + return CollectionTools.hashBag(this.iterator()); } @Override diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectListValueModelAdapter.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectListValueModelAdapter.java index 6b7ea124a4..227ba6bddd 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectListValueModelAdapter.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/AspectListValueModelAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2012 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -189,7 +189,7 @@ public abstract class AspectListValueModelAdapter } protected List buildValueList() { - return ListTools.list(this.iterator()); + return ListTools.arrayList(this.iterator()); } @Override diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeCollectionValueModel.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeCollectionValueModel.java index b720c883cc..54a5a00187 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeCollectionValueModel.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeCollectionValueModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -344,7 +344,7 @@ public class CompositeCollectionValueModel protected void collectionChanged(CollectionChangeEvent event) { this.removeAllComponentSources(); this.addAllComponentSources(); - this.fireCollectionChanged(VALUES, CollectionTools.collection(this.iterator())); + this.fireCollectionChanged(VALUES, CollectionTools.hashBag(this.iterator())); } @@ -396,7 +396,7 @@ public class CompositeCollectionValueModel ArrayList componentCollection = this.collections.get(componentCVM); this.removeComponentItems(componentCollection); this.addComponentItems(componentCVM, componentCollection); - this.fireCollectionChanged(VALUES, CollectionTools.collection(this.iterator())); + this.fireCollectionChanged(VALUES, CollectionTools.hashBag(this.iterator())); } // minimize scope of suppressed warnings diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeListValueModel.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeListValueModel.java index ac9e7d2900..ff4406a642 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeListValueModel.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/CompositeListValueModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -479,14 +479,14 @@ public class CompositeListValueModel protected Iterable buildSubListHolder(int fromIndex) { int listModelSize = this.listModel.size(); - return ListTools.list(this.listModel, listModelSize).subList(fromIndex, listModelSize); + return ListTools.arrayList(this.listModel, listModelSize).subList(fromIndex, listModelSize); } protected Iterable buildSubListHolder(int fromIndex, int toIndex) { int listModelSize = this.listModel.size(); return ((fromIndex == 0) && (toIndex == listModelSize)) ? this.listModel : - ListTools.list(this.listModel, listModelSize).subList(fromIndex, toIndex); + ListTools.arrayList(this.listModel, listModelSize).subList(fromIndex, toIndex); } @Override diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ExtendedListValueModelWrapper.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ExtendedListValueModelWrapper.java index 9d1fe07aa4..4545b8bd64 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ExtendedListValueModelWrapper.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ExtendedListValueModelWrapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -206,7 +206,7 @@ public class ExtendedListValueModelWrapper } private List buildList() { - return ListTools.list(this.listIterator_()); + return ListTools.arrayList(this.listIterator_()); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ItemAspectListValueModelAdapter.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ItemAspectListValueModelAdapter.java index 0d922e3c73..a567b95257 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ItemAspectListValueModelAdapter.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ItemAspectListValueModelAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -268,7 +268,7 @@ public abstract class ItemAspectListValueModelAdapter * whether the item aspect change is significant. */ protected void itemAspectChanged(@SuppressWarnings("unused") EventObject event) { - this.fireListChanged(LIST_VALUES, ListTools.list(this.listModel, this.listModel.size())); + this.fireListChanged(LIST_VALUES, ListTools.arrayList(this.listModel, this.listModel.size())); } } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ListCurator.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ListCurator.java index 71b92caca7..a95b278f6b 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ListCurator.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/ListCurator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -180,7 +180,7 @@ public abstract class ListCurator // ********** behavior ********** void submitInventoryReport() { - List newRecord = ListTools.list(this.iteratorForRecord()); + List newRecord = ListTools.arrayList(this.iteratorForRecord()); int recordIndex = 0; // add items from the new record diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleCollectionValueModel.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleCollectionValueModel.java index d10e73672f..3842893b13 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleCollectionValueModel.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleCollectionValueModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -137,9 +137,9 @@ public class SimpleCollectionValueModel return true; } if ((o instanceof Collection) && (o instanceof CollectionValueModel)) { - Collection c1 = CollectionTools.collection(this.collection); + Collection c1 = CollectionTools.hashBag(this.collection); @SuppressWarnings("unchecked") - Collection c2 = CollectionTools.collection(((Collection) o).iterator()); + Collection c2 = CollectionTools.hashBag(((Collection) o).iterator()); return c1.equals(c2); } return false; @@ -147,7 +147,7 @@ public class SimpleCollectionValueModel @Override public int hashCode() { - return CollectionTools.collection(this.collection).hashCode(); + return CollectionTools.hashBag(this.collection).hashCode(); } diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleListValueModel.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleListValueModel.java index f2056b9493..da81f0c2de 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleListValueModel.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SimpleListValueModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -152,9 +152,9 @@ public class SimpleListValueModel return true; } if ((o instanceof List) && (o instanceof ListValueModel)) { - List l1 = ListTools.list(this.list); + List l1 = ListTools.arrayList(this.list); @SuppressWarnings("unchecked") - List l2 = ListTools.list(((List) o).iterator()); + List l2 = ListTools.arrayList(((List) o).iterator()); return l1.equals(l2); } return false; diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SortedListValueModelAdapter.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SortedListValueModelAdapter.java index 39bcd0cb9d..455ef6ae00 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SortedListValueModelAdapter.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/SortedListValueModelAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -105,7 +105,7 @@ public class SortedListValueModelAdapter @Override protected Iterable buildSyncList() { - return CollectionTools.sortedSet(this.collectionHolder, this.comparator, this.collectionHolder.size()); + return CollectionTools.treeSet(this.collectionHolder, this.comparator, this.collectionHolder.size()); } /** diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/prefs/PreferencesCollectionValueModel.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/prefs/PreferencesCollectionValueModel.java index 58f65bff5b..23dfebd425 100644 --- a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/prefs/PreferencesCollectionValueModel.java +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/model/value/prefs/PreferencesCollectionValueModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -133,7 +133,7 @@ public class PreferencesCollectionValueModel

@Override protected void fireAspectChanged(Object oldValue, Object newValue) { @SuppressWarnings("unchecked") Iterator> iterator = (Iterator>) newValue; - this.fireCollectionChanged(VALUES, CollectionTools.collection(iterator)); + this.fireCollectionChanged(VALUES, CollectionTools.hashBag(iterator)); } @Override diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/AbstractArrayQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/AbstractArrayQueue.java new file mode 100644 index 0000000000..0f9d7569d8 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/AbstractArrayQueue.java @@ -0,0 +1,172 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.internal.queue; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Abstract array implementation of the {@link Queue} interface. + * @param the type of elements maintained by the queue + */ +public abstract class AbstractArrayQueue + implements Queue, Cloneable, Serializable +{ + protected transient E[] elements; + + /** Index of next element to be "dequeued". */ + protected transient int head = 0; + + /** Index of next element to be "enqueued". */ + protected transient int tail = 0; + + protected int size = 0; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty queue with the specified initial capacity. + */ + @SuppressWarnings("unchecked") + protected AbstractArrayQueue(int initialCapacity) { + super(); + if (initialCapacity < 0) { + throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ + } + this.elements = (E[]) new Object[initialCapacity]; + } + + + // ********** Queue implementation ********** + + public void enqueue(E element) { + this.elements[this.tail] = element; + if (++this.tail == this.elements.length) { + this.tail = 0; + } + this.size++; + } + + public E dequeue() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + E element = this.elements[this.head]; + this.elements[this.head] = null; // allow GC to work + if (++this.head == this.elements.length) { + this.head = 0; + } + this.size--; + return element; + } + + public E peek() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + return this.elements[this.head]; + } + + public boolean isEmpty() { + return this.size == 0; + } + + + // ********** standard methods ********** + + @Override + public AbstractArrayQueue clone() { + try { + @SuppressWarnings("unchecked") + AbstractArrayQueue clone = (AbstractArrayQueue) super.clone(); + @SuppressWarnings("cast") + E[] array = (E[]) this.elements.clone(); + clone.elements = array; + return clone; + } catch (CloneNotSupportedException ex) { + throw new InternalError(); + } + } + + @Override + public String toString() { + return Arrays.toString(this.copyElements(this.size)); + } + + protected E[] copyElements(int newCapacity) { + @SuppressWarnings("unchecked") + E[] newElements = (E[]) new Object[newCapacity]; + if (this.size != 0) { + int t = this.tail; + if (t == 0) { + t = this.elements.length; + } + if (this.head < t) { + // elements are contiguous + System.arraycopy(this.elements, this.head, newElements, 0, this.size); + } else { + // elements wrap past end of array + int fragmentSize = this.elements.length - this.head; + System.arraycopy(this.elements, this.head, newElements, 0, fragmentSize); + System.arraycopy(this.elements, 0, newElements, fragmentSize, (this.size - fragmentSize)); + } + } + return newElements; + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write size (and any hidden stuff) + stream.defaultWriteObject(); + int elementsLength = this.elements.length; + stream.writeInt(elementsLength); + if (this.size == 0) { + return; + } + // save the elements in contiguous order + int t = this.tail; + if (t == 0) { + t = elementsLength; + } + if (this.head < t) { // elements are contiguous + for (int i = this.head; i < t; i++) { + stream.writeObject(this.elements[i]); + } + } else { // (this.head >= t) - elements wrap past end of array + for (int i = this.head; i < elementsLength; i++) { + stream.writeObject(this.elements[i]); + } + for (int i = 0; i < this.tail; i++) { + stream.writeObject(this.elements[i]); + } + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read size (and any hidden stuff) + stream.defaultReadObject(); + int elementsLength = stream.readInt(); + Object[] array = new Object[elementsLength]; + for (int i = 0; i < this.size; i++) { + array[i] = stream.readObject(); + } + this.elements = (E[]) array; + this.head = 0; + this.tail = this.size; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ArrayQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ArrayQueue.java new file mode 100644 index 0000000000..5d0db4dbeb --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ArrayQueue.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.internal.queue; + +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Resizable-array FIFO implementation of the {@link Queue} interface. + * @param the type of elements maintained by the queue + * @see FixedCapacityArrayQueue + * @see QueueTools + */ +public class ArrayQueue + extends AbstractArrayQueue +{ + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty queue with the specified initial capacity. + */ + public ArrayQueue(int initialCapacity) { + super(initialCapacity); + } + + + // ********** Queue implementation ********** + + @Override + public void enqueue(E element) { + this.ensureCapacity(this.size + 1); + super.enqueue(element); + } + + /** + * Increase the queue's capacity, if necessary, to ensure it has at least + * the specified minimum capacity. + */ + public void ensureCapacity(int minCapacity) { + if (this.elements.length < minCapacity) { + int newCapacity = ((this.elements.length * 3) >> 1) + 1; + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + this.elements = this.copyElements(newCapacity); + this.head = 0; + this.tail = this.size; + } + } + + /** + * Decrease the queue's capacity, if necessary, to match its current size. + */ + public void trimToSize() { + if (this.elements.length > this.size) { + this.elements = this.copyElements(this.size); + this.head = 0; + this.tail = this.size; + } + } + + + // ********** standard methods ********** + + @Override + public ArrayQueue clone() { + return (ArrayQueue) super.clone(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/DequeQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/DequeQueue.java new file mode 100644 index 0000000000..041d4e4231 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/DequeQueue.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.queue; + +import java.io.Serializable; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Adapt a {@link Deque} to the {@link Queue} interface. + * Elements are dequeued from the head of the deque and + * enqueued to the tail of the deque. + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public class DequeQueue + implements Queue, Serializable +{ + private Deque deque; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a queue, adapting the specified deque. + * Elements are dequeued from the head of the deque and + * enqueued to the tail of the deque. + */ + public DequeQueue(Deque deque) { + super(); + this.deque = deque; + } + + + // ********** Queue implementation ********** + + public void enqueue(E element) { + this.deque.enqueueTail(element); + } + + public E dequeue() { + return this.deque.dequeueHead(); + } + + public E peek() { + return this.deque.peekHead(); + } + + public boolean isEmpty() { + return this.deque.isEmpty(); + } + + + // ********** standard methods ********** + + @Override + public String toString() { + return this.deque.toString(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/EmptyQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/EmptyQueue.java new file mode 100644 index 0000000000..2d4c277d55 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/EmptyQueue.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.internal.queue; + +import java.io.Serializable; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Empty implementation of the {@link Queue} interface. + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public final class EmptyQueue + implements Queue, Serializable +{ + @SuppressWarnings("rawtypes") + public static final Queue INSTANCE = new EmptyQueue(); + @SuppressWarnings("unchecked") + public static Queue instance() { + return INSTANCE; + } + + // ensure single instance + private EmptyQueue() { + super(); + } + + public void enqueue(E o) { + throw new UnsupportedOperationException(); + } + + public E dequeue() { + throw new NoSuchElementException(); + } + + public E peek() { + throw new NoSuchElementException(); + } + + public boolean isEmpty() { + return true; + } + + @Override + public String toString() { + return "[]"; //$NON-NLS-1$ + } + + private static final long serialVersionUID = 1L; + private Object readResolve() { + // replace this object with the singleton + return INSTANCE; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/FixedCapacityArrayQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/FixedCapacityArrayQueue.java new file mode 100644 index 0000000000..124bdc706a --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/FixedCapacityArrayQueue.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.queue; + +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Fixed-capacity array FIFO implementation of the {@link Queue} interface. + * This implementation will throw an exception if its capacity is exceeded. + * @param the type of elements maintained by the queue + * @see ArrayQueue + * @see QueueTools + */ +public class FixedCapacityArrayQueue + extends AbstractArrayQueue +{ + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty queue with the specified capacity. + */ + public FixedCapacityArrayQueue(int capacity) { + super(capacity); + } + + + // ********** Queue implementation ********** + + /** + * @exception IllegalStateException if the queue is full + */ + @Override + public void enqueue(E element) { + if (this.isFull()) { + throw new IllegalStateException("Queue is full."); //$NON-NLS-1$ + } + super.enqueue(element); + } + + /** + * Return whether the queue is full, + * as its capacity is fixed. + */ + public boolean isFull() { + return this.size == this.elements.length; + } + + + // ********** standard methods ********** + + @Override + public FixedCapacityArrayQueue clone() { + return (FixedCapacityArrayQueue) super.clone(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/LinkedQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/LinkedQueue.java new file mode 100644 index 0000000000..83aeb357f5 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/LinkedQueue.java @@ -0,0 +1,283 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.internal.queue; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Linked FIFO implementation of the {@link Queue} interface. + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public class LinkedQueue + implements Queue, Cloneable, Serializable +{ + private final NodeFactory nodeFactory; + private transient Node head; // next element to dequeue + private transient Node tail; // last element + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty queue with no node cache. + */ + public LinkedQueue() { + this(0); + } + + /** + * Construct an empty queue with a node cache with the specified size. + * Specify a cache size of -1 for an unlimited cache. + */ + public LinkedQueue(int cacheSize) { + this(LinkedQueue.buildNodeFactory(cacheSize)); + this.head = null; + } + + private static NodeFactory buildNodeFactory(int cacheSize) { + if (cacheSize < -1) { + throw new IllegalArgumentException("Cache size must be greater than or equal to -1: " + cacheSize); //$NON-NLS-1$ + } + return (cacheSize == 0) ? SimpleNodeFactory.instance() : new CachingNodeFactory(cacheSize); + } + + private LinkedQueue(NodeFactory nodeFactory) { + super(); + this.nodeFactory = nodeFactory; + this.head = null; + this.tail = null; + } + + + // ********** Queue implementation ********** + + public void enqueue(E element) { + Node newNode = this.nodeFactory.buildNode(element, null); + if (this.tail == null) { + this.head = newNode; // first node + } else { + this.tail.next = newNode; + } + this.tail = newNode; + } + + public E dequeue() { + if (this.head == null) { + throw new NoSuchElementException(); + } + Node node = this.head; + this.head = node.next; + if (this.head == null) { + this.tail = null; // last node + } + E element = node.element; + this.nodeFactory.release(node); + return element; + } + + public E peek() { + if (this.head == null) { + throw new NoSuchElementException(); + } + return this.head.element; + } + + public boolean isEmpty() { + return this.head == null; + } + + + // ********** standard methods ********** + + @Override + public LinkedQueue clone() { + LinkedQueue clone = new LinkedQueue(this.nodeFactory.copy()); + E[] elements = this.buildElements(); + for (E element : elements) { + clone.enqueue(element); + } + return clone; + } + + @SuppressWarnings("unchecked") + private E[] buildElements() { + int size = this.size(); + if (size == 0) { + return (E[]) ObjectTools.EMPTY_OBJECT_ARRAY; + } + E[] elements = (E[]) new Object[size]; + int i = 0; + for (Node node = this.head; node != null; node = node.next) { + elements[i++] = node.element; + } + return elements; + } + + private int size() { + int size = 0; + for (Node node = this.head; node != null; node = node.next) { + size++; + } + return size; + } + + @Override + public String toString() { + return Arrays.toString(this.buildElements()); + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write nodeFactory (and any hidden stuff) + stream.defaultWriteObject(); + Object[] elements = this.buildElements(); + stream.writeInt(elements.length); + for (Object element : elements) { + stream.writeObject(element); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read nodeFactory (and any hidden stuff) + stream.defaultReadObject(); + int len = stream.readInt(); + for (int i = len; i-- > 0; ) { + this.enqueue((E) stream.readObject()); + } + } + + + // ********** Node classes ********** + + private static final class Node { + E element; + Node next; + + Node(E element, Node next) { + super(); + this.element = element; + this.next = next; + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.element); + } + } + + private abstract static class NodeFactory { + NodeFactory() { + super(); + } + + Node buildNode(E element, Node next) { + return new Node(element, next); + } + + abstract void release(Node node); + + abstract NodeFactory copy(); + } + + private static class SimpleNodeFactory + extends NodeFactory + implements Serializable + { + @SuppressWarnings("rawtypes") + public static final NodeFactory INSTANCE = new SimpleNodeFactory(); + @SuppressWarnings("unchecked") + public static NodeFactory instance() { + return INSTANCE; + } + + private SimpleNodeFactory() { + super(); + } + + @Override + void release(Node node) { + // NOP + } + + @Override + NodeFactory copy() { + return this; + } + + @Override + public String toString() { + return ObjectTools.singletonToString(this); + } + + private static final long serialVersionUID = 1L; + private Object readResolve() { + // replace this object with the singleton + return INSTANCE; + } + } + + private static final class CachingNodeFactory + extends NodeFactory + implements Serializable + { + private final int maxCacheSize; + private transient int cacheSize = 0; + private transient Node cacheHead; + private static final long serialVersionUID = 1L; + + CachingNodeFactory(int maxCacheSize) { + super(); + this.maxCacheSize = maxCacheSize; + } + + @Override + Node buildNode(E element, Node next) { + if (this.cacheHead == null) { + return super.buildNode(element, next); + } + Node node = this.cacheHead; + this.cacheHead = node.next; + this.cacheSize--; + node.element = element; + node.next = next; + return node; + } + + @Override + void release(Node node) { + if ((this.maxCacheSize == -1) || (this.cacheSize < this.maxCacheSize)) { + node.element = null; // allow GC to work + node.next = this.cacheHead; + this.cacheHead = node; + this.cacheSize++; + } + } + + @Override + NodeFactory copy() { + return new CachingNodeFactory(this.maxCacheSize); + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.cacheSize); + } + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ListQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ListQueue.java new file mode 100644 index 0000000000..14fe489a31 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/ListQueue.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.queue; + +import java.io.Serializable; +import java.util.List; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Adapt a {@link List} to the {@link Queue} interface. + * Elements are dequeued from the front of the list (i.e. index 0). + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public class ListQueue + implements Queue, Serializable +{ + private List list; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a queue, adapting the specified list. + * The queue will dequeue its elements in the same + * order they are returned by the list's iterator (i.e. the + * first element returned by the list's iterator will be the + * first element returned by {@link #dequeue()}). + */ + public ListQueue(List list) { + super(); + this.list = list; + } + + + // ********** Queue implementation ********** + + public void enqueue(E element) { + this.list.add(element); + } + + public E dequeue() { + if (this.list.size() == 0) { + throw new NoSuchElementException(); + } + return this.list.remove(0); + } + + public E peek() { + if (this.list.size() == 0) { + throw new NoSuchElementException(); + } + return this.list.get(0); + } + + public boolean isEmpty() { + return this.list.isEmpty(); + } + + + // ********** standard methods ********** + + @Override + public String toString() { + return this.list.toString(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/PriorityQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/PriorityQueue.java new file mode 100644 index 0000000000..6dec365f41 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/PriorityQueue.java @@ -0,0 +1,249 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.queue; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Comparator; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Resizable priority implementation of the {@link Queue} interface. + * Elements will dequeue in the order determined by a comparator + * (i.e. {@link #dequeue} will return the element sorted first). + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public class PriorityQueue + implements Queue, Cloneable, Serializable +{ + private final Comparator comparator; + + /** + * Standard heap implementation. + * To simplify our math, we leave the first slot [0] empty. + */ + private transient E[] elements; + + private int size = 0; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty priority queue with the specified comparator + * and initial capacity. + */ + @SuppressWarnings("unchecked") + public PriorityQueue(Comparator comparator, int initialCapacity) { + super(); + if (comparator == null) { + throw new NullPointerException(); + } + this.comparator = comparator; + if (initialCapacity < 0) { + throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ + } + + this.elements = (E[]) new Object[initialCapacity + 1]; + } + + /** + * Construct a priority queue with the specified comparator, + * initial array of elements, and size. The array of elements + * should hold elements at contiguous indices from + * 1 to the the specified size, inclusive. The array should not + * hold an element at index 0. The queue will not copy the + * elements from the supplied array; i.e. the queue will directly use + * and manipulate the supplied array. + */ + public PriorityQueue(Comparator comparator, E[] initialElements, int size) { + super(); + if (comparator == null) { + throw new NullPointerException(); + } + this.comparator = comparator; + + if (initialElements == null) { + throw new NullPointerException(); + } + if (initialElements.length == 0) { + throw new IllegalArgumentException("Initial elements array must have a length of at least 1."); //$NON-NLS-1$ + } + this.elements = initialElements; + + if (size < 0) { + throw new IllegalArgumentException("Illegal size: " + size); //$NON-NLS-1$ + } + this.size = size; + + if (this.size > 1) { + // this is similar to what we do when an element is dequeued + int nonLeafMax = this.size >> 1; + for (int i = nonLeafMax; i > 0; i--) { // we need move only non-leaf nodes + int current = i; + do { + int child = current << 1; // left child + if ((child < this.size) && (this.comparator.compare(this.elements[child + 1], this.elements[child]) < 0)) { + // right child exists and is less than left (i.e. dequeues first) + child++; + } + if (this.comparator.compare(this.elements[current], this.elements[child]) < 0) { + break; + } + ArrayTools.swap(this.elements, current, child); + current = child; + } while (current <= nonLeafMax); // i.e. not a leaf (i.e. has at least one child) + } + } + } + + + // ********** Queue implementation ********** + + public void enqueue(E element) { + this.ensureCapacity(this.size + 1); + this.size++; + int current = this.size; + this.elements[current] = element; + int parent = current >> 1; + while ((parent != 0) && this.comparator.compare(this.elements[current], this.elements[parent]) < 0) { + ArrayTools.swap(this.elements, current, parent); + current = parent; + parent = current >> 1; + } + } + + /** + * Increase the queue's capacity, if necessary, to ensure it has at least + * the specified minimum capacity. + */ + public void ensureCapacity(int minCapacity) { + int oldCapacity = this.elements.length - 1; + if (oldCapacity < minCapacity) { + int newCapacity = ((oldCapacity * 3) >> 1) + 1; + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + this.elements = this.copyElements(newCapacity); + } + } + + /** + * Decrease the queue's capacity, if necessary, to match its current size. + */ + public void trimToSize() { + if (this.elements.length > this.size + 1) { + this.elements = this.copyElements(this.size); + } + } + + private E[] copyElements(int newCapacity) { + @SuppressWarnings("unchecked") + E[] newElements = (E[]) new Object[newCapacity + 1]; + System.arraycopy(this.elements, 1, newElements, 1, this.size); // skip 0 + return newElements; + } + + public E dequeue() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + E element = this.elements[1]; + if (this.size != 1) { + // replace root with last node and move it to its new position + ArrayTools.swap(this.elements, 1, this.size); + int newSize = this.size - 1; + int nonLeafMax = newSize >> 1; + int current = 1; + while (current <= nonLeafMax) { // i.e. not a leaf (i.e. has at least one child) + int child = current << 1; // left child + if ((child < newSize) && (this.comparator.compare(this.elements[child + 1], this.elements[child]) < 0)) { + // right child exists and is less than left (i.e. dequeues first) + child++; + } + if (this.comparator.compare(this.elements[current], this.elements[child]) < 0) { + break; + } + ArrayTools.swap(this.elements, current, child); + current = child; + } + } + this.elements[this.size] = null; // allow GC to work + this.size--; + return element; + } + + public E peek() { + if (this.size == 0) { + throw new NoSuchElementException(); + } + return this.elements[1]; + } + + public boolean isEmpty() { + return this.size == 0; + } + + + // ********** standard methods ********** + + @Override + public PriorityQueue clone() { + try { + @SuppressWarnings("unchecked") + PriorityQueue clone = (PriorityQueue) super.clone(); + @SuppressWarnings("cast") + E[] array = (E[]) this.elements.clone(); + clone.elements = array; + return clone; + } catch (CloneNotSupportedException ex) { + throw new InternalError(); + } + } + + @Override + public String toString() { + return Arrays.toString(ArrayTools.subArray(this.elements, 1, this.size + 1)); + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write comparator and size (and any hidden stuff) + stream.defaultWriteObject(); + Object[] array = this.elements; + int elementsLength = array.length; + stream.writeInt(elementsLength); + if (this.size == 0) { + return; + } + for (int i = 1; i <= this.size; i++) { // skip 0 + stream.writeObject(array[i]); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read comparator and size (and any hidden stuff) + stream.defaultReadObject(); + int elementsLength = stream.readInt(); + Object[] array = new Object[elementsLength]; + for (int i = 1; i <= this.size; i++) { // skip 0 + array[i] = stream.readObject(); + } + this.elements = (E[]) array; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/QueueTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/QueueTools.java new file mode 100644 index 0000000000..88b7bb3707 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/QueueTools.java @@ -0,0 +1,534 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.queue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.collection.MapTools; +import org.eclipse.jpt.common.utility.internal.comparator.ComparatorTools; +import org.eclipse.jpt.common.utility.internal.stack.ArrayStack; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; + +/** + * {@link Queue} utility methods. + */ +public final class QueueTools { + + // ********** enqueue all ********** + + /** + * Enqueue all the elements returned by the specified iterable + * on the specified queue. + * Return whether the queue changed as a result. + */ + public static boolean enqueueAll(Queue queue, Iterable iterable) { + return enqueueAll(queue, iterable.iterator()); + } + + /** + * Enqueue all the elements returned by the specified iterator + * on the specified queue. + * Return whether the queue changed as a result. + */ + public static boolean enqueueAll(Queue queue, Iterator iterator) { + return iterator.hasNext() && enqueueAll_(queue, iterator); + } + + /** + * assume the iterator is not empty + */ + private static boolean enqueueAll_(Queue queue, Iterator iterator) { + do { + queue.enqueue(iterator.next()); + } while (iterator.hasNext()); + return true; + } + + /** + * Enqueue all the elements in the specified array + * on the specified queue. + * Return whether the queue changed as a result. + */ + public static boolean enqueueAll(Queue queue, E... array) { + int len = array.length; + return (len != 0) && enqueueAll_(queue, array, len); + } + + /** + * assume the array is not empty + */ + private static boolean enqueueAll_(Queue queue, E[] array, int arrayLength) { + int i = 0; + do { + queue.enqueue(array[i++]); + } while (i < arrayLength); + return true; + } + + + // ********** drain ********** + + /** + * Drain all the elements from the specified queue and return them in a + * list. + */ + public static ArrayList drain(Queue queue) { + ArrayList result = new ArrayList(); + drainTo(queue, result); + return result; + } + + /** + * Drain all the elements from the specified queue and add them to the + * specified collection. + * Return whether the queue changed as a result. + */ + public static boolean drainTo(Queue queue, Collection collection) { + return ( ! queue.isEmpty()) && drainTo_(queue, collection); + } + + /** + * assume the queue is not empty + */ + private static boolean drainTo_(Queue queue, Collection collection) { + do { + collection.add(queue.dequeue()); + } while ( ! queue.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified queue + * to the specified list at the specified index. + * Return whether the queue changed as a result. + */ + public static boolean drainTo(Queue queue, List list, int index) { + return ( ! queue.isEmpty()) && drainTo_(queue, list, index); + } + + /** + * assume the queue is not empty + */ + private static boolean drainTo_(Queue queue, List list, int index) { + return (index == list.size()) ? drainTo_(queue, list) : list.addAll(index, drain(queue)); + } + + /** + * Drain all the elements from the specified queue and push them on the + * specified stack. + * Return whether the queue changed as a result. + */ + public static boolean drainTo(Queue queue, Stack stack) { + return ( ! queue.isEmpty()) && drainTo_(queue, stack); + } + + /** + * assume the queue is not empty + */ + private static boolean drainTo_(Queue queue, Stack stack) { + do { + stack.push(queue.dequeue()); + } while ( ! queue.isEmpty()); + return true; + } + + /** + * Drain all the elements from the first specified queue and enqueue them + * on the second specified queue. + * Return whether the first queue changed as a result. + */ + public static boolean drainTo(Queue queue1, Queue queue2) { + return ( ! queue1.isEmpty()) && drainTo_(queue1, queue2); + } + + /** + * assume queue 1 is not empty + */ + private static boolean drainTo_(Queue queue1, Queue queue2) { + do { + queue2.enqueue(queue1.dequeue()); + } while ( ! queue1.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified queue, passing each element to the + * specified key transformer. Map the generated key to its element. + * Return whether the queue changed as a result. + */ + public static boolean drainTo(Queue queue, Map map, Transformer keyTransformer) { + return ( ! queue.isEmpty()) && drainTo_(queue, map, keyTransformer); + } + + /** + * assume the queue is not empty + */ + private static boolean drainTo_(Queue queue, Map map, Transformer keyTransformer) { + do { + MapTools.add(map, queue.dequeue(), keyTransformer); + } while ( ! queue.isEmpty()); + return true; + } + + /** + * Drain all the elements from the specified queue, passing each element to the + * specified key and value transformers. Add the generated key/value pairs + * to the specified map. + * Return whether the queue changed as a result. + */ + public static boolean drainTo(Queue queue, Map map, Transformer keyTransformer, Transformer valueTransformer) { + return ( ! queue.isEmpty()) && drainTo_(queue, map, keyTransformer, valueTransformer); + } + + /** + * assume the queue is not empty + */ + private static boolean drainTo_(Queue queue, Map map, Transformer keyTransformer, Transformer valueTransformer) { + do { + MapTools.add(map, queue.dequeue(), keyTransformer, valueTransformer); + } while ( ! queue.isEmpty()); + return true; + } + + + // ********** array queue factory methods ********** + + /** + * Return an empty array-based FIFO queue. + */ + public static ArrayQueue arrayQueue() { + return arrayQueue(10); + } + + /** + * Return an empty array-based FIFO queue with specified initial capacity. + */ + public static ArrayQueue arrayQueue(int initialCapacity) { + return new ArrayQueue(initialCapacity); + } + + /** + * Return an array-based FIFO queue corresponding to the specified iterable. + */ + public static ArrayQueue arrayQueue(Iterable iterable) { + return arrayQueue(iterable.iterator()); + } + + /** + * Return an array-based FIFO queue corresponding to the specified iterable. + * The specified iterable size is a performance hint. + */ + public static ArrayQueue arrayQueue(Iterable iterable, int iterableSize) { + return arrayQueue(iterable.iterator(), iterableSize); + } + + /** + * Return an array-based FIFO queue corresponding to the specified iterator. + */ + public static ArrayQueue arrayQueue(Iterator iterator) { + ArrayQueue result = QueueTools.arrayQueue(); + enqueueAll(result, iterator); + return result; + } + + /** + * Return an array-based FIFO queue corresponding to the specified iterator. + * The specified iterator size is a performance hint. + */ + public static ArrayQueue arrayQueue(Iterator iterator, int iteratorSize) { + ArrayQueue result = QueueTools.arrayQueue(iteratorSize); + enqueueAll(result, iterator); + return result; + } + + /** + * Return an array-based FIFO queue corresponding to the specified array. + */ + public static ArrayQueue arrayQueue(E... array) { + ArrayQueue result = QueueTools.arrayQueue(array.length); + enqueueAll(result, array); + return result; + } + + + // ********** linked queue factory methods ********** + + /** + * Return an empty link-based FIFO queue with no node cache. + */ + public static LinkedQueue linkedQueue() { + return linkedQueue(0); + } + + /** + * Return an empty link-based FIFO queue + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedQueue linkedQueue(int cacheSize) { + return new LinkedQueue(cacheSize); + } + + /** + * Return a link-based FIFO queue corresponding to the specified iterable. + */ + public static LinkedQueue linkedQueue(Iterable iterable) { + return linkedQueue(iterable, 0); + } + + /** + * Return a link-based FIFO queue corresponding to the specified iterable + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedQueue linkedQueue(Iterable iterable, int cacheSize) { + return linkedQueue(iterable.iterator(), cacheSize); + } + + /** + * Return a link-based FIFO queue corresponding to the specified iterator. + */ + public static LinkedQueue linkedQueue(Iterator iterator) { + return linkedQueue(iterator, 0); + } + + /** + * Return a link-based FIFO queue corresponding to the specified iterator + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedQueue linkedQueue(Iterator iterator, int cacheSize) { + LinkedQueue result = QueueTools.linkedQueue(cacheSize); + enqueueAll(result, iterator); + return result; + } + + /** + * Return a link-based FIFO queue corresponding to the specified array. + */ + public static LinkedQueue linkedQueue(E... array) { + return linkedQueue(array, 0); + } + + /** + * Return a link-based FIFO queue corresponding to the specified array + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedQueue linkedQueue(E[] array, int cacheSize) { + LinkedQueue result = QueueTools.linkedQueue(cacheSize); + enqueueAll(result, array); + return result; + } + + + // ********** fixed size queue factory methods ********** + + /** + * Return a fixed-capacity array queue with the specified capacity. + */ + public static FixedCapacityArrayQueue fixedCapacityArrayQueue(int capacity) { + return new FixedCapacityArrayQueue(capacity); + } + + /** + * Return a fized-capacity array queue containing the elements of the specified + * collection. The queue will dequeue its elements in the same + * order they are returned by the collection's iterator (i.e. the + * first element returned by the collection's iterator will be the + * first element returned by {@link Queue#dequeue()}). + * The queue's capacity will be match the collection's size. + */ + public static FixedCapacityArrayQueue fixedCapacityArrayQueue(Collection collection) { + FixedCapacityArrayQueue result = QueueTools.fixedCapacityArrayQueue(collection.size()); + enqueueAll(result, collection); + return result; + } + + + // ********** stack queue factory methods ********** + + /** + * Return a LIFO queue. + */ + public static StackQueue stackQueue() { + return adapt(new ArrayStack()); + } + + /** + * Adapt the specified stack to the {@link Queue} interface, + * implementing a LIFO queue. + */ + public static StackQueue adapt(Stack stack) { + return new StackQueue(stack); + } + + + // ********** priority queue factory methods ********** + + /** + * Return a priority queue that returns its elements in + * {@linkplain Comparable natural order}. + */ + public static > PriorityQueue priorityQueue() { + return priorityQueue(10); + } + + /** + * Return a priority queue that returns its elements in + * {@linkplain Comparable natural order} and has the specified initial capacity. + */ + public static > PriorityQueue priorityQueue(int initialCapacity) { + return priorityQueue(ComparatorTools.naturalComparator(), initialCapacity); + } + + /** + * Return a priority queue whose elements are returned in + * the order determined by the specified comparator. + */ + public static PriorityQueue priorityQueue(Comparator comparator) { + return priorityQueue(comparator, 10); + } + + /** + * Return a priority queue whose elements are returned in + * the order determined by the specified comparator + * and has the specified initial capacity. + */ + public static PriorityQueue priorityQueue(Comparator comparator, int initialCapacity) { + return new PriorityQueue(comparator, initialCapacity); + } + + /** + * Construct a priority queue with the specified initial full array of elements. + * The priority queue will return its elements in {@linkplain Comparable natural order}. + * The array of elements should hold elements at + * every index except 0. The queue will not copy the + * elements from the supplied array; i.e. the queue will directly use and manipulate + * the supplied array. + */ + public static > PriorityQueue priorityQueue(E[] initialElements) { + return priorityQueue(initialElements, initialElements.length - 1); + } + + /** + * Construct a priority queue with the specified initial array of elements and size. + * The priority queue will return its elements in {@linkplain Comparable natural order}. + * The array of elements should hold elements at contiguous indices from + * 1 to the the specified size, inclusive. The array should not + * hold an element at index 0. The queue will not copy the + * elements from the supplied array; i.e. the queue will directly use and manipulate + * the supplied array. + */ + public static > PriorityQueue priorityQueue(E[] initialElements, int size) { + return priorityQueue(ComparatorTools.naturalComparator(), initialElements, size); + } + + /** + * Construct a priority queue with the specified comparator and + * initial full array of elements. + * The array of elements should hold elements at + * every index except 0. The queue will not copy the + * elements from the supplied array; i.e. the queue will directly use and manipulate + * the supplied array. + */ + public static PriorityQueue priorityQueue(Comparator comparator, E[] initialElements) { + return priorityQueue(comparator, initialElements, initialElements.length - 1); + } + + /** + * Construct a priority queue with the specified comparator, + * initial array of elements, and size. The array of elements + * should hold elements at contiguous indices from + * 1 to the the specified size, inclusive. The array should not + * hold an element at index 0. The queue will not copy the + * elements from the supplied array; i.e. the queue will directly use and manipulate + * the supplied array. + */ + public static PriorityQueue priorityQueue(Comparator comparator, E[] initialElements, int size) { + return new PriorityQueue(comparator, initialElements, size); + } + + + // ********** synchronized queue factory methods ********** + + /** + * Return a synchronized queue. + */ + public static SynchronizedQueue synchronizedQueue() { + ArrayQueue queue = arrayQueue(); + return synchronizedQueue(queue); + } + + /** + * Return a queue that synchronizes with specified mutex. + */ + public static SynchronizedQueue synchronizedQueue(Object mutex) { + ArrayQueue queue = arrayQueue(); + return synchronizedQueue(queue, mutex); + } + + /** + * Return a queue that synchronizes the specified queue. + */ + public static SynchronizedQueue synchronizedQueue(Queue queue) { + return new SynchronizedQueue(queue); + } + + /** + * Return a queue that synchronizes the specified queue + * with specified mutex. + */ + public static SynchronizedQueue synchronizedQueue(Queue queue, Object mutex) { + return new SynchronizedQueue(queue, mutex); + } + + + // ********** misc queue factory methods ********** + + /** + * Adapt the specified deque to the {@link Queue} interface. + */ + public static DequeQueue adapt(Deque deque) { + return new DequeQueue(deque); + } + + /** + * Adapt the specified list to the {@link Queue} interface. + */ + public static ListQueue adapt(List list) { + return new ListQueue(list); + } + + /** + * Return an unmodifiable empty queue. + */ + public static Queue emptyQueue() { + return EmptyQueue.instance(); + } + + + // ********** constructor ********** + + /** + * Suppress default constructor, ensuring non-instantiability. + */ + private QueueTools() { + super(); + throw new UnsupportedOperationException(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/StackQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/StackQueue.java new file mode 100644 index 0000000000..11503386fd --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/StackQueue.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.queue; + +import java.io.Serializable; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Adapt a {@link Stack} to create a LIFO implementation of the {@link Queue} + * interface. + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public class StackQueue + implements Queue, Serializable +{ + private final Stack stack; + + private static final long serialVersionUID = 1L; + + + public StackQueue(Stack stack) { + super(); + if (stack == null) { + throw new NullPointerException(); + } + this.stack = stack; + } + + public void enqueue(E element) { + this.stack.push(element); + } + + public E dequeue() { + return this.stack.pop(); + } + + public E peek() { + return this.stack.peek(); + } + + public boolean isEmpty() { + return this.stack.isEmpty(); + } + + @Override + public String toString() { + return this.stack.toString(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/SynchronizedQueue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/SynchronizedQueue.java new file mode 100644 index 0000000000..c5c1deea89 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/queue/SynchronizedQueue.java @@ -0,0 +1,602 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.internal.queue; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.command.Command; +import org.eclipse.jpt.common.utility.internal.collection.MapTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; + +/** + * Thread-safe implementation of the {@link Queue} interface. + * This also provides protocol for suspending a thread until the + * queue is empty or not empty, with optional time-outs. + * @param the type of elements maintained by the queue + * @see QueueTools + */ +public class SynchronizedQueue + implements Queue, Serializable +{ + /** Backing queue. */ + private final Queue queue; + + /** Object to synchronize on. */ + private final Object mutex; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a synchronized queue that wraps the + * specified queue and locks on the specified mutex. + */ + public SynchronizedQueue(Queue queue, Object mutex) { + super(); + if ((queue == null) || (mutex == null)) { + throw new NullPointerException(); + } + this.queue = queue; + this.mutex = mutex; + } + + /** + * Construct a synchronized queue that wraps the + * specified queue and locks on itself. + */ + public SynchronizedQueue(Queue queue) { + super(); + if (queue == null) { + throw new NullPointerException(); + } + this.queue = queue; + this.mutex = this; + } + + + // ********** Queue implementation ********** + + public void enqueue(E element) { + synchronized (this.mutex) { + this.enqueue_(element); + } + } + + /** + * Pre-condition: synchronized + */ + private void enqueue_(E element) { + this.queue.enqueue(element); + this.mutex.notifyAll(); + } + + public E dequeue() { + synchronized (this.mutex) { + return this.dequeue_(); + } + } + + /** + * Pre-condition: synchronized + */ + private E dequeue_() { + E element = this.queue.dequeue(); + this.mutex.notifyAll(); + return element; + } + + public E peek() { + synchronized (this.mutex) { + return this.queue.peek(); + } + } + + public boolean isEmpty() { + synchronized (this.mutex) { + return this.queue.isEmpty(); + } + } + + + // ********** indefinite waits ********** + + /** + * Suspend the current thread until the queue's empty status changes + * to the specified value. + */ + public void waitUntilEmptyIs(boolean empty) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(empty); + } + } + + /** + * Pre-condition: synchronized + */ + private void waitUntilEmptyIs_(boolean empty) throws InterruptedException { + while (this.queue.isEmpty() != empty) { + this.mutex.wait(); + } + } + + /** + * Suspend the current thread until the queue is empty. + */ + public void waitUntilEmpty() throws InterruptedException { + this.waitUntilEmptyIs(true); + } + + /** + * Suspend the current thread until the queue has something on it. + */ + public void waitUntilNotEmpty() throws InterruptedException { + this.waitUntilEmptyIs(false); + } + + /** + * Suspend the current thread until the queue is empty, + * then "enqueue" the specified item to the tail of the queue + * and continue executing. + */ + public void waitToEnqueue(E element) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(true); + this.enqueue_(element); + } + } + + /** + * Suspend the current thread until the queue has something on it, + * then "dequeue" an item from the head of the queue and return it. + */ + public Object waitToDequeue() throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(false); + return this.dequeue_(); + } + } + + + // ********** timed waits ********** + + /** + * Suspend the current thread until the queue's empty status changes + * to the specified value or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if the specified + * empty status was achieved; return false if a time-out occurred. + * If the queue's empty status is already the specified value, + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilEmptyIs(boolean empty, long timeout) throws InterruptedException { + synchronized (this.mutex) { + return this.waitUntilEmptyIs_(empty, timeout); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean waitUntilEmptyIs_(boolean empty, long timeout) throws InterruptedException { + if (timeout == 0L) { + this.waitUntilEmptyIs_(empty); // wait indefinitely until notified + return true; // if it ever comes back, the condition was met + } + + long stop = System.currentTimeMillis() + timeout; + long remaining = timeout; + while ((this.queue.isEmpty() != empty) && (remaining > 0L)) { + this.mutex.wait(remaining); + remaining = stop - System.currentTimeMillis(); + } + return (this.queue.isEmpty() == empty); + } + + /** + * Suspend the current thread until the queue is empty + * or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if + * the queue is empty; return false if a time-out occurred. + * If the queue is already empty, return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilEmpty(long timeout) throws InterruptedException { + return this.waitUntilEmptyIs(true, timeout); + } + + /** + * Suspend the current thread until the queue has something on it. + * or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if + * the queue is not empty; return false if a time-out occurred. + * If the queue already has something on it, return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilNotEmpty(long timeout) throws InterruptedException { + return this.waitUntilEmptyIs(false, timeout); + } + + /** + * Suspend the current thread until the queue is empty, + * then "enqueue" the specified item to the tail of the queue + * and continue executing. If the queue is not emptied out + * before the time-out, simply continue executing without + * "enqueueing" the item. + * The time-out is specified in milliseconds. Return true if the + * item was enqueued; return false if a time-out occurred. + * If the queue is already empty, "enqueue" the specified item and + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitToEnqueue(E element, long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(true, timeout); + if (success) { + this.enqueue_(element); + } + return success; + } + } + + /** + * Suspend the current thread until the queue has something on it, + * then "dequeue" an item from the head of the queue and return it. + * If the queue is empty and nothing is "enqueued" on to it before the + * time-out, throw a no such element exception. + * The time-out is specified in milliseconds. + * If the queue is not empty, "dequeue" an item and + * return it immediately. + * If the time-out is zero, wait indefinitely. + */ + public Object waitToDequeue(long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(false, timeout); + if (success) { + return this.dequeue_(); + } + throw new NoSuchElementException(); + } + } + + + // ********** synchronized behavior ********** + + /** + * If the current thread is not interrupted, execute the specified command + * with the mutex locked. This is useful for initializing the queue in another + * thread. + */ + public void execute(Command command) throws InterruptedException { + if (Thread.currentThread().isInterrupted()) { + throw new InterruptedException(); + } + synchronized (this.mutex) { + command.execute(); + } + } + + + // ********** additional public protocol ********** + + /** + * "Enqueue" all the elements returned by the specified iterable. + * Return whether the queue changed as a result. + */ + public boolean enqueueAll(Iterable iterable) { + return this.enqueueAll(iterable.iterator()); + } + + /** + * "Enqueue" all the elements returned by the specified iterator. + * Return whether the queue changed as a result. + */ + public boolean enqueueAll(Iterator iterator) { + if ( ! iterator.hasNext()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueAll_(iterator); + } + } + + /** + * Pre-condition: synchronized + * Assume the iterator is not empty. + */ + private boolean enqueueAll_(Iterator iterator) { + do { + this.queue.enqueue(iterator.next()); + } while (iterator.hasNext()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Enqueue" all the elements in the specified array. + * Return whether the queue changed as a result. + */ + public boolean enqueueAll(E... array) { + int len = array.length; + if (len == 0) { + return false; + } + synchronized (this.mutex) { + return this.enqueueAll_(array, len); + } + } + + /** + * Pre-condition: synchronized + * Assume the array is not empty. + */ + private boolean enqueueAll_(E[] array, int arrayLength) { + int i = 0; + do { + this.queue.enqueue(array[i++]); + } while (i < arrayLength); + this.mutex.notifyAll(); + return true; + } + + /** + * Pop all the elements from the specified stack and "enqueue" them. + * Return whether the queue changed as a result. + */ + public boolean enqueueAll(Stack stack) { + if (stack.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueAll_(stack); + } + } + + /** + * Pre-condition: synchronized + * Assume the stack is not empty. + */ + private boolean enqueueAll_(Stack stack) { + do { + this.queue.enqueue(stack.pop()); + } while ( ! stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Dequeue" all the elements from the specified queue and + * "enqueue" them. + * Return whether the queue changed as a result. + * @see #drainTo(Queue) + */ + public boolean enqueueAll(Queue q) { + if (q.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.enqueueAll_(q); + } + } + + /** + * Pre-condition: synchronized + * Assume the queue is not empty. + */ + private boolean enqueueAll_(Queue q) { + do { + this.queue.enqueue(q.dequeue()); + } while ( ! q.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the queue and return them in a list. + */ + public ArrayList drain() { + ArrayList result = new ArrayList(); + this.drainTo(result); + return result; + } + + /** + * "Drain" all the current items from the queue into specified collection. + * Return whether the queue changed as a result. + */ + public boolean drainTo(Collection collection) { + synchronized (this.mutex) { + return this.drainTo_(collection); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTo_(Collection collection) { + if (this.queue.isEmpty()) { + return false; + } + return this.drainTo__(collection); + } + + /** + * Pre-condition: synchronized + * Assume the queue is not empty. + */ + private boolean drainTo__(Collection collection) { + do { + collection.add(this.queue.dequeue()); + } while ( ! this.queue.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the queue into specified list + * at the specified index. + * Return whether the queue changed as a result. + */ + public boolean drainTo(List list, int index) { + synchronized (this.mutex) { + return this.drainTo_(list, index); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTo_(List list, int index) { + if (this.queue.isEmpty()) { + return false; + } + if (index == list.size()) { + return this.drainTo__(list); + } + ArrayList temp = new ArrayList(); + this.drainTo__(temp); + list.addAll(index, temp); + return true; + } + + /** + * "Drain" all the current items from the queue into specified stack. + * Return whether the queue changed as a result. + */ + public boolean drainTo(Stack stack) { + synchronized (this.mutex) { + return this.drainTo_(stack); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTo_(Stack stack) { + if (this.queue.isEmpty()) { + return false; + } + do { + stack.push(this.queue.dequeue()); + } while ( ! this.queue.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the queue into specified queue. + * Return whether the queue changed as a result. + * @see #enqueueAll(Queue) + */ + public boolean drainTo(Queue q) { + synchronized (this.mutex) { + return this.drainTo_(q); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTo_(Queue q) { + if (this.queue.isEmpty()) { + return false; + } + do { + q.enqueue(this.queue.dequeue()); + } while ( ! this.queue.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the queue + * and add them on the specified map, using the specified key transformer + * to generate the key for each item. + * Return whether the queue changed as a result. + */ + public boolean drainTo(Map map, Transformer keyTransformer) { + synchronized (this.mutex) { + return this.drainTo_(map, keyTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTo_(Map map, Transformer keyTransformer) { + if (this.queue.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.queue.dequeue(), keyTransformer); + } while ( ! this.queue.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Drain" all the current items from the queue + * and add them on the specified map, using the specified key transformer + * to generate the key for each popped item and the specified value transformer + * to generator the value for each dequeued item. + * Return whether the queue changed as a result. + */ + public boolean drainTo(Map map, Transformer keyTransformer, Transformer valueTransformer) { + synchronized (this.mutex) { + return this.drainTo_(map, keyTransformer, valueTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean drainTo_(Map map, Transformer keyTransformer, Transformer valueTransformer) { + if (this.queue.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.queue.dequeue(), keyTransformer, valueTransformer); + } while ( ! this.queue.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * Return the object the queue locks on while performing + * its operations. + */ + public Object getMutex() { + return this.mutex; + } + + + // ********** standard methods ********** + + @Override + public String toString() { + synchronized (this.mutex) { + return this.queue.toString(); + } + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + synchronized (this.mutex) { + s.defaultWriteObject(); + } + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ArrayStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ArrayStack.java new file mode 100644 index 0000000000..ed5fe75d7b --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ArrayStack.java @@ -0,0 +1,164 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Resizable-array LIFO implementation of the {@link Stack} interface. + * @param the type of elements maintained by the stack + * @see FixedCapacityArrayStack + * @see StackTools + */ +public class ArrayStack + implements Stack, Cloneable, Serializable +{ + private transient E[] elements; + + private int size = 0; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty stack. + */ + public ArrayStack() { + this(10); + } + + /** + * Construct an empty stack with the specified initial capacity. + */ + @SuppressWarnings("unchecked") + public ArrayStack(int initialCapacity) { + super(); + if (initialCapacity < 0) { + throw new IllegalArgumentException("Illegal capacity: " + initialCapacity); //$NON-NLS-1$ + } + this.elements = (E[]) new Object[initialCapacity]; + } + + + // ********** Stack implementation ********** + + public void push(E element) { + this.ensureCapacity(this.size + 1); + this.elements[this.size++] = element; + } + + /** + * Increase the stack's capacity, if necessary, to ensure it has at least + * the specified minimum capacity. + */ + public void ensureCapacity(int minCapacity) { + if (this.elements.length < minCapacity) { + int newCapacity = ((this.elements.length * 3) >> 1) + 1; + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + this.elements = this.copyElements(newCapacity); + } + } + + /** + * Decrease the stack's capacity, if necessary, to match its current size. + */ + public void trimToSize() { + if (this.elements.length > this.size) { + this.elements = this.copyElements(this.size); + } + } + + private E[] copyElements(int newCapacity) { + @SuppressWarnings("unchecked") + E[] newElements = (E[]) new Object[newCapacity]; + if (this.size != 0) { + System.arraycopy(this.elements, 0, newElements, 0, this.size); + } + return newElements; + } + + public E pop() { + if (this.size == 0) { + throw new EmptyStackException(); + } + int index = this.size - 1; + E element = this.elements[index]; + this.elements[index] = null; // allow GC to work + this.size--; + return element; + } + + public E peek() { + if (this.size == 0) { + throw new EmptyStackException(); + } + return this.elements[this.size - 1]; + } + + public boolean isEmpty() { + return this.size == 0; + } + + + // ********** standard methods ********** + + @Override + public ArrayStack clone() { + try { + @SuppressWarnings("unchecked") + ArrayStack clone = (ArrayStack) super.clone(); + @SuppressWarnings("cast") + E[] array = (E[]) this.elements.clone(); + clone.elements = array; + return clone; + } catch (CloneNotSupportedException ex) { + throw new InternalError(); + } + } + + @Override + public String toString() { + return Arrays.toString(ArrayTools.reverse(this.copyElements(this.size))); + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write size (and any hidden stuff) + stream.defaultWriteObject(); + Object[] array = this.elements; + int elementsLength = array.length; + stream.writeInt(elementsLength); + for (int i = 0; i < this.size; i++) { + stream.writeObject(array[i]); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read size (and any hidden stuff) + stream.defaultReadObject(); + int elementsLength = stream.readInt(); + Object[] array = new Object[elementsLength]; + for (int i = 0; i < this.size; i++) { + array[i] = stream.readObject(); + } + this.elements = (E[]) array; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/DequeStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/DequeStack.java new file mode 100644 index 0000000000..20aaab9841 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/DequeStack.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.EmptyStackException; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Adapt a {@link Deque} to the {@link Stack} interface. + * Elements are pushed to and popped from the head of the deque. + * @param the type of elements maintained by the stack + * @see StackTools + */ +public class DequeStack + implements Stack, Serializable +{ + private Deque deque; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a stack, adapting the specified deque. + * Elements are pushed to and popped from the head of the deque. + */ + public DequeStack(Deque deque) { + super(); + this.deque = deque; + } + + + // ********** Stack implementation ********** + + public void push(E element) { + this.deque.enqueueHead(element); + } + + public E pop() { + try { + return this.deque.dequeueHead(); + } catch (NoSuchElementException ex) { + throw new EmptyStackException(); + } + } + + public E peek() { + try { + return this.deque.peekHead(); + } catch (NoSuchElementException ex) { + throw new EmptyStackException(); + } + } + + public boolean isEmpty() { + return this.deque.isEmpty(); + } + + + // ********** standard methods ********** + + @Override + public String toString() { + return this.deque.toString(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/EmptyStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/EmptyStack.java new file mode 100644 index 0000000000..cf18881346 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/EmptyStack.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2007, 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Empty implementation of the {@link Stack} interface. + * @param the type of elements maintained by the stack + * @see StackTools + */ +public final class EmptyStack + implements Stack, Serializable +{ + @SuppressWarnings("rawtypes") + public static final Stack INSTANCE = new EmptyStack(); + @SuppressWarnings("unchecked") + public static Stack instance() { + return INSTANCE; + } + + // ensure single instance + private EmptyStack() { + super(); + } + + public void push(E element) { + throw new UnsupportedOperationException(); + } + + public E pop() { + throw new EmptyStackException(); + } + + public E peek() { + throw new EmptyStackException(); + } + + public boolean isEmpty() { + return true; + } + + @Override + public String toString() { + return "[]"; //$NON-NLS-1$ + } + + private static final long serialVersionUID = 1L; + private Object readResolve() { + // replace this object with the singleton + return INSTANCE; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/FixedCapacityArrayStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/FixedCapacityArrayStack.java new file mode 100644 index 0000000000..44b55aba7f --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/FixedCapacityArrayStack.java @@ -0,0 +1,139 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Fixed-capacity array LIFO implementation of the {@link Stack} interface. + * This implementation will throw an exception if its capacity is exceeded. + * @param the type of elements maintained by the stack + * @see ArrayStack + * @see StackTools + */ +public class FixedCapacityArrayStack + implements Stack, Cloneable, Serializable +{ + private E[] elements; + + /** The index of where the next "pushed" element will go. */ + private int next = 0; + + private int size = 0; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty stack with the specified capacity. + */ + @SuppressWarnings("unchecked") + public FixedCapacityArrayStack(int capacity) { + super(); + if (capacity < 0) { + throw new IllegalArgumentException("Illegal capacity: " + capacity); //$NON-NLS-1$ + } + this.elements = (E[]) new Object[capacity]; + } + + + // ********** Stack implementation ********** + + public void push(E element) { + if (this.isFull()) { + throw new IllegalStateException("Stack is full."); //$NON-NLS-1$ + } + this.elements[this.next] = element; + if (++this.next == this.elements.length) { + this.next = 0; + } + this.size++; + } + + public E pop() { + if (this.size == 0) { + throw new EmptyStackException(); + } + int index = this.next; + if (index == 0) { + index = this.elements.length; + } + index--; + E element = this.elements[index]; + this.elements[index] = null; // allow GC to work + this.next = index; + this.size--; + return element; + } + + public E peek() { + if (this.size == 0) { + throw new EmptyStackException(); + } + int index = this.next; + if (index == 0) { + index = this.elements.length; + } + index--; + return this.elements[index]; + } + + public boolean isEmpty() { + return this.size == 0; + } + + /** + * Return whether the stack is full, + * as its capacity is fixed. + */ + public boolean isFull() { + return this.size == this.elements.length; + } + + + // ********** standard methods ********** + + @Override + public FixedCapacityArrayStack clone() { + int len = this.elements.length; + FixedCapacityArrayStack clone = new FixedCapacityArrayStack(len); + System.arraycopy(this.elements, 0, clone.elements, 0, len); + clone.next = this.next; + clone.size = this.size; + return clone; + } + + /** + * Print the elements in the order in which they are "pushed" on to + * the stack (as opposed to the order in which they will be "popped" + * off of the stack). + */ + @Override + public String toString() { + return Arrays.toString(ArrayTools.reverse(this.copyElements())); + } + + private Object[] copyElements() { + int len = this.size; + if (len == 0) { + return ObjectTools.EMPTY_OBJECT_ARRAY; + } + Object[] result = new Object[len]; + System.arraycopy(this.elements, 0, result, 0, len); + return result; + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/LinkedStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/LinkedStack.java new file mode 100644 index 0000000000..87aba7e2ae --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/LinkedStack.java @@ -0,0 +1,274 @@ +/******************************************************************************* + * Copyright (c) 2007, 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Linked LIFO implementation of the {@link Stack} interface. + * @param the type of elements maintained by the stack + * @see StackTools + */ +public class LinkedStack + implements Stack, Cloneable, Serializable +{ + private final NodeFactory nodeFactory; + private transient Node head; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct an empty stack with no node cache. + */ + public LinkedStack() { + this(0); + } + + /** + * Construct an empty stack with a node cache with the specified size. + * Specify a cache size of -1 for an unlimited cache. + */ + public LinkedStack(int cacheSize) { + this(LinkedStack.buildNodeFactory(cacheSize)); + this.head = null; + } + + private static NodeFactory buildNodeFactory(int cacheSize) { + if (cacheSize < -1) { + throw new IllegalArgumentException("Cache size must be greater than or equal to -1: " + cacheSize); //$NON-NLS-1$ + } + return (cacheSize == 0) ? SimpleNodeFactory.instance() : new CachingNodeFactory(cacheSize); + } + + private LinkedStack(NodeFactory nodeFactory) { + super(); + this.nodeFactory = nodeFactory; + this.head = null; + } + + + // ********** Stack implementation ********** + + public void push(E element) { + this.head = this.nodeFactory.buildNode(element, this.head); + } + + public E pop() { + if (this.head == null) { + throw new EmptyStackException(); + } + Node node = this.head; + this.head = node.next; + E element = node.element; + this.nodeFactory.release(node); + return element; + } + + public E peek() { + if (this.head == null) { + throw new EmptyStackException(); + } + return this.head.element; + } + + public boolean isEmpty() { + return this.head == null; + } + + + // ********** standard methods ********** + + @Override + public LinkedStack clone() { + LinkedStack clone = new LinkedStack(this.nodeFactory.copy()); + E[] elements = this.buildElements(); + for (int i = elements.length; i-- > 0; ) { + clone.push(elements[i]); + } + return clone; + } + + @SuppressWarnings("unchecked") + private E[] buildElements() { + int size = this.size(); + if (size == 0) { + return (E[]) ObjectTools.EMPTY_OBJECT_ARRAY; + } + E[] elements = (E[]) new Object[size]; + int i = 0; + for (Node node = this.head; node != null; node = node.next) { + elements[i++] = node.element; + } + return elements; + } + + private int size() { + int size = 0; + for (Node node = this.head; node != null; node = node.next) { + size++; + } + return size; + } + + @Override + public String toString() { + return Arrays.toString(this.buildElements()); + } + + + // ********** Serializable "implementation" ********** + + private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { + // write nodeFactory (and any hidden stuff) + stream.defaultWriteObject(); + Object[] elements = this.buildElements(); + int len = elements.length; + stream.writeInt(len); + // write elements in reverse order so they can be pushed as read + for (int i = len; i-- > 0; ) { + stream.writeObject(elements[i]); + } + } + + @SuppressWarnings("unchecked") + private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException, ClassNotFoundException { + // read nodeFactory (and any hidden stuff) + stream.defaultReadObject(); + int len = stream.readInt(); + for (int i = len; i-- > 0; ) { + this.push((E) stream.readObject()); + } + } + + + // ********** Node classes ********** + + private static final class Node { + E element; + Node next; + + Node(E element, Node next) { + super(); + this.element = element; + this.next = next; + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.element); + } + } + + private abstract static class NodeFactory { + NodeFactory() { + super(); + } + + Node buildNode(E element, Node next) { + return new Node(element, next); + } + + abstract void release(Node node); + + abstract NodeFactory copy(); + } + + private static class SimpleNodeFactory + extends NodeFactory + implements Serializable + { + @SuppressWarnings("rawtypes") + public static final NodeFactory INSTANCE = new SimpleNodeFactory(); + @SuppressWarnings("unchecked") + public static NodeFactory instance() { + return INSTANCE; + } + + private SimpleNodeFactory() { + super(); + } + + @Override + void release(Node node) { + // NOP + } + + @Override + NodeFactory copy() { + return this; + } + + @Override + public String toString() { + return ObjectTools.singletonToString(this); + } + + private static final long serialVersionUID = 1L; + private Object readResolve() { + // replace this object with the singleton + return INSTANCE; + } + } + + private static final class CachingNodeFactory + extends NodeFactory + implements Serializable + { + private final int maxCacheSize; + private transient int cacheSize = 0; + private transient Node cacheHead; + private static final long serialVersionUID = 1L; + + CachingNodeFactory(int maxCacheSize) { + super(); + this.maxCacheSize = maxCacheSize; + } + + @Override + Node buildNode(E element, Node next) { + if (this.cacheHead == null) { + return super.buildNode(element, next); + } + Node node = this.cacheHead; + this.cacheHead = node.next; + this.cacheSize--; + node.element = element; + node.next = next; + return node; + } + + @Override + void release(Node node) { + if ((this.maxCacheSize == -1) || (this.cacheSize < this.maxCacheSize)) { + node.element = null; // allow GC to work + node.next = this.cacheHead; + this.cacheHead = node; + this.cacheSize++; + } + } + + @Override + NodeFactory copy() { + return new CachingNodeFactory(this.maxCacheSize); + } + + @Override + public String toString() { + return ObjectTools.toString(this, this.cacheSize); + } + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ListStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ListStack.java new file mode 100644 index 0000000000..fd9c0c30af --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/ListStack.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (c) 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.EmptyStackException; +import java.util.List; +import org.eclipse.jpt.common.utility.internal.collection.ListTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Adapt a {@link List} to the {@link Stack} interface. + * Elements are popped from the end of the list (i.e. index size - 1). + * @param the type of elements maintained by the stack + * @see StackTools + */ +public class ListStack + implements Stack, Serializable +{ + private List list; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a stack, adapting the specified list. + * The stack will pop its elements in the reverse + * order they are returned by the list's iterator (i.e. the + * last element returned by the list's iterator will be the + * first element returned by {@link #pop()}). + */ + public ListStack(List list) { + super(); + this.list = list; + } + + + // ********** Stack implementation ********** + + public void push(E element) { + this.list.add(element); + } + + public E pop() { + int size = this.list.size(); + if (size == 0) { + throw new EmptyStackException(); + } + return this.list.remove(--size); + } + + public E peek() { + int size = this.list.size(); + if (size == 0) { + throw new EmptyStackException(); + } + return this.list.get(--size); + } + + public boolean isEmpty() { + return this.list.isEmpty(); + } + + + // ********** standard methods ********** + + @Override + public String toString() { + return ListTools.reverse(this.list).toString(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/StackTools.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/StackTools.java new file mode 100644 index 0000000000..40ddeb4df1 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/StackTools.java @@ -0,0 +1,447 @@ +/******************************************************************************* + * Copyright (c) 2013, 2015 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.internal.stack; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.collection.MapTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; + +/** + * {@link Stack} utility methods. + */ +public class StackTools { + + // ********** push all ********** + + /** + * Push all the elements returned by the specified iterable + * on the specified stack. + * Return whether the stack changed as a result. + */ + public static boolean pushAll(Stack stack, Iterable iterable) { + return pushAll(stack, iterable.iterator()); + } + + /** + * Push all the elements returned by the specified iterator + * on the specified stack. + * Return whether the stack changed as a result. + */ + public static boolean pushAll(Stack stack, Iterator iterator) { + return iterator.hasNext() && pushAll_(stack, iterator); + } + + /** + * assume the iterator is not empty + */ + private static boolean pushAll_(Stack stack, Iterator iterator) { + do { + stack.push(iterator.next()); + } while (iterator.hasNext()); + return true; + } + + /** + * Push all the elements in the specified array + * on the specified stack. + * Return whether the stack changed as a result. + */ + public static boolean pushAll(Stack stack, E... array) { + int len = array.length; + return (len != 0) && pushAll_(stack, array, len); + } + + /** + * assume the array is not empty + */ + private static boolean pushAll_(Stack stack, E[] array, int arrayLength) { + int i = 0; + do { + stack.push(array[i++]); + } while (i < arrayLength); + return true; + } + + + // ********** pop all ********** + + /** + * Pop all the elements from the specified stack and return them in a + * list. + */ + public static ArrayList popAll(Stack stack) { + ArrayList result = new ArrayList(); + popAllTo(stack, result); + return result; + } + + /** + * Pop all the elements from the specified stack and add them to the + * specified collection. + * Return whether the stack changed as a result. + */ + public static boolean popAllTo(Stack stack, Collection collection) { + return ( ! stack.isEmpty()) && popAllTo_(stack, collection); + } + + /** + * assume the stack is not empty + */ + private static boolean popAllTo_(Stack stack, Collection collection) { + do { + collection.add(stack.pop()); + } while ( ! stack.isEmpty()); + return true; + } + + /** + * Pop all the elements from the specified stack + * to the specified list at the specified index. + * Return whether the stack changed as a result. + */ + public static boolean popAllTo(Stack stack, List list, int index) { + return ( ! stack.isEmpty()) && popAllTo_(stack, list, index); + } + + /** + * assume the stack is not empty + */ + private static boolean popAllTo_(Stack stack, List list, int index) { + return (index == list.size()) ? popAllTo_(stack, list) : list.addAll(index, popAll(stack)); + } + + /** + * Pop all the elements from the specified stack and enqueue them on the + * specified queue. + * Return whether the stack changed as a result. + */ + public static boolean popAllTo(Stack stack, Queue queue) { + return ( ! stack.isEmpty()) && popAllTo_(stack, queue); + } + + /** + * assume the stack is not empty + */ + private static boolean popAllTo_(Stack stack, Queue queue) { + do { + queue.enqueue(stack.pop()); + } while ( ! stack.isEmpty()); + return true; + } + + /** + * Pop all the elements from the first specified stack and push them + * on the second specified stack. + * Return whether the first stack changed as a result. + */ + public static boolean popAllTo(Stack stack1, Stack stack2) { + return ( ! stack1.isEmpty()) && popAllTo_(stack1, stack2); + } + + /** + * assume stack 1 is not empty + */ + private static boolean popAllTo_(Stack stack1, Stack stack2) { + do { + stack2.push(stack1.pop()); + } while ( ! stack1.isEmpty()); + return true; + } + + /** + * Pop all the elements from the specified stack, passing each element to the + * specified key transformer. Map the generated key to its element. + * Return whether the stack changed as a result. + */ +// public static boolean popAllTo(Stack stack, Map map, Transformer keyTransformer) { + public static boolean popAllTo(Stack stack, Map map, Transformer keyTransformer) { + return ( ! stack.isEmpty()) && popAllTo_(stack, map, keyTransformer); + } + + /** + * assume the stack is not empty + */ + private static boolean popAllTo_(Stack stack, Map map, Transformer keyTransformer) { + do { + MapTools.add(map, stack.pop(), keyTransformer); + } while ( ! stack.isEmpty()); + return true; + } + + /** + * Pop all the elements from the specified stack, passing each element to the + * specified key and value transformers. Add the generated key/value pairs + * to the specified map. + * Return whether the stack changed as a result. + */ + public static boolean popAllTo(Stack stack, Map map, Transformer keyTransformer, Transformer valueTransformer) { + return ( ! stack.isEmpty()) && popAllTo_(stack, map, keyTransformer, valueTransformer); + } + + /** + * assume the stack is not empty + */ + private static boolean popAllTo_(Stack stack, Map map, Transformer keyTransformer, Transformer valueTransformer) { + do { + MapTools.add(map, stack.pop(), keyTransformer, valueTransformer); + } while ( ! stack.isEmpty()); + return true; + } + + + // ********** array stack factory methods ********** + + /** + * Return an array-based LIFO stack corresponding. + */ + public static ArrayStack arrayStack() { + return arrayStack(10); + } + + /** + * Return an array-based LIFO stack corresponding with the specified initial capacity. + */ + public static ArrayStack arrayStack(int initialCapacity) { + return new ArrayStack(initialCapacity); + } + + /** + * Return an array-based LIFO stack corresponding to the specified iterable. + * The stack will pop its elements in reverse of the + * order they are returned by the iterable's iterator (i.e. the + * last element returned by the iterable's iterator will be the + * first element returned by {@link Stack#pop()}; the first, last.). + */ + public static ArrayStack arrayStack(Iterable iterable) { + return arrayStack(iterable.iterator()); + } + + /** + * Return an array-based LIFO stack corresponding to the specified iterable. + * The stack will pop its elements in reverse of the + * order they are returned by the iterable's iterator (i.e. the + * last element returned by the iterable's iterator will be the + * first element returned by {@link Stack#pop()}; the first, last.). + * The specified iterable size is a performance hint. + */ + public static ArrayStack arrayStack(Iterable iterable, int iterableSize) { + return arrayStack(iterable.iterator(), iterableSize); + } + + /** + * Return an array-based LIFO stack corresponding to the specified iterator. + * The stack will pop its elements in reverse of the + * order they are returned by the iterator (i.e. the + * last element returned by the iterator will be the + * first element returned by {@link Stack#pop()}; the first, last.). + */ + public static ArrayStack arrayStack(Iterator iterator) { + ArrayStack result = StackTools.arrayStack(); + pushAll(result, iterator); + return result; + } + + /** + * Return an array-based LIFO stack corresponding to the specified iterator. + * The stack will pop its elements in reverse of the + * order they are returned by the iterator (i.e. the + * last element returned by the iterator will be the + * first element returned by {@link Stack#pop()}; the first, last.). + * The specified iterator size is a performance hint. + */ + public static ArrayStack arrayStack(Iterator iterator, int iteratorSize) { + ArrayStack result = StackTools.arrayStack(iteratorSize); + pushAll(result, iterator); + return result; + } + + /** + * Return an array-based LIFO stack corresponding to the specified array. + */ + public static ArrayStack arrayStack(E... array) { + ArrayStack result = StackTools.arrayStack(array.length); + pushAll(result, array); + return result; + } + + + // ********** linked stack factory methods ********** + + /** + * Return an empty link-based LIFO stack with no node cache. + */ + public static LinkedStack linkedStack() { + return linkedStack(0); + } + + /** + * Return an empty link-based LIFO stack + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedStack linkedStack(int cacheSize) { + return new LinkedStack(cacheSize); + } + + /** + * Return a link-based LIFO stack corresponding to the specified iterable. + */ + public static LinkedStack linkedStack(Iterable iterable) { + return linkedStack(iterable.iterator()); + } + + /** + * Return a link-based LIFO stack corresponding to the specified iterable + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedStack linkedStack(Iterable iterable, int cacheSize) { + return linkedStack(iterable.iterator(), cacheSize); + } + + /** + * Return a link-based LIFO stack corresponding to the specified iterator. + */ + public static LinkedStack linkedStack(Iterator iterator) { + LinkedStack result = StackTools.linkedStack(); + pushAll(result, iterator); + return result; + } + + /** + * Return a link-based LIFO stack corresponding to the specified iterator + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedStack linkedStack(Iterator iterator, int cacheSize) { + LinkedStack result = StackTools.linkedStack(cacheSize); + pushAll(result, iterator); + return result; + } + + /** + * Return a link-based LIFO stack corresponding to the specified array. + */ + public static LinkedStack linkedStack(E... array) { + LinkedStack result = StackTools.linkedStack(); + pushAll(result, array); + return result; + } + + /** + * Return a link-based LIFO stack corresponding to the specified array + * with the specified node cache size. + * Specify a cache size of -1 for an unlimited cache. + */ + public static LinkedStack linkedStack(E[] array, int cacheSize) { + LinkedStack result = StackTools.linkedStack(cacheSize); + pushAll(result, array); + return result; + } + + + // ********** fixed capacity stack factory methods ********** + + /** + * Return a fixed-capacity stack with the specified capacity. + */ + public static FixedCapacityArrayStack fixedCapacityArrayStack(int capacity) { + return new FixedCapacityArrayStack(capacity); + } + + /** + * Return a fized-capacity stack containing the elements of the specified + * collection. The stack will pop its elements in reverse of the + * order they are returned by the collection's iterator (i.e. the + * last element returned by the collection's iterator will be the + * first element returned by {@link Stack#pop()}; the first, last.). + */ + public static FixedCapacityArrayStack fixedCapacityArrayStack(Collection collection) { + FixedCapacityArrayStack result = StackTools.fixedCapacityArrayStack(collection.size()); + pushAll(result, collection); + return result; + } + + + // ********** synchronized stack factory methods ********** + + /** + * Return a synchronized stack. + */ + public static SynchronizedStack synchronizedStack() { + ArrayStack stack = arrayStack(); + return synchronizedStack(stack); + } + + /** + * Return a stack that synchronizes with specified mutex. + */ + public static SynchronizedStack synchronizedStack(Object mutex) { + LinkedStack stack = linkedStack(); + return synchronizedStack(stack, mutex); + } + + /** + * Return a stack that synchronizes the specified stack. + */ + public static SynchronizedStack synchronizedStack(Stack stack) { + return new SynchronizedStack(stack); + } + + /** + * Return a stack that synchronizes the specified stack + * with specified mutex. + */ + public static SynchronizedStack synchronizedStack(Stack stack, Object mutex) { + return new SynchronizedStack(stack, mutex); + } + + + // ********** misc stack factory methods ********** + + /** + * Adapt the specified list to the {@link Stack} interface. + */ + public static ListStack adapt(List list) { + return new ListStack(list); + } + + /** + * Adapt the specified deque to the {@link Stack} interface. + */ + public static DequeStack adapt(Deque deque) { + return new DequeStack(deque); + } + + /** + * Return an unmodifiable empty LIFO stack. + */ + public static Stack emptyStack() { + return EmptyStack.instance(); + } + + + // ********** constructor ********** + + /** + * Suppress default constructor, ensuring non-instantiability. + */ + private StackTools() { + super(); + throw new UnsupportedOperationException(); + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/SynchronizedStack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/SynchronizedStack.java new file mode 100644 index 0000000000..b8baf0e2f4 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/internal/stack/SynchronizedStack.java @@ -0,0 +1,604 @@ +/******************************************************************************* + * Copyright (c) 2007, 2015 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.internal.stack; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EmptyStackException; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.eclipse.jpt.common.utility.command.Command; +import org.eclipse.jpt.common.utility.internal.collection.MapTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; + +/** + * Thread-safe implementation of the {@link Stack} interface. + * This also provides protocol for suspending a thread until the + * stack is empty or not empty, with optional time-outs. + * @param the type of elements maintained by the stack + * @see StackTools + */ +public class SynchronizedStack + implements Stack, Serializable +{ + /** Backing stack. */ + private final Stack stack; + + /** Object to synchronize on. */ + private final Object mutex; + + private static final long serialVersionUID = 1L; + + + // ********** constructors ********** + + /** + * Construct a synchronized stack that wraps the + * specified stack and locks on the specified mutex. + */ + public SynchronizedStack(Stack stack, Object mutex) { + super(); + if ((stack == null) || (mutex == null)) { + throw new NullPointerException(); + } + this.stack = stack; + this.mutex = mutex; + } + + /** + * Construct a synchronized stack that wraps the + * specified stack and locks on itself. + */ + public SynchronizedStack(Stack stack) { + super(); + if (stack == null) { + throw new NullPointerException(); + } + this.stack = stack; + this.mutex = this; + } + + + // ********** Stack implementation ********** + + public void push(E element) { + synchronized (this.mutex) { + this.push_(element); + } + } + + /** + * Pre-condition: synchronized + */ + private void push_(E element) { + this.stack.push(element); + this.mutex.notifyAll(); + } + + public E pop() { + synchronized (this.mutex) { + return this.pop_(); + } + } + + /** + * Pre-condition: synchronized + */ + private E pop_() { + E o = this.stack.pop(); + this.mutex.notifyAll(); + return o; + } + + public E peek() { + synchronized (this.mutex) { + return this.stack.peek(); + } + } + + public boolean isEmpty() { + synchronized (this.mutex) { + return this.stack.isEmpty(); + } + } + + + // ********** indefinite waits ********** + + /** + * Suspend the current thread until the stack's empty status changes + * to the specified value. + */ + public void waitUntilEmptyIs(boolean empty) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(empty); + } + } + + /** + * Pre-condition: synchronized + */ + private void waitUntilEmptyIs_(boolean empty) throws InterruptedException { + while (this.stack.isEmpty() != empty) { + this.mutex.wait(); + } + } + + /** + * Suspend the current thread until the stack is empty. + */ + public void waitUntilEmpty() throws InterruptedException { + this.waitUntilEmptyIs(true); + } + + /** + * Suspend the current thread until the stack has something on it. + */ + public void waitUntilNotEmpty() throws InterruptedException { + this.waitUntilEmptyIs(false); + } + + /** + * Suspend the current thread until the stack is empty, + * then "push" the specified item on to the top of the stack + * and continue executing. + */ + public void waitToPush(E element) throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(true); + this.push_(element); + } + } + + /** + * Suspend the current thread until the stack has something on it, + * then "pop" an item from the top of the stack and return it. + */ + public Object waitToPop() throws InterruptedException { + synchronized (this.mutex) { + this.waitUntilEmptyIs_(false); + return this.pop_(); + } + } + + + // ********** timed waits ********** + + /** + * Suspend the current thread until the stack's empty status changes + * to the specified value or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if the specified + * empty status was achieved; return false if a time-out occurred. + * If the stack's empty status is already the specified value, + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilEmptyIs(boolean empty, long timeout) throws InterruptedException { + synchronized (this.mutex) { + return this.waitUntilEmptyIs_(empty, timeout); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean waitUntilEmptyIs_(boolean empty, long timeout) throws InterruptedException { + if (timeout == 0L) { + this.waitUntilEmptyIs_(empty); // wait indefinitely until notified + return true; // if it ever comes back, the condition was met + } + + long stop = System.currentTimeMillis() + timeout; + long remaining = timeout; + while ((this.stack.isEmpty() != empty) && (remaining > 0L)) { + this.mutex.wait(remaining); + remaining = stop - System.currentTimeMillis(); + } + return (this.stack.isEmpty() == empty); + } + + /** + * Suspend the current thread until the stack is empty + * or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if + * the stack is empty; return false if a time-out occurred. + * If the stack is already empty, return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilEmpty(long timeout) throws InterruptedException { + return this.waitUntilEmptyIs(true, timeout); + } + + /** + * Suspend the current thread until the stack has something on it. + * or the specified time-out occurs. + * The time-out is specified in milliseconds. Return true if + * the stack is not empty; return false if a time-out occurred. + * If the stack already has something on it, return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitUntilNotEmpty(long timeout) throws InterruptedException { + return this.waitUntilEmptyIs(false, timeout); + } + + /** + * Suspend the current thread until the stack is empty, + * then "push" the specified item on to the top of the stack + * and continue executing. If the stack is not emptied out + * before the time-out, simply continue executing without + * "pushing" the item. + * The time-out is specified in milliseconds. Return true if the + * item was pushed; return false if a time-out occurred. + * If the stack is already empty, "push" the specified item and + * return true immediately. + * If the time-out is zero, wait indefinitely. + */ + public boolean waitToPush(E element, long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(true, timeout); + if (success) { + this.push_(element); + } + return success; + } + } + + /** + * Suspend the current thread until the stack has something on it, + * then "pop" an item from the top of the stack and return it. + * If the stack is empty and nothing is "pushed" on to it before the + * time-out, throw an empty stack exception. + * The time-out is specified in milliseconds. + * If the stack is not empty, "pop" an item and + * return it immediately. + * If the time-out is zero, wait indefinitely. + */ + public Object waitToPop(long timeout) throws InterruptedException { + synchronized (this.mutex) { + boolean success = this.waitUntilEmptyIs_(false, timeout); + if (success) { + return this.pop_(); + } + throw new EmptyStackException(); + } + } + + + // ********** synchronized behavior ********** + + /** + * If the current thread is not interrupted, execute the specified command + * with the mutex locked. This is useful for initializing the stack in another + * thread. + */ + public void execute(Command command) throws InterruptedException { + if (Thread.currentThread().isInterrupted()) { + throw new InterruptedException(); + } + synchronized (this.mutex) { + command.execute(); + } + } + + + // ********** additional (synchronized) public protocol ********** + + /** + * "Push" all the elements returned by the specified iterable. + * Return whether the stack changed as a result. + */ + public boolean pushAll(Iterable iterable) { + return this.pushAll(iterable.iterator()); + } + + /** + * "Push" all the elements returned by the specified iterator. + * Return whether the stack changed as a result. + */ + public boolean pushAll(Iterator iterator) { + if ( ! iterator.hasNext()) { + return false; + } + synchronized (this.mutex) { + return this.pushAll_(iterator); + } + } + + /** + * Pre-condition: synchronized + * Assume the iterator is not empty. + */ + private boolean pushAll_(Iterator iterator) { + do { + this.stack.push(iterator.next()); + } while (iterator.hasNext()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Push" all the elements in the specified array. + * Return whether the stack changed as a result. + */ + public boolean pushAll(E... array) { + int len = array.length; + if (len == 0) { + return false; + } + synchronized (this.mutex) { + return this.pushAll_(array, len); + } + } + + /** + * Pre-condition: synchronized + * Assume the array is not empty. + */ + private boolean pushAll_(E[] array, int arrayLength) { + int i = 0; + do { + this.stack.push(array[i++]); + } while (i < arrayLength); + this.mutex.notifyAll(); + return true; + } + + /** + * "Pop" all the elements from the specified stack and "push" them. + * Return whether the stack changed as a result. + */ + public boolean pushAll(Stack s) { + if (s.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.pushAll_(s); + } + } + + /** + * Pre-condition: synchronized + * Assume the stack is not empty. + */ + private boolean pushAll_(Stack s) { + do { + this.stack.push(s.pop()); + } while ( ! s.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Dequeue" all the elements from the specified queue and + * "push" them. + * Return whether the stack changed as a result. + * @see #popAllTo(Queue) + */ + public boolean pushAll(Queue queue) { + if (queue.isEmpty()) { + return false; + } + synchronized (this.mutex) { + return this.pushAll_(queue); + } + } + + /** + * Pre-condition: synchronized + * Assume the queue is not empty. + */ + private boolean pushAll_(Queue queue) { + do { + this.stack.push(queue.dequeue()); + } while ( ! queue.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Pop" all the current items from the stack and return them in a list. + */ + public ArrayList popAll() { + ArrayList result = new ArrayList(); + this.popAllTo(result); + return result; + } + + /** + * "Pop" all the current items from the stack into specified collection. + * Return whether the stack changed as a result. + */ + public boolean popAllTo(Collection collection) { + synchronized (this.mutex) { + return this.popAllTo_(collection); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean popAllTo_(Collection collection) { + if (this.stack.isEmpty()) { + return false; + } + return this.popAllTo__(collection); + } + + /** + * Pre-condition: synchronized + * Assume the stack is not empty. + */ + private boolean popAllTo__(Collection collection) { + do { + collection.add(this.stack.pop()); + } while ( ! this.stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Pop" all the current items from the stack into specified list + * at the specified index. + * Return whether the stack changed as a result. + */ + public boolean popAllTo(List list, int index) { + synchronized (this.mutex) { + return this.popAllTo_(list, index); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean popAllTo_(List list, int index) { + if (this.stack.isEmpty()) { + return false; + } + if (index == list.size()) { + return this.popAllTo__(list); + } + ArrayList temp = new ArrayList(); + this.popAllTo__(temp); + list.addAll(index, temp); + return true; + } + + /** + * "Pop" all the current items from the stack + * and "push" them onto the specified stack. + * Return whether the stack changed as a result. + */ + public boolean popAllTo(Stack stack2) { + synchronized (this.mutex) { + return this.popAllTo_(stack2); + } + } + + /** + * Pre-condition: synchronized + */ + public boolean popAllTo_(Stack stack2) { + if (this.stack.isEmpty()) { + return false; + } + do { + stack2.push(this.stack.pop()); + } while ( ! this.stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Pop" all the current items from the stack + * and "enqueue" them on the specified queue. + * Return whether the stack changed as a result. + * @see #pushAll(Queue) + */ + public boolean popAllTo(Queue queue) { + synchronized (this.mutex) { + return this.popAllTo_(queue); + } + } + + /** + * Pre-condition: synchronized + */ + public boolean popAllTo_(Queue queue) { + if (this.stack.isEmpty()) { + return false; + } + do { + queue.enqueue(this.stack.pop()); + } while ( ! this.stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Pop" all the current items from the stack + * and add them on the specified map, using the specified key transformer + * to generate the key for each item. + * Return whether the stack changed as a result. + */ + public boolean popAllTo(Map map, Transformer keyTransformer) { + synchronized (this.mutex) { + return this.popAllTo_(map, keyTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean popAllTo_(Map map, Transformer keyTransformer) { + if (this.stack.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.stack.pop(), keyTransformer); + } while ( ! this.stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * "Pop" all the current items from the stack + * and add them on the specified map, using the specified key transformer + * to generate the key for each popped item and the specified value transformer + * to generator the value for each popped item. + * Return whether the stack changed as a result. + */ + public boolean popAllTo(Map map, Transformer keyTransformer, Transformer valueTransformer) { + synchronized (this.mutex) { + return this.popAllTo_(map, keyTransformer, valueTransformer); + } + } + + /** + * Pre-condition: synchronized + */ + private boolean popAllTo_(Map map, Transformer keyTransformer, Transformer valueTransformer) { + if (this.stack.isEmpty()) { + return false; + } + do { + MapTools.add(map, this.stack.pop(), keyTransformer, valueTransformer); + } while ( ! this.stack.isEmpty()); + this.mutex.notifyAll(); + return true; + } + + /** + * Return the object the stack locks on while performing + * its operations. + */ + public Object getMutex() { + return this.mutex; + } + + + // ********** standard methods ********** + + @Override + public String toString() { + synchronized (this.mutex) { + return this.stack.toString(); + } + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + synchronized (this.mutex) { + s.defaultWriteObject(); + } + } +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/queue/Queue.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/queue/Queue.java new file mode 100644 index 0000000000..2b04a58fa1 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/queue/Queue.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.queue; + +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.stack.Stack; + +/** + * Interface defining the classic queue behavior, + * without the backdoors allowed by {@link java.util.Queue}. + *

+ * Provisional API: This interface is part of an interim API that is still + * under development and expected to change significantly before reaching + * stability. It is available at this early stage to solicit feedback from + * pioneering adopters on the understanding that any code that uses this API + * will almost certainly be broken (repeatedly) as the API evolves. + * + * @param the type of elements contained by the queue + * @see org.eclipse.jpt.common.utility.internal.queue.ArrayQueue + * @see org.eclipse.jpt.common.utility.internal.queue.LinkedQueue + * @see org.eclipse.jpt.common.utility.internal.queue.QueueTools + * @see Deque Deque - for an interface without the semantic baggage of {@link java.util.Deque} + * @see Stack Stack - for an interface without the semantic baggage of {@link java.util.Stack} + */ +public interface Queue { + + /** + * "Enqueue" the specified item to the tail of the queue. + */ + void enqueue(E element); + + /** + * "Dequeue" an item from the head of the queue. + */ + E dequeue(); + + /** + * Return the item on the head of the queue + * without removing it from the queue. + */ + E peek(); + + /** + * Return whether the queue is empty. + */ + boolean isEmpty(); +} diff --git a/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/stack/Stack.java b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/stack/Stack.java new file mode 100644 index 0000000000..df382cc955 --- /dev/null +++ b/common/plugins/org.eclipse.jpt.common.utility/src/org/eclipse/jpt/common/utility/stack/Stack.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2007, 2015 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.stack; + +import org.eclipse.jpt.common.utility.queue.Queue; + +/** + * Interface defining the classic stack behavior, + * without the backdoors allowed by {@link java.util.Stack}. + *

+ * Provisional API: This interface is part of an interim API that is still + * under development and expected to change significantly before reaching + * stability. It is available at this early stage to solicit feedback from + * pioneering adopters on the understanding that any code that uses this API + * will almost certainly be broken (repeatedly) as the API evolves. + * + * @param the type of elements contained by the stack + * @see org.eclipse.jpt.common.utility.internal.stack.ArrayStack + * @see org.eclipse.jpt.common.utility.internal.stack.LinkedStack + * @see org.eclipse.jpt.common.utility.internal.stack.StackTools + * @see Queue Queue - for an interface without the semantic baggage of {@link java.util.Queue} + */ +public interface Stack { + + /** + * "Push" the specified item on to the top of the stack. + */ + void push(E element); + + /** + * "Pop" an item from the top of the stack. + */ + E pop(); + + /** + * Return the item on the top of the stack + * without removing it from the stack. + */ + E peek(); + + /** + * Return whether the stack is empty. + */ + boolean isEmpty(); +} diff --git a/common/tests/org.eclipse.jpt.common.core.tests/src/org/eclipse/jpt/common/core/tests/internal/utility/jdt/ASTToolsTests.java b/common/tests/org.eclipse.jpt.common.core.tests/src/org/eclipse/jpt/common/core/tests/internal/utility/jdt/ASTToolsTests.java index df1c3a16ba..69ac508837 100644 --- a/common/tests/org.eclipse.jpt.common.core.tests/src/org/eclipse/jpt/common/core/tests/internal/utility/jdt/ASTToolsTests.java +++ b/common/tests/org.eclipse.jpt.common.core.tests/src/org/eclipse/jpt/common/core/tests/internal/utility/jdt/ASTToolsTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2013 Oracle. All rights reserved. + * Copyright (c) 2006, 2015 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. @@ -134,8 +134,8 @@ public class ASTToolsTests Iterable actual = ASTTools.resolveFullyQualifiedNames(daea.getExpression(field.getModifiedDeclaration(this.buildASTRoot(cu)))); assertEquals( - ListTools.list(new String[] {fqOtherClassName, fqOtherClassName2}), - ListTools.list(actual)); + ListTools.arrayList(new String[] {fqOtherClassName, fqOtherClassName2}), + ListTools.arrayList(actual)); } public void testResolveFullyQualifiedNames2() throws Exception { @@ -162,8 +162,8 @@ public class ASTToolsTests Iterable actual = ASTTools.resolveFullyQualifiedNames(daea.getExpression(field.getModifiedDeclaration(this.buildASTRoot(cu)))); assertEquals( - ListTools.list(new String[] {null, fqOtherClassName}), - ListTools.list(actual)); + ListTools.arrayList(new String[] {null, fqOtherClassName}), + ListTools.arrayList(actual)); } public void testResolveFullyQualifiedNames3() throws Exception { @@ -190,7 +190,7 @@ public class ASTToolsTests Iterable actual = ASTTools.resolveFullyQualifiedNames(daea.getExpression(field.getModifiedDeclaration(this.buildASTRoot(cu)))); assertEquals( - ListTools.list(new String[] {null, fqOtherClassName}), - ListTools.list(actual)); + ListTools.arrayList(new String[] {null, fqOtherClassName}), + ListTools.arrayList(actual)); } } diff --git a/common/tests/org.eclipse.jpt.common.ui.tests/src/org/eclipse/jpt/common/ui/tests/internal/jface/TreeContentProviderUiTest.java b/common/tests/org.eclipse.jpt.common.ui.tests/src/org/eclipse/jpt/common/ui/tests/internal/jface/TreeContentProviderUiTest.java index 6e95ea0f73..5c349e0515 100644 --- a/common/tests/org.eclipse.jpt.common.ui.tests/src/org/eclipse/jpt/common/ui/tests/internal/jface/TreeContentProviderUiTest.java +++ b/common/tests/org.eclipse.jpt.common.ui.tests/src/org/eclipse/jpt/common/ui/tests/internal/jface/TreeContentProviderUiTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -376,7 +376,7 @@ public class TreeContentProviderUiTest public CollectionValueModel transform(TreeNode value) { return (value instanceof Nest) ? this.transform((Nest) value) : - new StaticCollectionValueModel(CollectionTools.collection(value)); + new StaticCollectionValueModel(CollectionTools.hashBag(value)); } private CollectionValueModel transform(Nest nest) { 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 index 34edf4821c..28e0f2a141 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -9,11 +9,10 @@ ******************************************************************************/ package org.eclipse.jpt.common.utility.tests.internal; -import junit.framework.Test; -import junit.framework.TestSuite; import org.eclipse.jpt.common.utility.tests.internal.collection.JptCommonUtilityCollectionTests; import org.eclipse.jpt.common.utility.tests.internal.command.JptCommonUtilityCommandTests; import org.eclipse.jpt.common.utility.tests.internal.comparator.JptCommonUtilityComparatorTests; +import org.eclipse.jpt.common.utility.tests.internal.deque.JptCommonUtilityDequeTests; import org.eclipse.jpt.common.utility.tests.internal.enumeration.JptCommonUtilityEnumerationTests; import org.eclipse.jpt.common.utility.tests.internal.exception.JptCommonUtilityExceptionTests; import org.eclipse.jpt.common.utility.tests.internal.factory.JptCommonUtilityFactoryTests; @@ -24,8 +23,12 @@ import org.eclipse.jpt.common.utility.tests.internal.jdbc.JptCommonUtilityJDBCTe import org.eclipse.jpt.common.utility.tests.internal.model.JptCommonUtilityModelTests; import org.eclipse.jpt.common.utility.tests.internal.node.JptCommonUtilityNodeTests; import org.eclipse.jpt.common.utility.tests.internal.predicate.JptCommonUtilityPredicateTests; +import org.eclipse.jpt.common.utility.tests.internal.queue.JptCommonUtilityQueueTests; import org.eclipse.jpt.common.utility.tests.internal.reference.JptCommonUtilityReferenceTests; +import org.eclipse.jpt.common.utility.tests.internal.stack.JptCommonUtilityStackTests; import org.eclipse.jpt.common.utility.tests.internal.transformer.JptCommonUtilityTransformerTests; +import junit.framework.Test; +import junit.framework.TestSuite; /** * decentralize test creation code @@ -38,6 +41,7 @@ public class JptCommonUtilityTests { suite.addTest(JptCommonUtilityCollectionTests.suite()); suite.addTest(JptCommonUtilityCommandTests.suite()); suite.addTest(JptCommonUtilityComparatorTests.suite()); + suite.addTest(JptCommonUtilityDequeTests.suite()); suite.addTest(JptCommonUtilityEnumerationTests.suite()); suite.addTest(JptCommonUtilityExceptionTests.suite()); suite.addTest(JptCommonUtilityFactoryTests.suite()); @@ -48,7 +52,9 @@ public class JptCommonUtilityTests { suite.addTest(JptCommonUtilityModelTests.suite()); suite.addTest(JptCommonUtilityNodeTests.suite()); suite.addTest(JptCommonUtilityPredicateTests.suite()); + suite.addTest(JptCommonUtilityQueueTests.suite()); suite.addTest(JptCommonUtilityReferenceTests.suite()); + suite.addTest(JptCommonUtilityStackTests.suite()); suite.addTest(JptCommonUtilityTransformerTests.suite()); suite.addTestSuite(ArrayToolsTests.class); diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/AbstractRepeatingElementListTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/AbstractRepeatingElementListTests.java index 6c8c23dc1b..4170eb8497 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/AbstractRepeatingElementListTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/AbstractRepeatingElementListTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -70,7 +70,7 @@ public abstract class AbstractRepeatingElementListTests boolean exCaught = false; try { - list.addAll(CollectionTools.collection("foo", "bar")); + list.addAll(CollectionTools.hashBag("foo", "bar")); fail("bogus list: " + list); } catch (UnsupportedOperationException ex) { exCaught = true; @@ -84,7 +84,7 @@ public abstract class AbstractRepeatingElementListTests boolean exCaught = false; try { - list.addAll(1, CollectionTools.collection("foo", "bar")); + list.addAll(1, CollectionTools.hashBag("foo", "bar")); fail("bogus list: " + list); } catch (UnsupportedOperationException ex) { exCaught = true; @@ -168,6 +168,9 @@ public abstract class AbstractRepeatingElementListTests List list = this.buildList(3); assertEquals(0, list.indexOf(this.getElement())); assertEquals(-1, list.indexOf(new Object())); + + list = this.buildList(0); + assertEquals(-1, list.indexOf(this.getElement())); } public void testIsEmpty() { @@ -207,6 +210,10 @@ public abstract class AbstractRepeatingElementListTests List list = this.buildList(3); assertEquals(2, list.lastIndexOf(this.getElement())); assertEquals(-1, list.lastIndexOf(new Object())); + + list = this.buildList(0); + assertEquals(-1, list.indexOf(this.getElement())); + assertEquals(-1, list.lastIndexOf(new Object())); } public void testListIterator() { @@ -474,6 +481,19 @@ public abstract class AbstractRepeatingElementListTests assertNull(array[20]); } + public void testToString() { + List list1 = this.buildList(3); + List list2 = new ArrayList(); + list2.add(this.getElement()); + list2.add(this.getElement()); + list2.add(this.getElement()); + assertEquals(list2.toString(), list1.toString()); + + list1 = this.buildList(0); + list2 = new ArrayList(); + assertEquals(list2.toString(), list1.toString()); + } + public abstract List buildList(int size); public abstract String getElement(); diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayQueueTests.java deleted file mode 100644 index a6066d594f..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayQueueTests.java +++ /dev/null @@ -1,192 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2015 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.collection; - -import java.util.ArrayList; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.collection.ArrayQueue; -import org.eclipse.jpt.common.utility.internal.collection.QueueTools; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ArrayQueueTests - extends QueueTests -{ - public ArrayQueueTests(String name) { - super(name); - } - - @Override - Queue buildQueue() { - return new ArrayQueue(); - } - - public void testCollectionConstructor() { - ArrayList c = new ArrayList(); - c.add("first"); - c.add("second"); - c.add("third"); - c.add("fourth"); - c.add("fifth"); - c.add("sixth"); - c.add("seventh"); - c.add("eighth"); - c.add("ninth"); - c.add("tenth"); // force some free space - Queue queue = QueueTools.arrayQueue(c); - - assertFalse(queue.isEmpty()); - assertEquals("first", queue.peek()); - queue.enqueue("eleventh"); - queue.enqueue("twelfth"); - - assertEquals("first", queue.peek()); - assertEquals("first", queue.dequeue()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.peek()); - assertEquals("third", queue.dequeue()); - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertEquals("eleventh", queue.dequeue()); - assertEquals("twelfth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testWrappedElements() { - Queue queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - - // make room for 11 and 12 - assertEquals("first", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.dequeue()); - - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - queue.enqueue("eleventh"); - queue.enqueue("twelfth"); - - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertEquals("eleventh", queue.dequeue()); - assertEquals("twelfth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testArrayCapacityExceeded() { - Queue queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - queue.enqueue("eleventh"); - queue.enqueue("twelfth"); - - assertEquals("first", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.dequeue()); - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertEquals("eleventh", queue.dequeue()); - assertEquals("twelfth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testArrayCapacityExceededWithWrappedElements() { - Queue queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - - assertEquals("first", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.dequeue()); - - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - queue.enqueue("eleventh"); - queue.enqueue("twelfth"); - queue.enqueue("thirteenth"); - queue.enqueue("fourteenth"); - queue.enqueue("fifteenth"); - - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertEquals("eleventh", queue.dequeue()); - assertEquals("twelfth", queue.dequeue()); - assertEquals("thirteenth", queue.dequeue()); - assertEquals("fourteenth", queue.dequeue()); - assertEquals("fifteenth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testSerialization_fullArray() throws Exception { - Queue queue = new ArrayQueue(3); - queue.enqueue("first"); - queue.enqueue("second"); - queue.enqueue("third"); - - this.verifyClone(queue, TestTools.serialize(queue)); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayStackTests.java deleted file mode 100644 index 10b863caa9..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ArrayStackTests.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2015 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.collection; - -import java.util.ArrayList; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.collection.ArrayStack; -import org.eclipse.jpt.common.utility.internal.collection.StackTools; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class ArrayStackTests - extends StackTests -{ - public ArrayStackTests(String name) { - super(name); - } - - @Override - Stack buildStack() { - return new ArrayStack(); - } - - public void testCollectionConstructor() { - ArrayList c = new ArrayList(); - c.add("first"); - c.add("second"); - c.add("third"); - c.add("fourth"); - c.add("fifth"); - c.add("sixth"); - c.add("seventh"); - c.add("eighth"); - c.add("ninth"); - c.add("tenth"); // force some free space - Stack stack = StackTools.arrayStack(c); - - assertFalse(stack.isEmpty()); - assertEquals("tenth", stack.peek()); - stack.push("eleventh"); - stack.push("twelfth"); - - assertEquals("twelfth", stack.peek()); - assertEquals("twelfth", stack.pop()); - assertEquals("eleventh", stack.pop()); - assertEquals("tenth", stack.peek()); - assertEquals("tenth", stack.pop()); - assertEquals("ninth", stack.pop()); - assertFalse(stack.isEmpty()); - assertEquals("eighth", stack.peek()); - assertEquals("eighth", stack.pop()); - assertEquals("seventh", stack.pop()); - assertEquals("sixth", stack.pop()); - assertEquals("fifth", stack.pop()); - assertEquals("fourth", stack.pop()); - assertEquals("third", stack.pop()); - assertEquals("second", stack.pop()); - assertEquals("first", stack.pop()); - assertTrue(stack.isEmpty()); - } - - public void testSerialization_fullArray() throws Exception { - Stack stack = new ArrayStack(3); - stack.push("first"); - stack.push("second"); - stack.push("third"); - - this.verifyClone(stack, TestTools.serialize(stack)); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/BagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/BagTests.java index 8f72babc00..42682e35dd 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/BagTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/BagTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -9,76 +9,813 @@ ******************************************************************************/ package org.eclipse.jpt.common.utility.tests.internal.collection; -import junit.framework.TestCase; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NoSuchElementException; import org.eclipse.jpt.common.utility.collection.Bag; -import org.eclipse.jpt.common.utility.internal.collection.EmptyBag; -import org.eclipse.jpt.common.utility.internal.collection.HashBag; +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; import org.eclipse.jpt.common.utility.tests.internal.TestTools; +//subclass MultiThreadedTestCase for subclasses of this class @SuppressWarnings("nls") -public class BagTests extends TestCase { +public abstract class BagTests + extends MultiThreadedTestCase +{ + private Bag bag; - public BagTests(String name) { + protected BagTests(String name) { super(name); } - public void testEmptyBag_iterator() throws Exception { - assertFalse(EmptyBag.instance().iterator().hasNext()); + @Override + protected void setUp() throws Exception { + super.setUp(); + this.bag = this.buildBag(); + } + + protected Bag buildBag() { + Bag b = this.buildBag_(); + 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; + } + + protected abstract Bag buildBag_(); + + protected abstract Bag buildBag(Collection c); + + protected abstract Bag buildBag(int initialCapacity, float loadFactor); + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + private Collection buildCollection() { + Collection c = new ArrayList(); + 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 testEmptyBag_size() throws Exception { - assertEquals(0, EmptyBag.instance().size()); + public void testCtorCollection() { + Collection c = this.buildCollection(); + Bag b = this.buildBag(c); + for (String s : c) { + assertTrue(b.contains(s)); + } + } + + public void testCtorIntFloat() { + boolean exCaught; + + exCaught = false; + try { + this.bag = this.buildBag(-20, 0.66f); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + + exCaught = false; + try { + this.bag = this.buildBag(20, -0.66f); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); } - public void testEmptyBag_uniqueIterator() throws Exception { - assertFalse(EmptyBag.instance().uniqueIterator().hasNext()); + 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 testEmptyBag_uniqueCount() throws Exception { - assertEquals(0, EmptyBag.instance().uniqueCount()); + 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 testEmptyBag_count() throws Exception { - assertEquals(0, EmptyBag.instance().count("foo")); + public void testAddAll() { + Collection c = this.buildCollection(); + assertTrue(this.bag.addAll(c)); + for (String s : c) { + assertTrue(this.bag.contains(s)); + } } - public void testEmptyBag_entries() throws Exception { - assertFalse(EmptyBag.instance().entries().hasNext()); + 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 testEmptyBag_remove() throws Exception { - assertFalse(EmptyBag.instance().remove("foo", 3)); + public void testClone() { + @SuppressWarnings("unchecked") + Bag bag2 = (Bag) ObjectTools.execute(this.bag, "clone"); + assertTrue(this.bag != bag2); + assertEquals(this.bag, bag2); + assertTrue(this.bag.hashCode() == bag2.hashCode()); } - public void testEmptyBag_add() throws Exception { + 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 c = new ArrayList(); + 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 testEqualsObject() { + Bag bag2 = this.buildBag(); + assertEquals(this.bag, this.bag); + assertEquals(this.bag, bag2); + + bag2.add("four"); + assertFalse(this.bag.equals(bag2)); // same unique counts; different sizes + bag2.remove("four"); + + bag2.add("five"); + bag2.remove("four"); + assertFalse(this.bag.equals(bag2)); // same sizes; different unique counts + bag2.remove("five"); + bag2.add("four"); + + bag2.remove("two"); + bag2.add("four"); + assertFalse(this.bag.equals(bag2)); // same sizes; same unique counts + + Collection c = new ArrayList(this.bag); + assertFalse(this.bag.equals(c)); + } + + public void testHashCode() { + Bag 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 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 { - EmptyBag.instance().add("foo", 3); - fail(); - } catch (UnsupportedOperationException ex) { + iterator.remove(); + } catch (IllegalStateException ex) { exCaught = true; } assertTrue(exCaught); } - public void testEmptyBag_equals() throws Exception { - assertTrue(EmptyBag.instance().equals(EmptyBag.instance())); - assertFalse(EmptyBag.instance().equals("foo")); + public void testIterator() { + int i = 0; + Iterator iterator = this.bag.iterator(); + assertTrue(iterator.hasNext()); + while (iterator.hasNext()) { + iterator.next(); + i++; + } + assertEquals(11, i); + assertFalse(iterator.hasNext()); - Bag bag = new HashBag(); - assertTrue(EmptyBag.instance().equals(bag)); - bag.add("foo"); - assertFalse(EmptyBag.instance().equals(bag)); + 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 testIterator_remove_all() { + assertEquals(4, this.bag.count("four")); + Iterator iterator = this.bag.iterator(); + String next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if ((next != null) && next.equals("four")) { + iterator.remove(); + } + } + assertEquals(0, this.bag.count("four")); + } + + public void testIterator_remove_CME() { + Iterator iterator = this.bag.iterator(); + assertTrue(iterator.hasNext()); + boolean exCaught = false; + try { + String next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.equals("four")) { + this.bag.remove("two"); + iterator.remove(); + } + } + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyUniqueIterator() { + this.bag.clear(); + Iterator iterator = this.bag.uniqueIterator(); + 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 testEmptyBag_hashCode() throws Exception { - assertEquals(0, EmptyBag.instance().hashCode()); + public void testUniqueIterator() { + int i = 0; + Iterator 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 testEmptyBag_serialization() throws Exception { - Bag xxx = TestTools.serialize(EmptyBag.instance()); - assertSame(EmptyBag.instance(), xxx); + public void testEmptyEntries() { + this.bag.clear(); + Iterator> iterator = this.bag.entries(); + 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 testEntries() { + int i = 0; + Iterator> 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 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 testEntries_remove_CME() { + Iterator> iterator = this.bag.entries(); + assertTrue(iterator.hasNext()); + boolean exCaught = false; + try { + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + this.bag.remove("two"); + iterator.remove(); + } + } + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEntry_setCount_increase() { + Iterator> iterator = this.bag.entries(); + assertEquals(4, this.bag.count("four")); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + assertEquals(4, next.setCount(42)); + break; + } + } + assertEquals(42, this.bag.count("four")); + assertEquals(49, this.bag.size()); + } + + public void testEntry_setCount_same() { + Iterator> iterator = this.bag.entries(); + assertEquals(4, this.bag.count("four")); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + assertEquals(4, next.setCount(4)); + break; + } + } + assertEquals(4, this.bag.count("four")); + assertEquals(11, this.bag.size()); + } + + public void testEntry_setCount_derease() { + Iterator> iterator = this.bag.entries(); + assertEquals(4, this.bag.count("four")); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + assertEquals(4, next.setCount(2)); + break; + } + } + assertEquals(2, this.bag.count("four")); + assertEquals(9, this.bag.size()); + } + + public void testEntry_setCount_IAE1() { + Iterator> iterator = this.bag.entries(); + boolean exCaught = false; + try { + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + next.setCount(0); + fail(next.toString()); + } + } + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEntry_setCount_IAE2() { + Iterator> iterator = this.bag.entries(); + boolean exCaught = false; + try { + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + next.setCount(-33); + fail(next.toString()); + } + } + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + @SuppressWarnings("null") + public void testEntry_equalsObject() { + Iterator> iterator1 = this.bag.entries(); + Bag bag2 = this.buildBag(); + Bag.Entry next1 = null; + while (iterator1.hasNext()) { + next1 = iterator1.next(); + if (next1.getElement().equals("four")) { + break; + } + } + assertFalse(next1.equals("four")); + Iterator> iterator2 = bag2.entries(); + Bag.Entry next2 = null; + while (iterator2.hasNext()) { + next2 = iterator2.next(); + if (next2.getElement().equals("four")) { + break; + } + } + assertEquals(next1, next2); + + bag2.remove("four"); + iterator1 = this.bag.entries(); + while (iterator1.hasNext()) { + next1 = iterator1.next(); + if (next1.getElement().equals("four")) { + break; + } + } + iterator2 = bag2.entries(); + while (iterator2.hasNext()) { + next2 = iterator2.next(); + if (next2.getElement().equals("four")) { + break; + } + } + assertEquals(next1.getElement(), next2.getElement()); + assertFalse(next1.equals(next2)); + + iterator1 = this.bag.entries(); + while (iterator1.hasNext()) { + next1 = iterator1.next(); + if (next1.getElement().equals("three")) { + break; + } + } + assertEquals(next1.getCount(), next2.getCount()); + assertFalse(next1.equals(next2)); + } + + @SuppressWarnings("null") + public void testEntry_hashCode() { + Iterator> iterator = this.bag.entries(); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + break; + } + } + assertEquals(4 * "four".hashCode(), next.hashCode()); + + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement() == null) { + break; + } + } + assertEquals(0, next.hashCode()); + } + + @SuppressWarnings("null") + public void testEntry_toString() { + Iterator> iterator = this.bag.entries(); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals("four")) { + break; + } + } + assertEquals("four=>4", next.toString()); + } + + 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 c = new ArrayList(); + 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 c = new ArrayList(); + 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 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 testSerialization_empty() throws Exception { + this.bag.clear(); + Bag bag2 = TestTools.serialize(this.bag); + + assertTrue("same object?", this.bag != bag2); + assertEquals(0, bag2.size()); + assertEquals(this.bag, bag2); + } + + 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/collection/CollectionToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/CollectionToolsTests.java index d198057575..a9f30d140a 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/CollectionToolsTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/CollectionToolsTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -20,17 +20,18 @@ 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.collection.Bag; import org.eclipse.jpt.common.utility.internal.ClassTools; import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; -import org.eclipse.jpt.common.utility.internal.collection.EmptyBag; +import org.eclipse.jpt.common.utility.internal.collection.IdentityHashBag; +import org.eclipse.jpt.common.utility.internal.collection.SynchronizedBag; import org.eclipse.jpt.common.utility.internal.comparator.ComparatorTools; import org.eclipse.jpt.common.utility.internal.iterable.EmptyIterable; import org.eclipse.jpt.common.utility.internal.iterator.EmptyIterator; import org.eclipse.jpt.common.utility.internal.iterator.IteratorTools; import org.eclipse.jpt.common.utility.internal.predicate.PredicateTools; import org.eclipse.jpt.common.utility.tests.internal.ArrayToolsTests; +import junit.framework.TestCase; @SuppressWarnings("nls") public class CollectionToolsTests @@ -164,7 +165,7 @@ public class CollectionToolsTests String[] a = this.buildStringArray1(); assertTrue(CollectionTools.addAll(list, a)); assertEquals(6, list.size()); - assertTrue(list.containsAll(CollectionTools.collection(a))); + assertTrue(list.containsAll(CollectionTools.hashBag(a))); } public void testAddAllCollectionObjectArray_StringListEmptyArray() { @@ -177,7 +178,7 @@ public class CollectionToolsTests String[] a = this.buildStringArray1(); assertFalse(CollectionTools.addAll(set, a)); assertEquals(3, set.size()); - assertTrue(set.containsAll(CollectionTools.collection(a))); + assertTrue(set.containsAll(CollectionTools.hashBag(a))); assertFalse(CollectionTools.addAll(set, new String[0])); } @@ -193,7 +194,7 @@ public class CollectionToolsTests assertTrue(CollectionTools.addAll(list, a)); assertEquals(6, list.size()); - assertTrue(list.containsAll(CollectionTools.collection(a))); + assertTrue(list.containsAll(CollectionTools.hashBag(a))); } public void testAddAllCollectionObjectArray_ObjectUnmodified() { @@ -201,118 +202,81 @@ public class CollectionToolsTests Set set = this.buildObjectSet1(); assertFalse(CollectionTools.addAll(set, a)); assertEquals(3, set.size()); - assertTrue(set.containsAll(CollectionTools.collection(a))); - } - - - // ********** bag ********** - - public void testBagIterable() { - Iterable iterable = this.buildStringList1(); - Bag b = CollectionTools.bag(iterable); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); + assertTrue(set.containsAll(CollectionTools.hashBag(a))); } - public void testBagIterableInt() { - Iterable iterable = this.buildStringList1(); - Bag b = CollectionTools.bag(iterable, 3); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } - public void testBagIterator_String() { - Bag b = CollectionTools.bag(this.buildStringList1().iterator()); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } + // ********** hash bag ********** - public void testBagIterator_StringObject() { - Collection c = new ArrayList(); - c.add("zero"); - c.add("one"); - c.add("two"); - c.add("three"); - Bag b = CollectionTools.bag(c.iterator()); - assertEquals(4, b.size()); - assertTrue(b.containsAll(c)); - } - - public void testBagIterator_Empty() { - Bag b = CollectionTools.bag(EmptyIterator.instance()); - assertEquals(0, b.size()); - } - - public void testBagIteratorInt() { - Bag b = CollectionTools.bag(this.buildStringList1().iterator(), 3); - assertEquals(3, b.size()); - assertTrue(b.containsAll(this.buildStringList1())); - } - - public void testBagIteratorInt_Empty() { - Bag b = CollectionTools.bag(EmptyIterator.instance(), 3); - assertEquals(0, b.size()); - } - - public void testBagObjectArray() { - Bag b = CollectionTools.bag(this.buildStringArray1()); - assertEquals(3, b.size()); - assertTrue(CollectionTools.containsAll(b, (Object[]) this.buildStringArray1())); - } - - public void testBagObjectArray_Vararg() { - Bag b = CollectionTools.bag("foo", "bar", "baz"); - assertEquals(3, b.size()); - assertTrue(CollectionTools.containsAll(b, new Object[]{"foo", "bar", "baz"})); - } - - public void testBagObjectArray_Empty() { - Bag b = CollectionTools.bag(EmptyBag.instance()); - assertEquals(0, b.size()); + public void testHashBagIntFloat() { + Collection c = CollectionTools.hashBag(42, 0.88f); + assertEquals(0, c.size()); + assertTrue(c.isEmpty()); } - - // ********** collection ********** - - public void testCollectionIterable() { + public void testHashBagIterable() { Iterable iterable = this.buildStringList1(); - Collection c = CollectionTools.collection(iterable); + Collection c = CollectionTools.hashBag(iterable); assertEquals(3, c.size()); assertTrue(c.containsAll(this.buildStringList1())); } - public void testCollectionIterableInt() { + public void testHashBagIterableInt() { Iterable iterable = this.buildStringList1(); - Collection c = CollectionTools.collection(iterable, 3); + Collection c = CollectionTools.hashBag(iterable, 3); assertEquals(3, c.size()); assertTrue(c.containsAll(this.buildStringList1())); } - public void testCollectionIterator() { - Collection c = CollectionTools.collection(this.buildStringList1().iterator()); + public void testHashBagIterator() { + Collection c = CollectionTools.hashBag(this.buildStringList1().iterator()); assertEquals(3, c.size()); assertTrue(c.containsAll(this.buildStringList1())); } - public void testCollectionIterator_ObjectString() { - Collection c = CollectionTools.collection(this.buildStringList1().iterator()); + public void testHashBagIterator_ObjectString() { + Collection c = CollectionTools.hashBag(this.buildStringList1().iterator()); assertEquals(3, c.size()); assertTrue(c.containsAll(this.buildStringList1())); } - public void testCollectionIteratorInt() { - Collection c = CollectionTools.collection(this.buildStringList1().iterator(), 3); + public void testHashBagIteratorInt() { + Collection c = CollectionTools.hashBag(this.buildStringList1().iterator(), 3); assertEquals(3, c.size()); assertTrue(c.containsAll(this.buildStringList1())); } - public void testCollectionObjectArray() { - Collection c = CollectionTools.collection(this.buildStringArray1()); + public void testHashBagObjectArray() { + Collection c = CollectionTools.hashBag(this.buildStringArray1()); assertEquals(3, c.size()); assertTrue(CollectionTools.containsAll(c, (Object[]) this.buildStringArray1())); } + // ********** synchronized bag ********** + + public void testSynchronizedBagObject() { + Object mutex = "foo"; + SynchronizedBag sBag = CollectionTools.synchronizedBag(mutex); + assertEquals(mutex, sBag.getMutex()); + } + + public void testSynchronizedBagBagObject() { + Bag bag = CollectionTools.hashBag(); + Object mutex = "foo"; + SynchronizedBag sBag = CollectionTools.synchronizedBag(bag, mutex); + assertEquals(mutex, sBag.getMutex()); + } + + + // ********** identity hash bag ********** + + public void testIdentityHashBagIntFloat() { + IdentityHashBag bag = CollectionTools.identityHashBag(42, 0.88f); + assertTrue(bag.isEmpty()); + } + + // ********** contains all ********** public void testContainsAllCollectionIterable() { @@ -348,22 +312,50 @@ public class CollectionToolsTests // ********** filter ********** public void testFilterCollectionFilter() { - Collection c = CollectionTools.collection(new String[] { "zero", "one", "two", "three", "four" }); + Collection c = CollectionTools.hashBag(new String[] { "zero", "one", "two", "three", "four" }); Collection actual = CollectionTools.filter(c, new ArrayToolsTests.StringLengthEquals(3)); - Collection expected = CollectionTools.collection(new String[] { "one", "two" }); + Collection expected = CollectionTools.hashBag(new String[] { "one", "two" }); assertEquals(expected, actual); } public void testFilterCollectionFilterTransparent() { - Collection c = CollectionTools.collection(new String[] { "zero", "one", "two", "three", "four" }); + Collection c = CollectionTools.hashBag(new String[] { "zero", "one", "two", "three", "four" }); Collection actual = CollectionTools.filter(c, PredicateTools.true_()); - Collection expected = CollectionTools.collection(new String[] { "zero", "one", "two", "three", "four" }); + Collection expected = CollectionTools.hashBag(new String[] { "zero", "one", "two", "three", "four" }); assertEquals(expected, actual); assertNotSame(expected, actual); } + // ********** identity bag ********** + + // tested in IdentityHashBagTests + // ********** partition ********** + public void testPartitionCollectionInt_negative() { + this.verifyPartitionCollectionException(-3); + } + + public void testPartitionCollectionInt_0() { + this.verifyPartitionCollectionException(0); + } + + public void testPartitionCollectionInt_tooMany() { + this.verifyPartitionCollectionException(6); + } + + public void verifyPartitionCollectionException(int count) { + Collection c = Arrays.asList(new String[] { "zero", "one", "two", "three", "four" }); + boolean exCaught = false; + try { + ArrayList> actual = CollectionTools.partition(c, count); + fail("bogus partition: " + actual); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + public void testPartitionCollectionInt_1() { Collection c = Arrays.asList(new String[] { "zero", "one", "two", "three", "four" }); ArrayList> actual = CollectionTools.partition(c, 1); @@ -792,6 +784,18 @@ public class CollectionToolsTests } + // ********** to array fix ********** + + public void testToArrayCollectionClass() { + List list = Arrays.asList(new String[] { "zero", "one", "two" }); + String[] actual = CollectionTools.toArray(list, String.class); + assertEquals(3, actual.length); + assertEquals("zero", actual[0]); + assertEquals("one", actual[1]); + assertEquals("two", actual[2]); + } + + // ********** transform ********** public void testTransformCollectionTransformer() { @@ -804,23 +808,23 @@ public class CollectionToolsTests } - // ********** set ********** + // ********** hash set ********** - public void testSetIterable() { + public void testHashSetIterable() { Iterable iterable = this.buildStringSet1(); - assertEquals(this.buildStringSet1(), CollectionTools.set(iterable)); + assertEquals(this.buildStringSet1(), CollectionTools.hashSet(iterable)); } - public void testSetIterableInt() { + public void testHashSetIterableInt() { Iterable iterable = this.buildStringSet1(); - assertEquals(this.buildStringSet1(), CollectionTools.set(iterable, 22)); + assertEquals(this.buildStringSet1(), CollectionTools.hashSet(iterable, 22)); } - public void testSetIterator_String() { - assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().iterator())); + public void testHashSetIterator_String() { + assertEquals(this.buildStringSet1(), CollectionTools.hashSet(this.buildStringSet1().iterator())); } - public void testSetIterator_Object() { + public void testHashSetIterator_Object() { List list = new ArrayList(); list.add("0"); list.add("1"); @@ -833,21 +837,21 @@ public class CollectionToolsTests Set set = new HashSet(); set.addAll(list); - assertEquals(set, CollectionTools.set(list.iterator())); + assertEquals(set, CollectionTools.hashSet(list.iterator())); } - public void testSetIteratorInt() { - assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().iterator(), 3)); + public void testHashSetIteratorInt() { + assertEquals(this.buildStringSet1(), CollectionTools.hashSet(this.buildStringSet1().iterator(), 3)); } - public void testSetObjectArray() { - assertEquals(this.buildStringSet1(), CollectionTools.set(this.buildStringSet1().toArray())); + public void testHashSetObjectArray() { + assertEquals(this.buildStringSet1(), CollectionTools.hashSet(this.buildStringSet1().toArray())); } - // ********** sorted set ********** + // ********** tree set ********** - public void testSortedSetIterable() { + public void testTreeSetIterable() { ArrayList list = new ArrayList(); list.add("0"); list.add("2"); @@ -858,11 +862,11 @@ public class CollectionToolsTests ss1.addAll(list); Iterable iterable = list; - SortedSet ss2 = CollectionTools.sortedSet(iterable); + SortedSet ss2 = CollectionTools.treeSet(iterable); assertEquals(ss1, ss2); } - public void testSortedSetIterableInt() { + public void testTreeSetIterableInt() { ArrayList list = new ArrayList(); list.add("0"); list.add("2"); @@ -873,11 +877,11 @@ public class CollectionToolsTests ss1.addAll(list); Iterable iterable = list; - SortedSet ss2 = CollectionTools.sortedSet(iterable, 5); + SortedSet ss2 = CollectionTools.treeSet(iterable, 5); assertEquals(ss1, ss2); } - public void testSortedSetIterableComparator() { + public void testTreeSetIterableComparator() { ArrayList list = new ArrayList(); list.add("0"); list.add("2"); @@ -888,11 +892,11 @@ public class CollectionToolsTests ss1.addAll(list); Iterable iterable = list; - SortedSet ss2 = CollectionTools.sortedSet(iterable, ComparatorTools.reverseComparator()); + SortedSet ss2 = CollectionTools.treeSet(iterable, ComparatorTools.reverseComparator()); assertEquals(ss1, ss2); } - public void testSortedSetIterableComparatorInt() { + public void testTreeSetIterableComparatorInt() { ArrayList list = new ArrayList(); list.add("0"); list.add("2"); @@ -903,34 +907,34 @@ public class CollectionToolsTests ss1.addAll(list); Iterable iterable = list; - SortedSet ss2 = CollectionTools.sortedSet(iterable, ComparatorTools.reverseComparator(), 5); + SortedSet ss2 = CollectionTools.treeSet(iterable, ComparatorTools.reverseComparator(), 5); assertEquals(ss1, ss2); } - public void testSortedSetIterator() { - assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildSortedStringSet1().iterator())); + public void testTreeSetIterator() { + assertEquals(this.buildSortedStringSet1(), CollectionTools.treeSet(this.buildSortedStringSet1().iterator())); } - public void testSortedSetIterator_TreeSet() { + public void testTreeSetIterator_TreeSet() { SortedSet ss1 = new TreeSet(); ss1.add("0"); ss1.add("2"); ss1.add("3"); ss1.add("1"); - SortedSet set2 = CollectionTools.sortedSet(ss1.iterator()); + SortedSet set2 = CollectionTools.treeSet(ss1.iterator()); assertEquals(ss1, set2); } - public void testSortedSetIteratorInt() { - assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildSortedStringSet1().iterator(), 8)); + public void testTreeSetIteratorInt() { + assertEquals(this.buildSortedStringSet1(), CollectionTools.treeSet(this.buildSortedStringSet1().iterator(), 8)); } - public void testSortedSetObjectArray() { - assertEquals(this.buildSortedStringSet1(), CollectionTools.sortedSet(this.buildStringSet1().toArray(new String[0]))); + public void testTreeSetObjectArray() { + assertEquals(this.buildSortedStringSet1(), CollectionTools.treeSet(this.buildStringSet1().toArray(new String[0]))); } - public void testSortedSetObjectArrayComparator() { + public void testTreeSetObjectArrayComparator() { ArrayList list = new ArrayList(); list.add("0"); list.add("2"); @@ -941,11 +945,12 @@ public class CollectionToolsTests ss1.addAll(list); String[] array = list.toArray(new String[list.size()]); - SortedSet ss2 = CollectionTools.sortedSet(array, ComparatorTools.reverseComparator()); + SortedSet ss2 = CollectionTools.treeSet(array, ComparatorTools.reverseComparator()); assertEquals(ss1, ss2); } + // ********** Old School Vector ********** public void testVectorIterable() { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/EmptyBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/EmptyBagTests.java new file mode 100644 index 0000000000..685e1a3839 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/EmptyBagTests.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2010, 2015 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.collection; + +import org.eclipse.jpt.common.utility.collection.Bag; +import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; +import org.eclipse.jpt.common.utility.internal.collection.HashBag; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class EmptyBagTests + extends TestCase +{ + public EmptyBagTests(String name) { + super(name); + } + + public void testEmptyBag_iterator() throws Exception { + assertFalse(CollectionTools.emptyBag().iterator().hasNext()); + } + + public void testEmptyBag_size() throws Exception { + assertEquals(0, CollectionTools.emptyBag().size()); + } + + public void testEmptyBag_uniqueIterator() throws Exception { + assertFalse(CollectionTools.emptyBag().uniqueIterator().hasNext()); + } + + public void testEmptyBag_uniqueCount() throws Exception { + assertEquals(0, CollectionTools.emptyBag().uniqueCount()); + } + + public void testEmptyBag_count() throws Exception { + assertEquals(0, CollectionTools.emptyBag().count("foo")); + } + + public void testEmptyBag_entries() throws Exception { + assertFalse(CollectionTools.emptyBag().entries().hasNext()); + } + + public void testEmptyBag_remove() throws Exception { + assertFalse(CollectionTools.emptyBag().remove("foo", 3)); + } + + public void testEmptyBag_add() throws Exception { + boolean exCaught = false; + try { + CollectionTools.emptyBag().add("foo", 3); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyBag_equals() throws Exception { + assertTrue(CollectionTools.emptyBag().equals(CollectionTools.emptyBag())); + assertFalse(CollectionTools.emptyBag().equals("foo")); + + Bag bag = new HashBag(); + assertTrue(CollectionTools.emptyBag().equals(bag)); + bag.add("foo"); + assertFalse(CollectionTools.emptyBag().equals(bag)); + } + + public void testEmptyBag_hashCode() throws Exception { + assertEquals(0, CollectionTools.emptyBag().hashCode()); + } + + public void testEmptyBag_serialization() throws Exception { + Bag xxx = TestTools.serialize(CollectionTools.emptyBag()); + assertSame(CollectionTools.emptyBag(), xxx); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayQueueTests.java deleted file mode 100644 index e1f0bfa5dc..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayQueueTests.java +++ /dev/null @@ -1,216 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.collection; - -import java.util.ArrayList; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.collection.FixedSizeArrayQueue; -import org.eclipse.jpt.common.utility.internal.collection.QueueTools; - -@SuppressWarnings("nls") -public class FixedSizeArrayQueueTests - extends QueueTests -{ - public FixedSizeArrayQueueTests(String name) { - super(name); - } - - @Override - FixedSizeArrayQueue buildQueue() { - return new FixedSizeArrayQueue(10); - } - - public void testCollectionConstructor() { - ArrayList c = new ArrayList(); - c.add("first"); - c.add("second"); - c.add("third"); - c.add("fourth"); - c.add("fifth"); - c.add("sixth"); - c.add("seventh"); - c.add("eighth"); - c.add("ninth"); - c.add("tenth"); - Queue queue = QueueTools.fixedSizeQueue(c); - - assertFalse(queue.isEmpty()); - assertEquals("first", queue.peek()); - assertEquals("first", queue.dequeue()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.peek()); - assertEquals("third", queue.dequeue()); - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testIsFull() { - FixedSizeArrayQueue queue = this.buildQueue(); - assertFalse(queue.isFull()); - queue.enqueue("first"); - assertFalse(queue.isFull()); - queue.enqueue("second"); - assertFalse(queue.isFull()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - assertTrue(queue.isFull()); - - queue.dequeue(); - assertFalse(queue.isEmpty()); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - assertFalse(queue.isFull()); - } - - public void testWrappedElements() { - Queue queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - - // make room for 11 and 12 - assertEquals("first", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.dequeue()); - - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - queue.enqueue("eleventh"); - queue.enqueue("twelfth"); - - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertEquals("eleventh", queue.dequeue()); - assertEquals("twelfth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testArrayCapacityExceeded() { - Queue queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - - boolean exCaught = false; - try { - queue.enqueue("eleventh"); - fail("bogus"); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - assertEquals("first", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.dequeue()); - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } - - public void testArrayCapacityExceededWithWrappedElements() { - Queue queue = this.buildQueue(); - assertTrue(queue.isEmpty()); - queue.enqueue("first"); - assertFalse(queue.isEmpty()); - queue.enqueue("second"); - assertFalse(queue.isEmpty()); - queue.enqueue("third"); - queue.enqueue("fourth"); - queue.enqueue("fifth"); - queue.enqueue("sixth"); - - assertEquals("first", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("second", queue.dequeue()); - assertFalse(queue.isEmpty()); - assertEquals("third", queue.dequeue()); - - queue.enqueue("seventh"); - queue.enqueue("eighth"); - queue.enqueue("ninth"); - queue.enqueue("tenth"); - queue.enqueue("eleventh"); - queue.enqueue("twelfth"); - queue.enqueue("thirteenth"); - - boolean exCaught = false; - try { - queue.enqueue("fourteenth"); - fail("bogus"); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - - assertEquals("fourth", queue.dequeue()); - assertEquals("fifth", queue.dequeue()); - assertEquals("sixth", queue.dequeue()); - assertEquals("seventh", queue.dequeue()); - assertEquals("eighth", queue.dequeue()); - assertEquals("ninth", queue.dequeue()); - assertEquals("tenth", queue.dequeue()); - assertEquals("eleventh", queue.dequeue()); - assertEquals("twelfth", queue.dequeue()); - assertEquals("thirteenth", queue.dequeue()); - assertTrue(queue.isEmpty()); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayStackTests.java deleted file mode 100644 index 53ba45f1ea..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/FixedSizeArrayStackTests.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.collection; - -import java.util.ArrayList; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.collection.FixedSizeArrayStack; -import org.eclipse.jpt.common.utility.internal.collection.StackTools; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -@SuppressWarnings("nls") -public class FixedSizeArrayStackTests - extends StackTests -{ - public FixedSizeArrayStackTests(String name) { - super(name); - } - - @Override - FixedSizeArrayStack buildStack() { - return new FixedSizeArrayStack(10); - } - - public void testCollectionConstructor() { - ArrayList c = new ArrayList(); - c.add("first"); - c.add("second"); - c.add("third"); - c.add("fourth"); - c.add("fifth"); - c.add("sixth"); - c.add("seventh"); - c.add("eighth"); - c.add("ninth"); - c.add("tenth"); - Stack stack = StackTools.fixedSizeStack(c); - - assertFalse(stack.isEmpty()); - assertEquals("tenth", stack.peek()); - assertEquals("tenth", stack.pop()); - assertEquals("ninth", stack.pop()); - assertFalse(stack.isEmpty()); - assertEquals("eighth", stack.peek()); - assertEquals("eighth", stack.pop()); - assertEquals("seventh", stack.pop()); - assertEquals("sixth", stack.pop()); - assertEquals("fifth", stack.pop()); - assertEquals("fourth", stack.pop()); - assertEquals("third", stack.pop()); - assertEquals("second", stack.pop()); - assertEquals("first", stack.pop()); - assertTrue(stack.isEmpty()); - } - - public void testIsFull() { - FixedSizeArrayStack stack = this.buildStack(); - assertFalse(stack.isFull()); - stack.push("first"); - assertFalse(stack.isFull()); - stack.push("second"); - assertFalse(stack.isFull()); - stack.push("third"); - stack.push("fourth"); - stack.push("fifth"); - stack.push("sixth"); - stack.push("seventh"); - stack.push("eighth"); - stack.push("ninth"); - stack.push("tenth"); - assertTrue(stack.isFull()); - - stack.pop(); - assertFalse(stack.isEmpty()); - stack.pop(); - stack.pop(); - stack.pop(); - stack.pop(); - stack.pop(); - stack.pop(); - stack.pop(); - assertFalse(stack.isFull()); - } - - public void testArrayCapacityExceeded() { - Stack stack = this.buildStack(); - assertTrue(stack.isEmpty()); - stack.push("first"); - assertFalse(stack.isEmpty()); - stack.push("second"); - assertFalse(stack.isEmpty()); - stack.push("third"); - stack.push("fourth"); - stack.push("fifth"); - stack.push("sixth"); - stack.push("seventh"); - stack.push("eighth"); - stack.push("ninth"); - stack.push("tenth"); - - boolean exCaught = false; - try { - stack.push("eleventh"); - fail("bogus"); - } catch (IllegalStateException ex) { - exCaught = true; - } - assertTrue(exCaught); - - assertFalse(stack.isEmpty()); - assertEquals("tenth", stack.peek()); - assertEquals("tenth", stack.pop()); - assertEquals("ninth", stack.pop()); - assertFalse(stack.isEmpty()); - assertEquals("eighth", stack.peek()); - assertEquals("eighth", stack.pop()); - assertEquals("seventh", stack.pop()); - assertEquals("sixth", stack.pop()); - assertEquals("fifth", stack.pop()); - assertEquals("fourth", stack.pop()); - assertEquals("third", stack.pop()); - assertEquals("second", stack.pop()); - assertEquals("first", stack.pop()); - assertTrue(stack.isEmpty()); - } - - public void testSerialization_fullArray() throws Exception { - Stack stack = new FixedSizeArrayStack(3); - stack.push("first"); - stack.push("second"); - stack.push("third"); - - this.verifyClone(stack, TestTools.serialize(stack)); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/HashBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/HashBagTests.java index a03d98e267..a17bfa72b0 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/HashBagTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/HashBagTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -9,379 +9,37 @@ ******************************************************************************/ package org.eclipse.jpt.common.utility.tests.internal.collection; -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.collection.Bag; -import org.eclipse.jpt.common.utility.internal.ArrayTools; import org.eclipse.jpt.common.utility.internal.SystemTools; import org.eclipse.jpt.common.utility.internal.collection.HashBag; import org.eclipse.jpt.common.utility.tests.internal.TestTools; @SuppressWarnings("nls") -public class HashBagTests extends TestCase { - private HashBag bag; - +public class HashBagTests + extends BagTests +{ public HashBagTests(String name) { super(name); } @Override - protected void setUp() throws Exception { - super.setUp(); - this.bag = this.buildBag(); - } - - private HashBag buildBag() { - HashBag b = new HashBag(); - 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; + protected Bag buildBag_() { + return new HashBag(); } @Override - protected void tearDown() throws Exception { - TestTools.clear(this); - super.tearDown(); - } - - private Collection buildCollection() { - Collection c = new ArrayList(); - 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 c = this.buildCollection(); - Bag b = new HashBag(c); - for (String s : c) { - assertTrue(b.contains(s)); - } - } - - public void testCtorIntFloat() { - boolean exCaught; - - exCaught = false; - try { - this.bag = new HashBag(-20, 0.66f); - } catch (IllegalArgumentException ex) { - exCaught = true; - } - assertTrue(exCaught); - - exCaught = false; - try { - this.bag = new HashBag(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 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 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 c = new ArrayList(); - 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 bag2 = this.buildBag(); - assertEquals(this.bag, bag2); - bag2.add("five"); - assertFalse(this.bag.equals(bag2)); - Collection c = new ArrayList(this.bag); - assertFalse(this.bag.equals(c)); - } - - public void testHashCode() { - Bag 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 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 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 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); + protected Bag buildBag(Collection c) { + return new HashBag(c); } - public void testEntries() { - int i = 0; - Iterator> 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 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); + @Override + protected Bag buildBag(int initialCapacity, float loadFactor) { + return new HashBag(initialCapacity, loadFactor); } public void testHashingDistribution() throws Exception { - Bag bigBag = new HashBag(); + Bag bigBag = this.buildBag(); for (int i = 0; i < 10000; i++) { bigBag.add("object" + i); } @@ -408,149 +66,4 @@ public class HashBagTests extends TestCase { } } } - - 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 c = new ArrayList(); - 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 c = new ArrayList(); - 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 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/collection/IdentityHashBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashBagTests.java index 23aa0f14d5..1fb037c1e4 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashBagTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashBagTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -14,17 +14,19 @@ 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.collection.Bag; import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.StringTools; import org.eclipse.jpt.common.utility.internal.SystemTools; import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; import org.eclipse.jpt.common.utility.internal.collection.IdentityHashBag; import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; @SuppressWarnings("nls") -public class IdentityHashBagTests extends TestCase { +public class IdentityHashBagTests + extends TestCase +{ private IdentityHashBag bag; private String one = "one"; private String two = "two"; @@ -44,19 +46,23 @@ public class IdentityHashBagTests extends TestCase { } protected IdentityHashBag buildBag() { - IdentityHashBag result = new IdentityHashBag(); - 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; + return CollectionTools.identityHashBag(this.buildBagContents()); + } + + protected Collection buildBagContents() { + ArrayList c = new ArrayList(); + c.add(null); + c.add(this.one); + c.add(this.two); + c.add(this.two); + c.add(this.three); + c.add(this.three); + c.add(this.three); + c.add(this.four); + c.add(this.four); + c.add(this.four); + c.add(this.four); + return c; } @Override @@ -199,17 +205,32 @@ public class IdentityHashBagTests extends TestCase { assertEquals(0, this.bag.count("five")); } - public void testEquals() { - IdentityHashBag bag2 = this.buildBag(); + public void testEqualsObject() { + assertEquals(this.bag, this.bag); + IdentityHashBag bag2 = CollectionTools.identityHashBag(this.buildBagContents(), 20); assertEquals(this.bag, bag2); - bag2.add("five"); - assertFalse(this.bag.equals(bag2)); + + bag2.add(this.four); + assertFalse(this.bag.equals(bag2)); // same unique counts; different sizes + bag2.remove(this.four); + + String five = "five"; + bag2.add(five); + bag2.remove(this.four); + assertFalse(this.bag.equals(bag2)); // same sizes; different unique counts + bag2.remove(five); + bag2.add(this.four); + + bag2.remove(this.two); + bag2.add(this.four); + assertFalse(this.bag.equals(bag2)); // same sizes; same unique counts + Collection c = new ArrayList(this.bag); assertFalse(this.bag.equals(c)); } public void testHashCode() { - IdentityHashBag bag2 = this.buildBag(); + IdentityHashBag bag2 = CollectionTools.identityHashBag(this.buildBagContents().toArray(StringTools.EMPTY_STRING_ARRAY)); assertEquals(this.bag.hashCode(), bag2.hashCode()); } @@ -287,6 +308,30 @@ public class IdentityHashBagTests extends TestCase { assertTrue("ConcurrentModificationException not thrown", exCaught); } + public void testEmptyUniqueIterator() { + this.bag.clear(); + Iterator iterator = this.bag.uniqueIterator(); + 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 testUniqueIterator() { int i = 0; Iterator iterator = this.bag.uniqueIterator(); @@ -338,6 +383,30 @@ public class IdentityHashBagTests extends TestCase { assertTrue(exCaught); } + public void testEmptyEntries() { + this.bag.clear(); + Iterator> iterator = this.bag.entries(); + 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 testEntries() { int i = 0; Iterator> iterator = this.bag.entries(); @@ -392,6 +461,25 @@ public class IdentityHashBagTests extends TestCase { assertTrue(exCaught); } + public void testEntries_remove_CME() { + Iterator> iterator = this.bag.entries(); + assertTrue(iterator.hasNext()); + boolean exCaught = false; + try { + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + this.bag.remove(this.two); + iterator.remove(); + } + } + } catch (ConcurrentModificationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + public void testHashingDistribution() throws Exception { IdentityHashBag bigBag = new IdentityHashBag(); for (int i = 0; i < 10000; i++) { @@ -501,13 +589,13 @@ public class IdentityHashBagTests extends TestCase { assertTrue("same object?", this.bag != bag2); assertEquals(11, bag2.size()); - assertEquals(CollectionTools.bag(this.bag.iterator()), CollectionTools.bag(bag2.iterator())); + assertEquals(CollectionTools.hashBag(this.bag.iterator()), CollectionTools.hashBag(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")); + assertTrue(CollectionTools.hashBag(bag2.iterator()).contains(null)); + assertTrue(CollectionTools.hashBag(bag2.iterator()).contains("one")); + assertTrue(CollectionTools.hashBag(bag2.iterator()).contains("two")); + assertTrue(CollectionTools.hashBag(bag2.iterator()).contains("three")); + assertTrue(CollectionTools.hashBag(bag2.iterator()).contains("four")); int nullCount = 0, oneCount = 0, twoCount = 0, threeCount = 0, fourCount = 0; for (String next : bag2) { @@ -528,6 +616,15 @@ public class IdentityHashBagTests extends TestCase { assertEquals(3, threeCount); assertEquals(4, fourCount); } + + public void testSerialization_empty() throws Exception { + this.bag.clear(); + Bag bag2 = TestTools.serialize(this.bag); + + assertTrue("same object?", this.bag != bag2); + assertEquals(0, bag2.size()); + assertEquals(this.bag, bag2); + } public void testToArray() { Object[] a = this.bag.toArray(); @@ -571,4 +668,169 @@ public class IdentityHashBagTests extends TestCase { assertTrue(s.indexOf("null") != -1); } + public void testEntry_setCount_increase() { + Iterator> iterator = this.bag.entries(); + assertEquals(4, this.bag.count(this.four)); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + assertEquals(4, next.setCount(42)); + break; + } + } + assertEquals(42, this.bag.count(this.four)); + assertEquals(49, this.bag.size()); + } + + public void testEntry_setCount_same() { + Iterator> iterator = this.bag.entries(); + assertEquals(4, this.bag.count(this.four)); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + assertEquals(4, next.setCount(4)); + break; + } + } + assertEquals(4, this.bag.count(this.four)); + assertEquals(11, this.bag.size()); + } + + public void testEntry_setCount_derease() { + Iterator> iterator = this.bag.entries(); + assertEquals(4, this.bag.count(this.four)); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + assertEquals(4, next.setCount(2)); + break; + } + } + assertEquals(2, this.bag.count(this.four)); + assertEquals(9, this.bag.size()); + } + + public void testEntry_setCount_IAE1() { + Iterator> iterator = this.bag.entries(); + boolean exCaught = false; + try { + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + next.setCount(0); + fail(next.toString()); + } + } + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEntry_setCount_IAE2() { + Iterator> iterator = this.bag.entries(); + boolean exCaught = false; + try { + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + next.setCount(-33); + fail(next.toString()); + } + } + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + @SuppressWarnings("null") + public void testEntry_equalsObject() { + Iterator> iterator1 = this.bag.entries(); + Bag bag2 = this.buildBag(); + Bag.Entry next1 = null; + while (iterator1.hasNext()) { + next1 = iterator1.next(); + if (next1.getElement().equals(this.four)) { + break; + } + } + assertFalse(next1.equals(this.four)); + Iterator> iterator2 = bag2.entries(); + Bag.Entry next2 = null; + while (iterator2.hasNext()) { + next2 = iterator2.next(); + if (next2.getElement().equals(this.four)) { + break; + } + } + assertEquals(next1, next2); + + bag2.remove(this.four); + iterator1 = this.bag.entries(); + while (iterator1.hasNext()) { + next1 = iterator1.next(); + if (next1.getElement().equals(this.four)) { + break; + } + } + iterator2 = bag2.entries(); + while (iterator2.hasNext()) { + next2 = iterator2.next(); + if (next2.getElement().equals(this.four)) { + break; + } + } + assertEquals(next1.getElement(), next2.getElement()); + assertFalse(next1.equals(next2)); + + iterator1 = this.bag.entries(); + while (iterator1.hasNext()) { + next1 = iterator1.next(); + if (next1.getElement().equals(this.three)) { + break; + } + } + assertEquals(next1.getCount(), next2.getCount()); + assertFalse(next1.equals(next2)); + } + + @SuppressWarnings("null") + public void testEntry_hashCode() { + Iterator> iterator = this.bag.entries(); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + break; + } + } + assertEquals(4 * this.four.hashCode(), next.hashCode()); + + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement() == null) { + break; + } + } + assertEquals(0, next.hashCode()); + } + + @SuppressWarnings("null") + public void testEntry_toString() { + Iterator> iterator = this.bag.entries(); + Bag.Entry next = null; + while (iterator.hasNext()) { + next = iterator.next(); + if (next.getElement().equals(this.four)) { + break; + } + } + assertEquals("four=>4", next.toString()); + } } diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashSetTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashSetTests.java index 5dab6f4350..670246921f 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashSetTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/IdentityHashSetTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Oracle. All rights reserved. + * Copyright (c) 2013, 2015 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. @@ -12,13 +12,14 @@ package org.eclipse.jpt.common.utility.tests.internal.collection; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; +import java.util.HashSet; 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.collection.CollectionTools; import org.eclipse.jpt.common.utility.internal.collection.IdentityHashSet; import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; @SuppressWarnings("nls") public class IdentityHashSetTests @@ -83,8 +84,10 @@ public class IdentityHashSetTests } public void testCtorInt() { - boolean exCaught; + this.set = new IdentityHashSet(20); + assertNotNull(this.set); + boolean exCaught; exCaught = false; try { this.set = new IdentityHashSet(-20); @@ -161,6 +164,7 @@ public class IdentityHashSetTests } public void testEquals() { + assertEquals(this.set, this.set); IdentityHashSet set2 = this.buildSet(); assertEquals(this.set, set2); set2.add("five"); @@ -169,6 +173,13 @@ public class IdentityHashSetTests assertFalse(this.set.equals(c)); } + public void testEquals_set() { + HashSet set2 = new HashSet(this.set); + assertEquals(this.set, set2); + set2.add("five"); + assertFalse(this.set.equals(set2)); + } + public void testHashCode() { IdentityHashSet set2 = this.buildSet(); assertEquals(this.set.hashCode(), set2.hashCode()); @@ -291,6 +302,21 @@ public class IdentityHashSetTests assertFalse(this.set.retainAll(c)); } + public void testRetainAll_IHS() { + Collection c = new IdentityHashSet(); + c.add(this.one); + c.add(new String(this.two)); + c.add(this.three); + assertTrue(this.set.retainAll(c)); + assertTrue(this.set.contains(this.one)); + assertFalse(this.set.contains(this.two)); + assertTrue(this.set.contains(this.three)); + assertFalse(this.set.contains(this.four)); + assertFalse(this.set.remove(this.two)); + assertFalse(this.set.remove(this.four)); + assertFalse(this.set.retainAll(c)); + } + public void testSize() { assertEquals(5, this.set.size()); String five = "five"; @@ -307,13 +333,13 @@ public class IdentityHashSetTests assertTrue("same object?", this.set != set2); assertEquals(5, set2.size()); - assertEquals(CollectionTools.set(this.set.iterator()), CollectionTools.set(set2.iterator())); + assertEquals(CollectionTools.hashSet(this.set.iterator()), CollectionTools.hashSet(set2.iterator())); // look for similar elements - assertTrue(CollectionTools.set(set2.iterator()).contains(null)); - assertTrue(CollectionTools.set(set2.iterator()).contains("one")); - assertTrue(CollectionTools.set(set2.iterator()).contains("two")); - assertTrue(CollectionTools.set(set2.iterator()).contains("three")); - assertTrue(CollectionTools.set(set2.iterator()).contains("four")); + assertTrue(CollectionTools.hashSet(set2.iterator()).contains(null)); + assertTrue(CollectionTools.hashSet(set2.iterator()).contains("one")); + assertTrue(CollectionTools.hashSet(set2.iterator()).contains("two")); + assertTrue(CollectionTools.hashSet(set2.iterator()).contains("three")); + assertTrue(CollectionTools.hashSet(set2.iterator()).contains("four")); int nullCount = 0, oneCount = 0, twoCount = 0, threeCount = 0, fourCount = 0; for (String next : set2) { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/JptCommonUtilityCollectionTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/JptCommonUtilityCollectionTests.java index 67a7c49947..77363e4645 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/JptCommonUtilityCollectionTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/JptCommonUtilityCollectionTests.java @@ -20,25 +20,17 @@ public class JptCommonUtilityCollectionTests { public static Test suite() { TestSuite suite = new TestSuite(JptCommonUtilityCollectionTests.class.getPackage().getName()); - suite.addTestSuite(ArrayQueueTests.class); - suite.addTestSuite(ArrayStackTests.class); - suite.addTestSuite(BagTests.class); suite.addTestSuite(CollectionToolsTests.class); - suite.addTestSuite(FixedSizeArrayQueueTests.class); - suite.addTestSuite(FixedSizeArrayStackTests.class); + suite.addTestSuite(EmptyBagTests.class); suite.addTestSuite(HashBagTests.class); suite.addTestSuite(IdentityHashBagTests.class); suite.addTestSuite(IdentityHashSetTests.class); - suite.addTestSuite(LinkedQueueTests.class); - suite.addTestSuite(LinkedStackTests.class); - suite.addTestSuite(ListQueueTests.class); - suite.addTestSuite(ListStackTests.class); suite.addTestSuite(ListToolsTests.class); suite.addTestSuite(MapToolsTests.class); suite.addTestSuite(NullElementListTests.class); + suite.addTestSuite(NullListTests.class); suite.addTestSuite(RepeatingElementListTests.class); - suite.addTestSuite(SynchronizedQueueTests.class); - suite.addTestSuite(SynchronizedStackTests.class); + suite.addTestSuite(SynchronizedBagTests.class); suite.addTestSuite(TightMapTests.class); return suite; diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedQueueTests.java deleted file mode 100644 index 31ec036f8b..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedQueueTests.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2015 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.collection; - -import java.util.Arrays; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.internal.collection.LinkedQueue; - -@SuppressWarnings("nls") -public class LinkedQueueTests - extends QueueTests -{ - public LinkedQueueTests(String name) { - super(name); - } - - @Override - Queue buildQueue() { - return new LinkedQueue(); - } - - public void testSize() { - Queue queue = this.buildQueue(); - String first = "first"; - String second = "second"; - String third = "third"; - - assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); - queue.enqueue(first); - queue.enqueue(second); - assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); - queue.enqueue(third); - assertEquals(3, ((Integer) ObjectTools.execute(queue, "size")).intValue()); - queue.dequeue(); - assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); - queue.dequeue(); - queue.dequeue(); - assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); - } - - public void testBuildElements() { - Queue queue = this.buildQueue(); - String first = "first"; - String second = "second"; - String third = "third"; - queue.enqueue(first); - queue.enqueue(second); - queue.enqueue(third); - - Object[] elements = new Object[] { first, second, third }; - assertTrue(Arrays.equals(elements, ((Object[]) ObjectTools.execute(queue, "buildElements")))); - } - - public void testNodeCache() { - Queue queue = new LinkedQueue(2); - String first = "first"; - String second = "second"; - String third = "third"; - String fourth = "fourth"; - String fifth = "fifth"; - - Object factory = ObjectTools.get(queue, "nodeFactory"); - - this.verifyNodeCache(0, factory); - queue.enqueue(first); - this.verifyNodeCache(0, factory); - queue.enqueue(second); - queue.enqueue(third); - queue.enqueue(fourth); - queue.enqueue(fifth); - this.verifyNodeCache(0, factory); - assertNull(ObjectTools.get(factory, "cacheHead")); - - queue.dequeue(); - this.verifyNodeCache(1, factory); - queue.dequeue(); - this.verifyNodeCache(2, factory); - queue.dequeue(); - this.verifyNodeCache(2, factory); - queue.dequeue(); - this.verifyNodeCache(2, factory); - queue.dequeue(); - this.verifyNodeCache(2, factory); - queue.enqueue(first); - this.verifyNodeCache(1, factory); - queue.enqueue(second); - this.verifyNodeCache(0, factory); - queue.enqueue(third); - this.verifyNodeCache(0, factory); - } - - public void verifyNodeCache(int size, Object factory) { - assertEquals(size, ((Integer) ObjectTools.get(factory, "cacheSize")).intValue()); - int nodeCount = 0; - for (Object node = ObjectTools.get(factory, "cacheHead"); node != null; node = ObjectTools.get(node, "next")) { - nodeCount++; - } - assertEquals(size, nodeCount); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedStackTests.java deleted file mode 100644 index b1dd06d91e..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/LinkedStackTests.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2015 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.collection; - -import java.util.Arrays; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.internal.collection.LinkedStack; - -@SuppressWarnings("nls") -public class LinkedStackTests - extends StackTests -{ - public LinkedStackTests(String name) { - super(name); - } - - @Override - Stack buildStack() { - return new LinkedStack(); - } - - public void testSize() { - Stack stack = this.buildStack(); - String first = "first"; - String second = "second"; - String third = "third"; - - assertEquals(0, ((Integer) ObjectTools.execute(stack, "size")).intValue()); - stack.push(first); - stack.push(second); - assertEquals(2, ((Integer) ObjectTools.execute(stack, "size")).intValue()); - stack.push(third); - assertEquals(3, ((Integer) ObjectTools.execute(stack, "size")).intValue()); - stack.pop(); - assertEquals(2, ((Integer) ObjectTools.execute(stack, "size")).intValue()); - stack.pop(); - stack.pop(); - assertEquals(0, ((Integer) ObjectTools.execute(stack, "size")).intValue()); - } - - public void testBuildElements() { - Stack stack = this.buildStack(); - String first = "first"; - String second = "second"; - String third = "third"; - stack.push(first); - stack.push(second); - stack.push(third); - - Object[] elements = new Object[] { third, second, first }; - assertTrue(Arrays.equals(elements, ((Object[]) ObjectTools.execute(stack, "buildElements")))); - } - - public void testNodeCache() { - Stack stack = new LinkedStack(2); - String first = "first"; - String second = "second"; - String third = "third"; - String fourth = "fourth"; - String fifth = "fifth"; - - Object factory = ObjectTools.get(stack, "nodeFactory"); - - this.verifyNodeCache(0, factory); - stack.push(first); - this.verifyNodeCache(0, factory); - stack.push(second); - stack.push(third); - stack.push(fourth); - stack.push(fifth); - this.verifyNodeCache(0, factory); - assertNull(ObjectTools.get(factory, "cacheHead")); - - stack.pop(); - this.verifyNodeCache(1, factory); - stack.pop(); - this.verifyNodeCache(2, factory); - stack.pop(); - this.verifyNodeCache(2, factory); - stack.pop(); - this.verifyNodeCache(2, factory); - stack.pop(); - this.verifyNodeCache(2, factory); - stack.push(first); - this.verifyNodeCache(1, factory); - stack.push(second); - this.verifyNodeCache(0, factory); - stack.push(third); - this.verifyNodeCache(0, factory); - } - - public void verifyNodeCache(int size, Object factory) { - assertEquals(size, ((Integer) ObjectTools.get(factory, "cacheSize")).intValue()); - int nodeCount = 0; - for (Object node = ObjectTools.get(factory, "cacheHead"); node != null; node = ObjectTools.get(node, "next")) { - nodeCount++; - } - assertEquals(size, nodeCount); - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListQueueTests.java deleted file mode 100644 index ff602956e2..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListQueueTests.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.collection; - -import java.util.ArrayList; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.collection.ListQueue; - -public class ListQueueTests - extends QueueTests -{ - public ListQueueTests(String name) { - super(name); - } - - @Override - Queue buildQueue() { - return new ListQueue(new ArrayList()); - } - - @Override - public void testClone() { - // unsupported - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListStackTests.java deleted file mode 100644 index 4012ee2763..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListStackTests.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 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.collection; - -import java.util.ArrayList; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.collection.ListStack; - -public class ListStackTests - extends StackTests -{ - public ListStackTests(String name) { - super(name); - } - - @Override - Stack buildStack() { - return new ListStack(new ArrayList()); - } - - @Override - public void testClone() { - // unsupported - } -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListToolsTests.java index d8045a0545..7dd8f7d10f 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListToolsTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/ListToolsTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -18,11 +18,11 @@ import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.ListIterator; import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; -import junit.framework.TestCase; import org.eclipse.jpt.common.utility.internal.ClassTools; import org.eclipse.jpt.common.utility.internal.Range; import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; @@ -31,7 +31,10 @@ import org.eclipse.jpt.common.utility.internal.comparator.ComparatorTools; import org.eclipse.jpt.common.utility.internal.iterable.EmptyIterable; import org.eclipse.jpt.common.utility.internal.iterator.EmptyIterator; import org.eclipse.jpt.common.utility.internal.predicate.PredicateTools; +import org.eclipse.jpt.common.utility.iterable.ListIterable; import org.eclipse.jpt.common.utility.tests.internal.ArrayToolsTests; +import org.eclipse.jpt.common.utility.transformer.Transformer; +import junit.framework.TestCase; @SuppressWarnings("nls") public class ListToolsTests @@ -40,6 +43,9 @@ public class ListToolsTests public ListToolsTests(String name) { super(name); } + + // ********** add all ********** + public void testAddAllListIntObjectArray() { List list = this.buildStringList1(); ListTools.addAll(list, 2, new String[] { "X", "X", "X" }); @@ -171,7 +177,7 @@ public class ListToolsTests // ********** diff ********** - public void testIndexOfDifference() { + public void testIndexOfDifference_none() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -183,7 +189,67 @@ public class ListToolsTests assertEquals(3, ListTools.indexOfDifference(list1, list2)); } - public void testLastIndexOfDifference() { + public void testIndexOfDifference_none_null() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add(null); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(null); + list2.add(new String("c")); + assertEquals(3, ListTools.indexOfDifference(list1, list2)); + } + + public void testIndexOfDifference_first() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(0, ListTools.indexOfDifference(list1, list2)); + } + + public void testIndexOfDifference_middle() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("X")); + list2.add(new String("c")); + assertEquals(1, ListTools.indexOfDifference(list1, list2)); + } + + public void testIndexOfDifference_middle_null() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add(null); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("X")); + list2.add(new String("c")); + assertEquals(1, ListTools.indexOfDifference(list1, list2)); + } + + public void testIndexOfDifference_last() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("X")); + assertEquals(2, ListTools.indexOfDifference(list1, list2)); + } + + public void testIndexOfDifference_last_size() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -191,11 +257,105 @@ public class ListToolsTests List list2 = new ArrayList(); list2.add(new String("a")); list2.add(new String("b")); + assertEquals(2, ListTools.indexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_none() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(-1, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_none_null() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add(null); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(null); list2.add(new String("c")); assertEquals(-1, ListTools.lastIndexOfDifference(list1, list2)); } - public void testDifferenceRange() { + public void testLastIndexOfDifference_first() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("X")); + assertEquals(2, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_first_size() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("b")); + assertEquals(2, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_middle() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("X")); + list2.add(new String("c")); + assertEquals(1, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_middle_null1() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add(null); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(1, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_middle_null2() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add(null); + list2.add(new String("c")); + assertEquals(1, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testLastIndexOfDifference_last() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(0, ListTools.lastIndexOfDifference(list1, list2)); + } + + public void testDifferenceRange_none() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -207,6 +367,42 @@ public class ListToolsTests assertNull(ListTools.differenceRange(list1, list2)); } + public void testDifferenceRange_single() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("b")); + list2.add(new String("c")); + assertEquals(new Range(0, 0), ListTools.differenceRange(list1, list2)); + } + + public void testDifferenceRange_some() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("Y")); + list2.add(new String("c")); + assertEquals(new Range(0, 1), ListTools.differenceRange(list1, list2)); + } + + public void testDifferenceRange_all() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("Y")); + list2.add(new String("Z")); + assertEquals(new Range(0, 2), ListTools.differenceRange(list1, list2)); + } + // ********** filter ********** @@ -228,7 +424,7 @@ public class ListToolsTests // ********** identity diff ********** - public void testIndexOfIdentityDifference() { + public void testIndexOfIdentityDifference_none() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -240,7 +436,31 @@ public class ListToolsTests assertEquals(3, ListTools.indexOfIdentityDifference(list1, list2)); } - public void testLastIndexOfIdentityDifference() { + public void testIndexOfIdentityDifference_zero() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add("b"); + list2.add("c"); + assertEquals(0, ListTools.indexOfIdentityDifference(list1, list2)); + } + + public void testIndexOfIdentityDifference_last() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add("a"); + list2.add("b"); + list2.add(new String("c")); + assertEquals(2, ListTools.indexOfIdentityDifference(list1, list2)); + } + + public void testLastIndexOfIdentityDifference_none() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -252,7 +472,42 @@ public class ListToolsTests assertEquals(-1, ListTools.lastIndexOfIdentityDifference(list1, list2)); } - public void testIdentityDifferenceRange() { + public void testLastIndexOfIdentityDifference_zero() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("a")); + list2.add("b"); + list2.add("c"); + assertEquals(0, ListTools.lastIndexOfIdentityDifference(list1, list2)); + } + + public void testLastIndexOfIdentityDifference_first() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add("a"); + list2.add("b"); + list2.add(new String("c")); + assertEquals(2, ListTools.lastIndexOfIdentityDifference(list1, list2)); + } + + public void testLastIndexOfIdentityDifference_size() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add("a"); + list2.add("b"); + assertEquals(2, ListTools.lastIndexOfIdentityDifference(list1, list2)); + } + + public void testIdentityDifferenceRange_none() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -264,6 +519,42 @@ public class ListToolsTests assertNull(ListTools.identityDifferenceRange(list1, list2)); } + public void testIdentityDifferenceRange_single() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add("b"); + list2.add("c"); + assertEquals(new Range(0, 0), ListTools.identityDifferenceRange(list1, list2)); + } + + public void testIdentityDifferenceRange_some() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("Y")); + list2.add("c"); + assertEquals(new Range(0, 1), ListTools.identityDifferenceRange(list1, list2)); + } + + public void testIdentityDifferenceRange_all() { + List list1 = new ArrayList(); + list1.add("a"); + list1.add("b"); + list1.add("c"); + List list2 = new ArrayList(); + list2.add(new String("X")); + list2.add(new String("Y")); + list2.add(new String("Z")); + assertEquals(new Range(0, 2), ListTools.identityDifferenceRange(list1, list2)); + } + // ********** index of ********** @@ -273,6 +564,7 @@ public class ListToolsTests assertEquals(1, ListTools.indexOf(list, "B", 1)); assertEquals(-1, ListTools.indexOf(list, "B", 2)); assertEquals(-1, ListTools.indexOf(list, "B", 22)); + assertEquals(-1, ListTools.indexOf(new ArrayList(), "B", 1)); } public void testIndexOfListObjectInt_Null() { @@ -287,9 +579,12 @@ public class ListToolsTests String s = "B"; List list = Arrays.asList(new String[] { "A", s, "C", "D" }); assertEquals(1, ListTools.identityIndexOf(list, s, -11)); + assertEquals(1, ListTools.identityIndexOf(list, s, 0)); assertEquals(1, ListTools.identityIndexOf(list, s, 1)); assertEquals(-1, ListTools.identityIndexOf(list, s, 2)); assertEquals(-1, ListTools.identityIndexOf(list, s, 22)); + assertEquals(-1, ListTools.identityIndexOf(list, s, 4)); + assertEquals(-1, ListTools.identityIndexOf(new ArrayList(), s, 1)); } public void testIdentityIndexOfListObjectInt_NotFound() { @@ -395,7 +690,12 @@ public class ListToolsTests assertEquals(-1, ListTools.lastIndexOf(list, "B", -11)); assertEquals(1, ListTools.lastIndexOf(list, "B", 1)); assertEquals(1, ListTools.lastIndexOf(list, "B", 2)); + assertEquals(1, ListTools.lastIndexOf(list, "B", 4)); + assertEquals(-1, ListTools.lastIndexOf(list, null, 4)); assertEquals(1, ListTools.lastIndexOf(list, "B", 22)); + assertEquals(0, ListTools.lastIndexOf(list, "A", 22)); + assertEquals(-1, ListTools.lastIndexOf(list, "XXXs", 22)); + assertEquals(-1, ListTools.lastIndexOf(new ArrayList(), "XXXs", 22)); } public void testLastIndexOfListObjectInt_Null() { @@ -404,6 +704,8 @@ public class ListToolsTests assertEquals(1, ListTools.lastIndexOf(list, null, 1)); assertEquals(1, ListTools.lastIndexOf(list, null, 2)); assertEquals(1, ListTools.lastIndexOf(list, null, 22)); + list = Arrays.asList(new String[] { null, "A", "C", "D" }); + assertEquals(0, ListTools.lastIndexOf(list, null, 22)); } public void testLastIdentityIndexOfListObjectInt() { @@ -412,7 +714,9 @@ public class ListToolsTests assertEquals(-1, ListTools.lastIdentityIndexOf(list, s, -11)); assertEquals(1, ListTools.lastIdentityIndexOf(list, s, 1)); assertEquals(1, ListTools.lastIdentityIndexOf(list, s, 2)); + assertEquals(1, ListTools.lastIdentityIndexOf(list, s, 4)); assertEquals(1, ListTools.lastIdentityIndexOf(list, s, 22)); + assertEquals(-1, ListTools.lastIdentityIndexOf(new ArrayList(), s, 22)); } public void testLastIdentityIndexOfListObjectInt_NotFound() { @@ -426,49 +730,49 @@ public class ListToolsTests } - // ********** list ********** + // ********** array list ********** - public void testListIterable() { + public void testArrayListIterable() { Iterable iterable = this.buildStringList1(); - assertEquals(this.buildStringList1(), ListTools.list(iterable)); + assertEquals(this.buildStringList1(), ListTools.arrayList(iterable)); } - public void testListIterableInt() { + public void testArrayListIterableInt() { Iterable iterable = this.buildStringList1(); - assertEquals(this.buildStringList1(), ListTools.list(iterable, 3)); + assertEquals(this.buildStringList1(), ListTools.arrayList(iterable, 3)); } - public void testListIterator_String() { - List list = ListTools.list(this.buildStringList1().iterator()); + public void testArrayListIterator_String() { + List list = ListTools.arrayList(this.buildStringList1().iterator()); assertEquals(this.buildStringList1(), list); } - public void testListIterator_StringObject() { + public void testArrayListIterator_StringObject() { List list1 = new ArrayList(); list1.add("0"); list1.add("1"); list1.add("2"); list1.add("3"); - List list2 = ListTools.list(list1.iterator()); + List list2 = ListTools.arrayList(list1.iterator()); assertEquals(list1, list2); } - public void testListIterator_Empty() { - assertEquals(0, ListTools.list(EmptyIterator.instance()).size()); + public void testArrayListIterator_Empty() { + assertEquals(0, ListTools.arrayList(EmptyIterator.instance()).size()); } - public void testListIteratorInt() { - List list = ListTools.list(this.buildStringList1().iterator(), 3); + public void testArrayListIteratorInt() { + List list = ListTools.arrayList(this.buildStringList1().iterator(), 3); assertEquals(this.buildStringList1(), list); } - public void testListIteratorInt_Empty() { - assertEquals(0, ListTools.list(EmptyIterator.instance(), 5).size()); + public void testArrayListIteratorInt_Empty() { + assertEquals(0, ListTools.arrayList(EmptyIterator.instance(), 5).size()); } - public void testListObjectArray() { - List list = ListTools.list(this.buildStringArray1()); + public void testArrayListObjectArray() { + List list = ListTools.arrayList(this.buildStringArray1()); assertEquals(this.buildStringList1(), list); } @@ -712,6 +1016,16 @@ public class ListToolsTests } } + public void testReverseList() { + List list = this.buildStringList1(); + List result = ListTools.reverse(list); + assertSame(list, result); + assertEquals("two", list.get(0)); + assertEquals("one", list.get(1)); + assertEquals("zero", list.get(2)); + assertEquals(3, list.size()); + } + public void testShuffleList() { List list = this.buildStringList1(); List result = ListTools.shuffle(list); @@ -730,6 +1044,22 @@ public class ListToolsTests ss.addAll(list); List result = ListTools.sort(list); assertSame(list, result); + Iterator ssIterator = ss.iterator(); + for (Iterator listIterator = list.iterator(); listIterator.hasNext(); ) { + assertEquals(ssIterator.next(), listIterator.next()); + } + } + + public void testSortListComparator() { + List list = this.buildStringList1(); + SortedSet ss = new TreeSet(ComparatorTools.reverseComparator()); + ss.addAll(list); + List result = ListTools.sort(list, ComparatorTools.reverseComparator()); + assertSame(list, result); + Iterator ssIterator = ss.iterator(); + for (Iterator listIterator = list.iterator(); listIterator.hasNext(); ) { + assertEquals(ssIterator.next(), listIterator.next()); + } } public void testSwapListIntInt() { @@ -743,6 +1073,87 @@ public class ListToolsTests } + // ********** transformers ********** + + public void testListIteratorTransformer() { + Transformer, ListIterator> transformer = ListTools.listIteratorTransformer(); + assertNotNull(transformer); + assertNotNull(transformer.toString()); + List list = this.buildStringList1(); + ListIterator iterator = transformer.transform(list); + assertNotNull(iterator); + assertEquals("zero", iterator.next()); + assertEquals("one", iterator.next()); + iterator.set("XXX"); + assertEquals("two", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals("XXX", list.get(1)); + } + + public void testReadOnlyListIteratorTransformer() { + Transformer, ListIterator> transformer = ListTools.readOnlyListIteratorTransformer(); + assertNotNull(transformer); + assertNotNull(transformer.toString()); + List list = this.buildStringList1(); + ListIterator iterator = transformer.transform(list); + assertNotNull(iterator); + assertEquals("zero", iterator.next()); + assertEquals("one", iterator.next()); + + boolean exCaught = false; + try { + iterator.set("XXX"); + fail("bogus: " + iterator); //$NON-NLS-1$ + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("two", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals("one", list.get(1)); + } + + public void testListIterableTransformer() { + Transformer, ListIterable> transformer = ListTools.listIterableTransformer(); + assertNotNull(transformer); + assertNotNull(transformer.toString()); + List list = this.buildStringList1(); + ListIterator iterator = transformer.transform(list).iterator(); + assertNotNull(iterator); + assertEquals("zero", iterator.next()); + assertEquals("one", iterator.next()); + iterator.set("XXX"); + assertEquals("two", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals("XXX", list.get(1)); + } + + public void testReadOnlyListIterableTransformer() { + Transformer, ListIterable> transformer = ListTools.readOnlyListIterableTransformer(); + assertNotNull(transformer); + assertNotNull(transformer.toString()); + List list = this.buildStringList1(); + ListIterator iterator = transformer.transform(list).iterator(); + assertNotNull(iterator); + assertEquals("zero", iterator.next()); + assertEquals("one", iterator.next()); + + boolean exCaught = false; + try { + iterator.set("XXX"); + fail("bogus: " + iterator); //$NON-NLS-1$ + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("two", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals("one", list.get(1)); + } + + // ********** constructor ********** public void testConstructor() { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/MapToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/MapToolsTests.java index 03ec8d932f..f257662833 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/MapToolsTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/MapToolsTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Oracle. All rights reserved. + * Copyright (c) 2013, 2015 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. @@ -9,24 +9,26 @@ ******************************************************************************/ package org.eclipse.jpt.common.utility.tests.internal.collection; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; -import junit.framework.TestCase; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.collection.Stack; import org.eclipse.jpt.common.utility.factory.Factory; import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.ClassTools; import org.eclipse.jpt.common.utility.internal.StringTools; import org.eclipse.jpt.common.utility.internal.collection.MapTools; -import org.eclipse.jpt.common.utility.internal.collection.QueueTools; -import org.eclipse.jpt.common.utility.internal.collection.StackTools; import org.eclipse.jpt.common.utility.internal.factory.FactoryTools; import org.eclipse.jpt.common.utility.internal.predicate.PredicateAdapter; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; import org.eclipse.jpt.common.utility.internal.transformer.AbstractTransformer; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; import org.eclipse.jpt.common.utility.transformer.Transformer; +import junit.framework.TestCase; @SuppressWarnings("nls") public class MapToolsTests @@ -45,6 +47,15 @@ public class MapToolsTests assertEquals(null, MapTools.get(map, "7", "")); } + public void testGet_MapObjectObject() { + Map map = this.buildMap(); + assertEquals("one", MapTools.get_(map, "1", "")); + assertEquals("", MapTools.get_(map, "7", "")); + assertEquals("", map.get("7")); + map.put("7", null); + assertEquals("", MapTools.get_(map, "7", "")); + } + public void testGetMapObjectFactory() { Factory factory = FactoryTools.staticFactory(""); Map map = this.buildMap(); @@ -55,6 +66,16 @@ public class MapToolsTests assertEquals(null, MapTools.get(map, "7", factory)); } + public void testGet_MapObjectFactory() { + Factory factory = FactoryTools.staticFactory(""); + Map map = this.buildMap(); + assertEquals("one", MapTools.get_(map, "1", factory)); + assertEquals("", MapTools.get_(map, "7", factory)); + assertEquals("", map.get("7")); + map.put("7", null); + assertEquals("", MapTools.get_(map, "7", factory)); + } + @SuppressWarnings("unchecked") public void testGetMapObjectClass() { ArrayList list = new ArrayList(); @@ -65,6 +86,36 @@ public class MapToolsTests assertEquals(null, MapTools.get(map, "7", ArrayList.class)); } + @SuppressWarnings("unchecked") + public void testGet_MapObjectClass() { + ArrayList list = new ArrayList(); + Map> map = this.buildListMap(); + assertEquals(list, MapTools.get_(map, "1", ArrayList.class)); + assertEquals(list, MapTools.get_(map, "7", ArrayList.class)); + map.put("7", null); + assertEquals(list, MapTools.get_(map, "7", ArrayList.class)); + } + + @SuppressWarnings("unchecked") + public void testGetMapObjectClassClassObject() { + ArrayList list = new ArrayList(); + Map> map = this.buildListMap(); + assertEquals(list, MapTools.get(map, "1", ArrayList.class, Collection.class, new ArrayList())); + assertEquals(list, MapTools.get(map, "7", ArrayList.class, Collection.class, new ArrayList())); + map.put("7", null); + assertEquals(null, MapTools.get(map, "7", ArrayList.class, Collection.class, new ArrayList())); + } + + @SuppressWarnings("unchecked") + public void testGet_MapObjectClassClassObject() { + ArrayList list = new ArrayList(); + Map> map = this.buildListMap(); + assertEquals(list, MapTools.get_(map, "1", ArrayList.class, Collection.class, new ArrayList())); + assertEquals(list, MapTools.get_(map, "7", ArrayList.class, Collection.class, new ArrayList())); + map.put("7", null); + assertEquals(new ArrayList(), MapTools.get_(map, "7", ArrayList.class, Collection.class, new ArrayList())); + } + public void testAddMapObjectTransformer() { Map map = new HashMap(); assertEquals(null, MapTools.add(map, "one", REVERSE_STRING_TRANSFORMER)); @@ -96,7 +147,7 @@ public class MapToolsTests strings.add("baz"); Queue queue = QueueTools.arrayQueue(strings); Map map = new HashMap(); - MapTools.addAll(map, queue, REVERSE_STRING_TRANSFORMER); + QueueTools.drainTo(queue, map, REVERSE_STRING_TRANSFORMER); assertEquals("foo", map.get("oof")); assertEquals("bar", map.get("rab")); assertEquals("baz", map.get("zab")); @@ -109,7 +160,7 @@ public class MapToolsTests strings.add("baz"); Stack stack = StackTools.arrayStack(strings); Map map = new HashMap(); - MapTools.addAll(map, stack, REVERSE_STRING_TRANSFORMER); + StackTools.popAllTo(stack, map, REVERSE_STRING_TRANSFORMER); assertEquals("foo", map.get("oof")); assertEquals("bar", map.get("rab")); assertEquals("baz", map.get("zab")); @@ -142,7 +193,7 @@ public class MapToolsTests strings.add("baz"); Queue queue = QueueTools.arrayQueue(strings); Map map = new HashMap(); - MapTools.addAll(map, queue, REVERSE_STRING_TRANSFORMER, SORT_STRING_TRANSFORMER); + QueueTools.drainTo(queue, map, REVERSE_STRING_TRANSFORMER, SORT_STRING_TRANSFORMER); assertEquals("foo", map.get("oof")); assertEquals("abr", map.get("rab")); assertEquals("abz", map.get("zab")); @@ -155,7 +206,7 @@ public class MapToolsTests strings.add("baz"); Stack stack = StackTools.arrayStack(strings); Map map = new HashMap(); - MapTools.addAll(map, stack, REVERSE_STRING_TRANSFORMER, SORT_STRING_TRANSFORMER); + StackTools.popAllTo(stack, map, REVERSE_STRING_TRANSFORMER, SORT_STRING_TRANSFORMER); assertEquals("foo", map.get("oof")); assertEquals("abr", map.get("rab")); assertEquals("abz", map.get("zab")); @@ -175,12 +226,40 @@ public class MapToolsTests assertEquals(this.buildMap(), map); } + public void testPutAllMapListList_IAE() { + Map map = new HashMap(); + boolean exCaught = false; + try { + List values = this.buildValues(); + values.remove(0); + MapTools.putAll(map, this.buildKeys(), values); + fail("bogus: " + map); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + public void testPutAllMapArrayArray() { Map map = new HashMap(); MapTools.putAll(map, this.buildKeys().toArray(StringTools.EMPTY_STRING_ARRAY), this.buildValues().toArray(StringTools.EMPTY_STRING_ARRAY)); assertEquals(this.buildMap(), map); } + public void testPutAllMapArrayArray_IAE() { + Map map = new HashMap(); + boolean exCaught = false; + try { + String[] values = this.buildValues().toArray(StringTools.EMPTY_STRING_ARRAY); + values = ArrayTools.removeElementAtIndex(values, 0); + MapTools.putAll(map, this.buildKeys().toArray(StringTools.EMPTY_STRING_ARRAY), values); + fail("bogus: " + map); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + public void testContainsAllKeysMapIterable() { Map map = this.buildMap(); Iterable keys = this.buildKeys(); @@ -197,24 +276,6 @@ public class MapToolsTests assertFalse(MapTools.containsAllKeys(map, (Object[]) keys)); } - public void testContainsAllKeysMapQueue() { - Map map = this.buildMap(); - Queue keys = QueueTools.arrayQueue(this.buildKeys()); - assertTrue(MapTools.containsAllKeys(map, keys)); - map.remove("1"); - keys = QueueTools.arrayQueue(this.buildKeys()); // rebuild queue - assertFalse(MapTools.containsAllKeys(map, keys)); - } - - public void testContainsAllKeysMapStack() { - Map map = this.buildMap(); - Stack keys = StackTools.arrayStack(this.buildKeys()); - assertTrue(MapTools.containsAllKeys(map, keys)); - map.remove("1"); - keys = StackTools.arrayStack(this.buildKeys()); // rebuild stack - assertFalse(MapTools.containsAllKeys(map, keys)); - } - public void testContainsAllValuesMapIterable() { Map map = this.buildMap(); Iterable values = this.buildValues(); @@ -231,24 +292,6 @@ public class MapToolsTests assertFalse(MapTools.containsAllValues(map, (Object[]) values)); } - public void testContainsAllValuesMapQueue() { - Map map = this.buildMap(); - Queue values = QueueTools.arrayQueue(this.buildValues()); - assertTrue(MapTools.containsAllValues(map, values)); - map.remove("1"); - values = QueueTools.arrayQueue(this.buildValues()); // rebuild queue - assertFalse(MapTools.containsAllValues(map, values)); - } - - public void testContainsAllValuesMapStack() { - Map map = this.buildMap(); - Stack values = StackTools.arrayStack(this.buildValues()); - assertTrue(MapTools.containsAllValues(map, values)); - map.remove("1"); - values = StackTools.arrayStack(this.buildValues()); // rebuild stack - assertFalse(MapTools.containsAllValues(map, values)); - } - public void testRemoveAllMapIterable() { Map map = this.buildMap(); Iterable keys = this.buildKeys(); @@ -265,22 +308,6 @@ public class MapToolsTests assertTrue(map.isEmpty()); } - public void testRemoveAllMapQueue() { - Map map = this.buildMap(); - Queue keys = QueueTools.arrayQueue(this.buildKeys()); - assertFalse(map.isEmpty()); - MapTools.removeAll(map, keys); - assertTrue(map.isEmpty()); - } - - public void testRemoveAllMapStack() { - Map map = this.buildMap(); - Stack keys = StackTools.arrayStack(this.buildKeys()); - assertFalse(map.isEmpty()); - MapTools.removeAll(map, keys); - assertTrue(map.isEmpty()); - } - public void testRetainAllMapCollection() { Map map = this.buildMap(); Collection keys = this.buildKeys(); @@ -321,64 +348,43 @@ public class MapToolsTests assertTrue(map.isEmpty()); } - public void testRetainAllMapArray() { - Map map = this.buildMap(); - String[] keys = this.buildKeys().toArray(StringTools.EMPTY_STRING_ARRAY); - assertFalse(map.isEmpty()); - MapTools.retainAll(map, (Object[]) keys); - assertEquals(this.buildMap(), map); - keys = ArrayTools.remove(keys, "3"); - MapTools.retainAll(map, (Object[]) keys); - assertFalse(map.containsKey("3")); - } - - public void testRetainAllMapArray_empty() { + public void testRetainAllMapIterableInt() { Map map = this.buildMap(); - String[] keys = StringTools.EMPTY_STRING_ARRAY; - assertFalse(map.isEmpty()); - MapTools.retainAll(map, (Object[]) keys); - assertTrue(map.isEmpty()); - } - - public void testRetainAllMapQueue() { - Map map = this.buildMap(); - Queue keys = QueueTools.arrayQueue(this.buildKeys()); + Iterable keys = this.buildKeys(); assertFalse(map.isEmpty()); - MapTools.retainAll(map, keys); + MapTools.retainAll(map, keys, 77); assertEquals(this.buildMap(), map); Collection temp = this.buildKeys(); temp.remove("3"); - keys = QueueTools.arrayQueue(temp); + keys = temp; MapTools.retainAll(map, keys); assertFalse(map.containsKey("3")); } - public void testRetainAllMapQueue_empty() { + public void testRetainAllMapIterableInt_empty() { Map map = this.buildMap(); - Queue keys = QueueTools.emptyQueue(); + Iterable keys = new ArrayList(); assertFalse(map.isEmpty()); - MapTools.retainAll(map, keys); + MapTools.retainAll(map, keys, 77); assertTrue(map.isEmpty()); } - public void testRetainAllMapStack() { + public void testRetainAllMapArray() { Map map = this.buildMap(); - Stack keys = StackTools.arrayStack(this.buildKeys()); + String[] keys = this.buildKeys().toArray(StringTools.EMPTY_STRING_ARRAY); assertFalse(map.isEmpty()); - MapTools.retainAll(map, keys); + MapTools.retainAll(map, (Object[]) keys); assertEquals(this.buildMap(), map); - Collection temp = this.buildKeys(); - temp.remove("3"); - keys = StackTools.arrayStack(temp); - MapTools.retainAll(map, keys); + keys = ArrayTools.remove(keys, "3"); + MapTools.retainAll(map, (Object[]) keys); assertFalse(map.containsKey("3")); } - public void testRetainAllMapStack_empty() { + public void testRetainAllMapArray_empty() { Map map = this.buildMap(); - Stack keys = StackTools.emptyStack(); + String[] keys = StringTools.EMPTY_STRING_ARRAY; assertFalse(map.isEmpty()); - MapTools.retainAll(map, keys); + MapTools.retainAll(map, (Object[]) keys); assertTrue(map.isEmpty()); } @@ -415,6 +421,21 @@ public class MapToolsTests assertEquals("ruof", map.get("4")); } + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ClassTools.newInstance(MapTools.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); + } + private List buildKeys() { ArrayList keys = new ArrayList(); keys.add("0"); diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/NullListTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/NullListTests.java new file mode 100644 index 0000000000..33c3397aaa --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/NullListTests.java @@ -0,0 +1,247 @@ +/******************************************************************************* + * Copyright (c) 2015 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.collection; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.ListIterator; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.collection.NullList; +import org.eclipse.jpt.common.utility.internal.iterator.IteratorTools; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class NullListTests + extends TestCase +{ + public NullListTests(String name) { + super(name); + } + + public void testAddObject() { + List list = NullList.instance(); + assertFalse(list.add("foo")); + assertTrue(list.isEmpty()); + } + + public void testAddIntObject() { + List list = NullList.instance(); + list.add(0, "foo"); + assertTrue(list.isEmpty()); + } + + public void testAddAllCollection() { + List list = NullList.instance(); + Collection collection = new ArrayList(); + collection.add("foo"); + collection.add("bar"); + assertFalse(list.addAll(collection)); + assertTrue(list.isEmpty()); + } + + public void testAddAllIntCollection() { + List list = NullList.instance(); + Collection collection = new ArrayList(); + collection.add("foo"); + collection.add("bar"); + assertFalse(list.addAll(0, collection)); + assertTrue(list.isEmpty()); + } + + public void testClear() { + List list = NullList.instance(); + list.clear(); + assertTrue(list.isEmpty()); + } + + public void testContainsObject() { + List list = NullList.instance(); + Collection collection = new ArrayList(); + collection.add("foo"); + collection.add("bar"); + assertFalse(list.addAll(collection)); + assertFalse(list.contains("foo")); + assertFalse(list.contains("bar")); + assertFalse(list.contains("XXX")); + } + + public void testContainsAllCollection() { + List list = NullList.instance(); + Collection collection = new ArrayList(); + collection.add("foo"); + collection.add("bar"); + assertFalse(list.addAll(collection)); + assertFalse(list.containsAll(collection)); + collection.clear(); + assertTrue(list.containsAll(collection)); + } + + public void testGetInt() { + List list = NullList.instance(); + boolean exCaught = false; + try { + list.get(0); + fail(); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIndexOfObject() { + List list = NullList.instance(); + assertEquals(-1, list.indexOf("foo")); + } + + public void testIsEmpty() { + List list = NullList.instance(); + assertTrue(list.isEmpty()); + } + + public void testIterator() { + List list = NullList.instance(); + assertTrue(IteratorTools.isEmpty(list.iterator())); + } + + public void testLastIndexOfObject() { + List list = NullList.instance(); + assertEquals(-1, list.lastIndexOf("foo")); + } + + public void testListIterator() { + List list = NullList.instance(); + assertTrue(IteratorTools.isEmpty(list.listIterator())); + } + + public void testListIteratorInt() { + List list = NullList.instance(); + ListIterator iterator = list.listIterator(0); + assertTrue(IteratorTools.isEmpty(iterator)); + boolean exCaught = false; + try { + iterator = list.listIterator(1); + fail("bogus list iterator: " + iterator); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testRemoveObject() { + List list = NullList.instance(); + assertFalse(list.remove("foo")); + assertTrue(list.isEmpty()); + } + + public void testRemoveInt() { + List list = NullList.instance(); + boolean exCaught = false; + try { + String object = list.remove(0); + fail("bogus element: " + object); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + assertTrue(list.isEmpty()); + } + + public void testRemoveAllCollection() { + List list = NullList.instance(); + Collection collection = new ArrayList(); + collection.add("foo"); + collection.add("bar"); + assertFalse(list.removeAll(collection)); + assertTrue(list.isEmpty()); + } + + public void testRetainAllCollection() { + List list = NullList.instance(); + Collection collection = new ArrayList(); + collection.add("foo"); + collection.add("bar"); + assertFalse(list.retainAll(collection)); + assertTrue(list.isEmpty()); + } + + public void testSetIntObject() { + List list = NullList.instance(); + boolean exCaught = false; + try { + String element = list.set(0, "foo"); + fail("bogus set: " + element); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSize() { + List list = NullList.instance(); + assertEquals(0, list.size()); + } + + public void testSubList() { + List list = NullList.instance(); + List subList = list.subList(0, 0); + assertTrue(subList.isEmpty()); + boolean exCaught = false; + try { + subList = list.subList(0, 3); + fail("bogus sub list: " + subList); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + + exCaught = false; + try { + subList = list.subList(3, 0); + fail("bogus sub list: " + subList); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + + exCaught = false; + try { + subList = list.subList(3, 3); + fail("bogus sub list: " + subList); + } catch (IndexOutOfBoundsException ex) { + exCaught = true; + } + assertTrue(exCaught); + + subList = list.subList(0, 0); + assertTrue(subList.isEmpty()); + } + + public void testToArray() { + List list = NullList.instance(); + assertEquals(0, list.toArray().length); + } + + public void testToArrayObjectArray() { + List list = NullList.instance(); + assertEquals(0, list.toArray(ObjectTools.EMPTY_OBJECT_ARRAY).length); + } + + public void testSerialization() throws Exception { + List list = NullList.instance(); + assertSame(list, TestTools.serialize(list)); + } + + public void testToString() { + List list = NullList.instance(); + assertEquals("[]", list.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/QueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/QueueTests.java deleted file mode 100644 index 9cd09a4f30..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/QueueTests.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2015 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.collection; - -import java.util.NoSuchElementException; -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -// subclass MultiThreadedTestCase for subclasses of this class -@SuppressWarnings("nls") -public abstract class QueueTests - extends MultiThreadedTestCase -{ - public QueueTests(String name) { - super(name); - } - - abstract Queue buildQueue(); - - public void testIsEmpty() { - Queue 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 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 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 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 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() { - Queue queue = this.buildQueue(); - queue.enqueue("first"); - queue.enqueue("second"); - queue.enqueue("third"); - - @SuppressWarnings("unchecked") - Queue clone = (Queue) ObjectTools.execute(queue, "clone"); - this.verifyClone(queue, clone); - } - - public void testSerialization() throws Exception { - Queue queue = this.buildQueue(); - queue.enqueue("first"); - queue.enqueue("second"); - queue.enqueue("third"); - - this.verifyClone(queue, TestTools.serialize(queue)); - } - - protected void verifyClone(Queue original, Queue 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/collection/StackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/StackTests.java deleted file mode 100644 index ad755fe1a3..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/StackTests.java +++ /dev/null @@ -1,150 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2015 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.collection; - -import java.util.EmptyStackException; -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; -import org.eclipse.jpt.common.utility.tests.internal.TestTools; - -//subclass MultiThreadedTestCase for subclasses of this class -@SuppressWarnings("nls") -public abstract class StackTests - extends MultiThreadedTestCase -{ - public StackTests(String name) { - super(name); - } - - abstract Stack buildStack(); - - public void testIsEmpty() { - Stack 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 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 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 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 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() { - Stack stack = this.buildStack(); - stack.push("first"); - stack.push("second"); - stack.push("third"); - - @SuppressWarnings("unchecked") - Stack clone = (Stack) ObjectTools.execute(stack, "clone"); - this.verifyClone(stack, clone); - } - - public void testSerialization() throws Exception { - Stack stack = this.buildStack(); - stack.push("first"); - stack.push("second"); - stack.push("third"); - - this.verifyClone(stack, TestTools.serialize(stack)); - } - - protected void verifyClone(Stack original, Stack 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/collection/SynchronizedBagTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedBagTests.java new file mode 100644 index 0000000000..011315bed8 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedBagTests.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2005, 2015 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.collection; + +import java.util.Collection; +import org.eclipse.jpt.common.utility.collection.Bag; +import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; +import org.eclipse.jpt.common.utility.internal.collection.HashBag; + +@SuppressWarnings("nls") +public class SynchronizedBagTests + extends BagTests +{ + public SynchronizedBagTests(String name) { + super(name); + } + + @Override + protected Bag buildBag_() { + return CollectionTools.synchronizedBag(); + } + + @Override + protected Bag buildBag(Collection c) { + return CollectionTools.synchronizedBag(new HashBag(c)); + } + + @Override + protected Bag buildBag(int initialCapacity, float loadFactor) { + return CollectionTools.synchronizedBag(new HashBag(initialCapacity, loadFactor)); + } + + @Override + public void testClone() { + // synchronized bag is not cloneable + } + + public void testCtorBagObject_nullBag() { + boolean exCaught = false; + try { + Bag bag = CollectionTools.synchronizedBag(null, "foo"); + fail("bogus bag: " + bag); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testCtorBagObject_nullMutex() { + Bag wrapped = CollectionTools.hashBag(); + boolean exCaught = false; + try { + Bag bag = CollectionTools.synchronizedBag(wrapped, null); + fail("bogus bag: " + bag); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testCtorBag_nullBag() { + boolean exCaught = false; + try { + Bag bag = CollectionTools.synchronizedBag(null); + fail("bogus bag: " + bag); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedQueueTests.java deleted file mode 100644 index 1973b5a68c..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedQueueTests.java +++ /dev/null @@ -1,260 +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.collection; - -import java.util.NoSuchElementException; - -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.collection.LinkedQueue; -import org.eclipse.jpt.common.utility.internal.collection.SynchronizedQueue; - -@SuppressWarnings("nls") -public class SynchronizedQueueTests - extends QueueTests -{ - private volatile SynchronizedQueue 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 buildQueue() { - return new SynchronizedQueue(); - } - - @Override - public void testClone() { - // synchronized queue is not cloneable - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.sq = new SynchronizedQueue(); - 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 SlowLinkedQueue(), "first"); - this.verifyConcurrentAccess(new SlowSynchronizedQueue(), "second"); - } - - private void verifyConcurrentAccess(SlowQueue 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 slowQueue) { - return new Runnable() { - public void run() { - slowQueue.slowDequeue(); - } - }; - } - - - private interface SlowQueue extends Queue { - Object slowDequeue(); - } - - private class SlowLinkedQueue extends LinkedQueue implements SlowQueue { - private static final long serialVersionUID = 1L; - SlowLinkedQueue() { - super(); - } - public Object slowDequeue() { - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - return this.dequeue(); - } - - } - - private class SlowSynchronizedQueue extends SynchronizedQueue implements SlowQueue { - private static final long serialVersionUID = 1L; - 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 synchronizedQueue) { - synchronizedQueue.enqueue(ITEM_1); - } - }; - } - - private Command buildWaitToDequeueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedQueue 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 synchronizedQueue) { - SynchronizedQueueTests.this.dequeuedObject = synchronizedQueue.dequeue(); - } - }; - } - - private Command buildWaitToEnqueueCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedQueue 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 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 synchronizedQueue) throws InterruptedException; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedStackTests.java deleted file mode 100644 index a0a923ef76..0000000000 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/SynchronizedStackTests.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.collection; - -import java.util.EmptyStackException; - -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.collection.LinkedStack; -import org.eclipse.jpt.common.utility.internal.collection.SynchronizedStack; - -@SuppressWarnings("nls") -public class SynchronizedStackTests - extends StackTests -{ - private volatile SynchronizedStack 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 buildStack() { - return new SynchronizedStack(); - } - - @Override - public void testClone() { - // synchronized stack is not cloneable - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - this.ss = new SynchronizedStack(); - 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 SlowLinkedStack(), "second"); - this.verifyConcurrentAccess(new SlowSynchronizedStack(), "first"); - } - - private void verifyConcurrentAccess(SlowStack 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 slowStack) { - return new Runnable() { - public void run() { - slowStack.slowPop(); - } - }; - } - - - private interface SlowStack extends Stack { - Object slowPop(); - } - - private class SlowLinkedStack extends LinkedStack implements SlowStack { - private static final long serialVersionUID = 1L; - SlowLinkedStack() { - super(); - } - public Object slowPop() { - try { - Thread.sleep(5 * TICK); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - return this.pop(); - } - - } - - private class SlowSynchronizedStack extends SynchronizedStack implements SlowStack { - private static final long serialVersionUID = 1L; - 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 synchronizedStack) { - synchronizedStack.push(ITEM_1); - } - }; - } - - private Command buildWaitToPopCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedStack 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 synchronizedStack) { - SynchronizedStackTests.this.poppedObject = synchronizedStack.pop(); - } - }; - } - - private Command buildWaitToPushCommand(final long timeout) { - return new Command() { - public void execute(SynchronizedStack 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 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 synchronizedStack) throws InterruptedException; - } - -} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/TightMapTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/TightMapTests.java index c243a8d2f8..0722e2a0c9 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/TightMapTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/collection/TightMapTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Oracle. All rights reserved. + * Copyright (c) 2013, 2015 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. @@ -18,7 +18,6 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; -import junit.framework.TestCase; import org.eclipse.jpt.common.utility.internal.ArrayTools; import org.eclipse.jpt.common.utility.internal.ObjectTools; import org.eclipse.jpt.common.utility.internal.StringTools; @@ -26,6 +25,7 @@ import org.eclipse.jpt.common.utility.internal.collection.CollectionTools; import org.eclipse.jpt.common.utility.internal.collection.TightMap; import org.eclipse.jpt.common.utility.internal.iterator.IteratorTools; import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; @SuppressWarnings("nls") public class TightMapTests @@ -64,6 +64,13 @@ public class TightMapTests super.tearDown(); } + public void testCtorMap() { + Map map2 = new HashMap(); + + this.map = new TightMap(map2); + assertEquals(this.map, map2); + } + public void testSize() { assertEquals(6, this.map.size()); @@ -200,6 +207,10 @@ public class TightMapTests assertFalse(this.map.containsKey("7")); assertEquals(3, this.map.size()); assertFalse(this.map.containsValue("seven")); + + assertEquals("one", this.map.remove("1")); + assertEquals("two", this.map.remove("2")); + assertEquals("four", this.map.remove("4")); } public void testPutAll() { @@ -740,14 +751,14 @@ public class TightMapTests Collection values = this.map.values(); HashMap map2 = new HashMap(); this.populateMap(map2); - assertTrue(CollectionTools.bag(values).equals(CollectionTools.bag(map2.values()))); + assertTrue(CollectionTools.hashBag(values).equals(CollectionTools.hashBag(map2.values()))); } public void testValues_hashCode() { Collection values = this.map.values(); HashMap map2 = new HashMap(); this.populateMap(map2); - assertEquals(CollectionTools.bag(values).hashCode(), CollectionTools.bag(map2.values()).hashCode()); + assertEquals(CollectionTools.hashBag(values).hashCode(), CollectionTools.hashBag(map2.values()).hashCode()); } public void testValues_removeAll() { @@ -763,7 +774,7 @@ public class TightMapTests Collection values2 = map2.values(); assertTrue(values2.removeAll(remove)); - assertEquals(CollectionTools.bag(values2), CollectionTools.bag(values)); + assertEquals(CollectionTools.hashBag(values2), CollectionTools.hashBag(values)); } public void testValues_add() { @@ -821,7 +832,7 @@ public class TightMapTests Collection values2 = map2.values(); assertTrue(values2.retainAll(retain)); - assertEquals(CollectionTools.bag(values2), CollectionTools.bag(values)); + assertEquals(CollectionTools.hashBag(values2), CollectionTools.hashBag(values)); } public void testValues_toArray() { @@ -1017,12 +1028,58 @@ public class TightMapTests assertTrue(exCaught); } + public void testEntrySet_iterator_entry_setValueObject() { + assertEquals(6, this.map.size()); + assertTrue(this.map.containsKey("2")); + assertTrue(this.map.containsValue("two")); + Set> entrySet = this.map.entrySet(); + assertEquals(6, entrySet.size()); + for (Iterator> stream = entrySet.iterator(); stream.hasNext(); ) { + Map.Entry entry = stream.next(); + if (ObjectTools.equals(entry.getKey(), "2")) { + entry.setValue("XXX"); + } + } + assertEquals(6, entrySet.size()); + assertTrue(this.map.containsKey("2")); + assertFalse(this.map.containsValue("two")); + assertEquals("XXX", this.map.get("2")); + assertTrue(this.map.containsValue("XXX")); + assertEquals(6, this.map.size()); + } + + public void testEntrySet_iterator_entry_equalsObject() { + assertEquals(6, this.map.size()); + assertTrue(this.map.containsKey("2")); + assertTrue(this.map.containsValue("two")); + Set> entrySet = this.map.entrySet(); + assertEquals(6, entrySet.size()); + for (Iterator> stream = entrySet.iterator(); stream.hasNext(); ) { + Map.Entry entry = stream.next(); + if (ObjectTools.equals(entry.getKey(), "2")) { + assertFalse(entry.equals("XXX")); + } + } + } + + public void testEntrySet_iterator_entry_equalsObject2() { + Map map1 = new TightMap(); + map1.put("foo", "bar"); + Map map2 = new TightMap(); + map2.put("foo", "XXX"); + Set> entrySet1 = map1.entrySet(); + Set> entrySet2 = map2.entrySet(); + Map.Entry entry1 = entrySet1.iterator().next(); + Map.Entry entry2 = entrySet2.iterator().next(); + assertFalse(entry1.equals(entry2)); + } + public void testEntrySet_size() { Set> entrySet = this.map.entrySet(); assertEquals(6, entrySet.size()); } - public void testEntrySet_contains() { + public void testEntrySet_contains1() { Set> entrySet = this.map.entrySet(); HashMap map2 = new HashMap(); this.populateMap(map2); @@ -1031,6 +1088,26 @@ public class TightMapTests } } + public void testEntrySet_contains2() { + Set> entrySet = this.map.entrySet(); + HashMap map2 = new HashMap(); + this.populateMap(map2); + map2.put("xxx", "XXX"); + for (Map.Entry entry : map2.entrySet()) { + String key = entry.getKey(); + if ((key != null) && key.equals("xxx")) { + assertFalse(entrySet.contains(entry)); + } else { + assertTrue(entrySet.contains(entry)); + } + } + } + + public void testEntrySet_contains3() { + Set> entrySet = this.map.entrySet(); + assertFalse(entrySet.contains("XXX")); + } + @SuppressWarnings("null") public void testEntrySet_remove1() { Set> entrySet = this.map.entrySet(); @@ -1063,6 +1140,20 @@ public class TightMapTests assertEquals(6, this.map.size()); } + public void testEntrySet_remove3() { + Map map1 = new TightMap(); + Set> entrySet1 = map1.entrySet(); + + Map map2 = new TightMap(); + map2.put("foo", "FOO"); + Set> entrySet2 = map2.entrySet(); + Map.Entry entry2 = entrySet2.iterator().next(); + + assertFalse(entrySet1.remove(entry2)); + map1.put("foo", "XXX"); + assertFalse(entrySet1.remove(entry2)); + } + public void testEntrySet_clear() { assertEquals(6, this.map.size()); Set> entrySet = this.map.entrySet(); @@ -1076,14 +1167,14 @@ public class TightMapTests Set> entrySet = this.map.entrySet(); HashMap map2 = new HashMap(); this.populateMap(map2); - assertTrue(CollectionTools.bag(entrySet).equals(CollectionTools.bag(map2.entrySet()))); + assertTrue(CollectionTools.hashBag(entrySet).equals(CollectionTools.hashBag(map2.entrySet()))); } public void testEntrySet_hashCode() { Set> entrySet = this.map.entrySet(); HashMap map2 = new HashMap(); this.populateMap(map2); - assertEquals(CollectionTools.bag(entrySet).hashCode(), CollectionTools.bag(map2.entrySet()).hashCode()); + assertEquals(CollectionTools.hashBag(entrySet).hashCode(), CollectionTools.hashBag(map2.entrySet()).hashCode()); } public void testEntrySet_removeAll() { @@ -1106,7 +1197,7 @@ public class TightMapTests assertTrue(entrySet.removeAll(remove)); assertTrue(entrySet2.removeAll(remove)); - assertEquals(CollectionTools.bag(entrySet2), CollectionTools.bag(entrySet)); + assertEquals(CollectionTools.hashBag(entrySet2), CollectionTools.hashBag(entrySet)); } public void testEntrySet_add() { @@ -1198,7 +1289,7 @@ public class TightMapTests Set> entrySet = this.map.entrySet(); assertTrue(entrySet.retainAll(retain)); assertTrue(entrySet2.retainAll(retain)); - assertEquals(CollectionTools.bag(entrySet2), CollectionTools.bag(entrySet)); + assertEquals(CollectionTools.hashBag(entrySet2), CollectionTools.hashBag(entrySet)); } public void testEntrySet_toArray() { @@ -1287,6 +1378,17 @@ public class TightMapTests assertTrue(this.map.equals(map2)); } + public void testEquals7() { + TightMap map1 = new TightMap(); + map1.put("null", null); + HashMap map2 = new HashMap(); + assertFalse(map1.equals(map2)); + map2.put("null", "null"); + assertFalse(map1.equals(map2)); + map2.put("null", null); + assertTrue(map1.equals(map2)); + } + public void testHashCode1() { HashMap map2 = new HashMap(); this.populateMap(map2); diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/AbstractPriorityDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/AbstractPriorityDequeTests.java new file mode 100644 index 0000000000..7a47c60eec --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/AbstractPriorityDequeTests.java @@ -0,0 +1,370 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.Comparator; +import java.util.NoSuchElementException; +import java.util.Random; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.deque.AbstractPriorityDeque; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public abstract class AbstractPriorityDequeTests + extends TestCase +{ + public AbstractPriorityDequeTests(String name) { + super(name); + } + + abstract > AbstractPriorityDeque buildDeque(); + + abstract > AbstractPriorityDeque buildDeque(int capacity); + + abstract > AbstractPriorityDeque buildDeque(Comparator comparator, int capacity); + + public void testIsEmpty_head() { + AbstractPriorityDeque deque = this.buildDeque(); + assertTrue(deque.isEmpty()); + deque.enqueue("first"); + assertFalse(deque.isEmpty()); + deque.enqueue("second"); + assertFalse(deque.isEmpty()); + deque.dequeueHead(); + assertFalse(deque.isEmpty()); + deque.dequeueHead(); + assertTrue(deque.isEmpty()); + } + + public void testIsEmpty_tail() { + AbstractPriorityDeque deque = this.buildDeque(); + assertTrue(deque.isEmpty()); + deque.enqueue("first"); + assertFalse(deque.isEmpty()); + deque.enqueue("second"); + assertFalse(deque.isEmpty()); + deque.dequeueTail(); + assertFalse(deque.isEmpty()); + deque.dequeueTail(); + assertTrue(deque.isEmpty()); + } + + public void testEnqueueAndDequeueHead() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueueTail(second); + assertEquals(first, deque.dequeueHead()); + assertEquals(second, deque.dequeueHead()); + } + + public void testEnqueueAndDequeueTail() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueue(second); + assertEquals(second, deque.dequeueTail()); + assertEquals(first, deque.dequeueTail()); + } + + public void testEnqueueAndPeekHead() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueue(second); + assertEquals(first, deque.peekHead()); + assertEquals(first, deque.peekHead()); + assertEquals(first, deque.dequeueHead()); + assertEquals(second, deque.peekHead()); + assertEquals(second, deque.peekHead()); + assertEquals(second, deque.dequeueHead()); + } + + public void testEnqueueAndPeekTail() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + String third = "third"; + String zzzz = "zzzz"; + + deque.enqueue(second); + deque.enqueue(zzzz); + deque.enqueue(third); + deque.enqueue(first); + assertEquals(zzzz, deque.peekTail()); + assertEquals(zzzz, deque.peekTail()); + assertEquals(zzzz, deque.dequeueTail()); + assertEquals(third, deque.peekTail()); + assertEquals(third, deque.peekTail()); + assertEquals(third, deque.dequeueTail()); + assertEquals(second, deque.peekTail()); + assertEquals(second, deque.peekTail()); + assertEquals(second, deque.dequeueTail()); + assertEquals(first, deque.peekTail()); + assertEquals(first, deque.peekTail()); + assertEquals(first, deque.dequeueTail()); + } + + public void testEmptyQueueExceptionPeekHead() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueue(second); + assertEquals(first, deque.peekHead()); + assertEquals(first, deque.dequeueHead()); + assertEquals(second, deque.peekHead()); + assertEquals(second, deque.dequeueHead()); + + boolean exCaught = false; + try { + deque.peekHead(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyQueueExceptionPeekTail() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueue(second); + assertEquals(second, deque.peekTail()); + assertEquals(second, deque.dequeueTail()); + assertEquals(first, deque.peekTail()); + assertEquals(first, deque.dequeueTail()); + + boolean exCaught = false; + try { + deque.peekTail(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyQueueExceptionDequeueHead() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueue(second); + assertEquals(first, deque.peekHead()); + assertEquals(first, deque.dequeueHead()); + assertEquals(second, deque.peekHead()); + assertEquals(second, deque.dequeueHead()); + + boolean exCaught = false; + try { + deque.dequeueHead(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyQueueExceptionDequeueTail() { + AbstractPriorityDeque deque = this.buildDeque(); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueue(second); + assertEquals(second, deque.peekTail()); + assertEquals(second, deque.dequeueTail()); + assertEquals(first, deque.peekTail()); + assertEquals(first, deque.dequeueTail()); + + boolean exCaught = false; + try { + deque.dequeueTail(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testClone() { + AbstractPriorityDeque deque = this.buildDeque(); + deque.enqueue("first"); + deque.enqueue("second"); + deque.enqueue("third"); + + @SuppressWarnings("unchecked") + AbstractPriorityDeque clone = (AbstractPriorityDeque) ObjectTools.execute(deque, "clone"); + this.verifyClone(deque, clone); + } + + public void testSerialization() throws Exception { + AbstractPriorityDeque deque = this.buildDeque(); + deque.enqueue("first"); + deque.enqueue("second"); + deque.enqueue("third"); + + this.verifyClone(deque, TestTools.serialize(deque)); + } + + protected void verifyClone(AbstractPriorityDeque original, AbstractPriorityDeque clone) { + assertNotSame(original, clone); + assertEquals(original.peekHead(), clone.peekHead()); + assertEquals(original.dequeueHead(), clone.dequeueHead()); + assertEquals(original.peekTail(), clone.peekTail()); + assertEquals(original.dequeueTail(), clone.dequeueTail()); + assertEquals(original.isEmpty(), clone.isEmpty()); + assertEquals(original.peekHead(), clone.peekHead()); + assertEquals(original.dequeueHead(), clone.dequeueHead()); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testToString() throws Exception { + AbstractPriorityDeque deque = this.buildDeque(); + assertEquals("[]", deque.toString()); + deque.enqueue("first"); + assertEquals("[first]", deque.toString()); + deque.enqueue("second"); + assertEquals("[first, second]", deque.toString()); + deque.enqueue("third"); + assertEquals("[first, second, third]", deque.toString()); + } + + public void testMultipleSizes() throws Exception { + int maxSize = 50; + Random random = new Random(); + for (int size = 1; size <= maxSize; size++) { + int[] values = new int[size]; + for (int i = 0; i < values.length; i++) { + values[i] = random.nextInt(); + } + AbstractPriorityDeque deque = this.buildDeque(size); + for (int value : values) { + deque.enqueue(Integer.valueOf(value)); + } + Integer currentHead = deque.dequeueHead(); + int i = 1; + Integer currentTail = null; + if ( ! deque.isEmpty()) { + currentTail = deque.dequeueTail(); + i++; + } + do { + if ( ! deque.isEmpty()) { + Integer nextHead = deque.dequeueHead(); + i++; + assertTrue(currentHead.intValue() <= nextHead.intValue()); + currentHead = nextHead; + } + if ( ! deque.isEmpty()) { + Integer nextTail = deque.dequeueTail(); + i++; + assertTrue((currentTail != null) && (currentTail.intValue() >= nextTail.intValue())); + currentTail = nextTail; + } + } while ( ! deque.isEmpty()); + assertEquals(size, i); + } + } + + public void testSomethingBig() throws Exception { + int size = 500000; + AbstractPriorityDeque deque = this.buildDeque(size); + Random random = new Random(); + for (int i = size; i-- > 0; ) { + deque.enqueue(Integer.valueOf(random.nextInt())); + } + Integer currentHead = deque.dequeueHead(); + int i = 1; + Integer currentTail = null; + if ( ! deque.isEmpty()) { + currentTail = deque.dequeueTail(); + i++; + } + do { + if ( ! deque.isEmpty()) { + Integer nextHead = deque.dequeueHead(); + i++; + assertTrue(currentHead.intValue() <= nextHead.intValue()); + currentHead = nextHead; + } + if ( ! deque.isEmpty()) { + Integer nextTail = deque.dequeueTail(); + i++; + assertTrue((currentTail != null) && (currentTail.intValue() >= nextTail.intValue())); + currentTail = nextTail; + } + } while ( ! deque.isEmpty()); + assertEquals(size, i); + } + + public void testConstructor_nullComparator() throws Exception { + boolean exCaught = false; + try { + AbstractPriorityDeque deque = this.buildDeque(null, 3); + fail("bogus deque: " + deque); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructor_negativeCapacity() throws Exception { + boolean exCaught = false; + try { + AbstractPriorityDeque deque = this.buildDeque(-7); + fail("bogus deque: " + deque); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSerialization_fullArray() throws Exception { + AbstractPriorityDeque deque = this.buildDeque(3); + deque.enqueue("first"); + deque.enqueue("second"); + deque.enqueue("third"); + + this.verifyClone(deque, TestTools.serialize(deque)); + } + + public void testSerialization_empty() throws Exception { + AbstractPriorityDeque original = this.buildDeque(); + AbstractPriorityDeque clone = TestTools.serialize(original); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("foo"); + 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/deque/ArrayDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ArrayDequeTests.java new file mode 100644 index 0000000000..24b318bf43 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ArrayDequeTests.java @@ -0,0 +1,366 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.deque.ArrayDeque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class ArrayDequeTests + extends DequeTests +{ + public ArrayDequeTests(String name) { + super(name); + } + + @Override + Deque buildDeque() { + return DequeTools.arrayDeque(); + } + + public void testConstructor_IAE() { + boolean exCaught = false; + try { + Deque queue = DequeTools.arrayDeque(-1); + fail("bogus deque: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEnsureCapacity() { + ArrayDeque queue = DequeTools.arrayDeque(0); + queue.ensureCapacity(7); + assertEquals(7, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testTrimToSize() { + ArrayDeque queue = DequeTools.arrayDeque(10); + queue.enqueueTail("foo"); + queue.enqueueTail("bar"); + queue.trimToSize(); + assertEquals(2, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testTrimToSize_noChange() { + ArrayDeque queue = DequeTools.arrayDeque(2); + queue.enqueueTail("foo"); + queue.enqueueTail("bar"); + queue.trimToSize(); + assertEquals(2, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testCollectionConstructor() { + ArrayList c = new ArrayList(); + c.add("first"); + c.add("second"); + c.add("third"); + c.add("fourth"); + c.add("fifth"); + c.add("sixth"); + c.add("seventh"); + c.add("eighth"); + c.add("ninth"); + c.add("tenth"); // force some free space + Deque queue = DequeTools.arrayDeque(c); + + assertFalse(queue.isEmpty()); + assertEquals("first", queue.peekHead()); + queue.enqueueTail("eleventh"); + queue.enqueueTail("twelfth"); + + assertEquals("first", queue.peekHead()); + assertEquals("first", queue.dequeueHead()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.peekHead()); + assertEquals("third", queue.dequeueHead()); + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertEquals("eleventh", queue.dequeueHead()); + assertEquals("twelfth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testWrappedElementsTail() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("third"); + queue.enqueueTail("fourth"); + queue.enqueueTail("fifth"); + queue.enqueueTail("sixth"); + + // make room for 11 and 12 + assertEquals("first", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueHead()); + + queue.enqueueTail("seventh"); + queue.enqueueTail("eighth"); + queue.enqueueTail("ninth"); + queue.enqueueTail("tenth"); + queue.enqueueTail("eleventh"); + queue.enqueueTail("twelfth"); + + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertEquals("eleventh", queue.dequeueHead()); + assertEquals("twelfth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testWrappedElementsHead() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueHead("first"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("third"); + queue.enqueueHead("fourth"); + queue.enqueueHead("fifth"); + queue.enqueueHead("sixth"); + + // make room for 11 and 12 + assertEquals("first", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueTail()); + + queue.enqueueHead("seventh"); + queue.enqueueHead("eighth"); + queue.enqueueHead("ninth"); + queue.enqueueHead("tenth"); + queue.enqueueHead("eleventh"); + queue.enqueueHead("twelfth"); + + assertEquals("fourth", queue.dequeueTail()); + assertEquals("fifth", queue.dequeueTail()); + assertEquals("sixth", queue.dequeueTail()); + assertEquals("seventh", queue.dequeueTail()); + assertEquals("eighth", queue.dequeueTail()); + assertEquals("ninth", queue.dequeueTail()); + assertEquals("tenth", queue.dequeueTail()); + assertEquals("eleventh", queue.dequeueTail()); + assertEquals("twelfth", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededTail() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("third"); + queue.enqueueTail("fourth"); + queue.enqueueTail("fifth"); + queue.enqueueTail("sixth"); + queue.enqueueTail("seventh"); + queue.enqueueTail("eighth"); + queue.enqueueTail("ninth"); + queue.enqueueTail("tenth"); + queue.enqueueTail("eleventh"); + queue.enqueueTail("twelfth"); + + assertEquals("first", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueHead()); + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertEquals("eleventh", queue.dequeueHead()); + assertEquals("twelfth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededHead() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueHead("first"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("third"); + queue.enqueueHead("fourth"); + queue.enqueueHead("fifth"); + queue.enqueueHead("sixth"); + queue.enqueueHead("seventh"); + queue.enqueueHead("eighth"); + queue.enqueueHead("ninth"); + queue.enqueueHead("tenth"); + queue.enqueueHead("eleventh"); + queue.enqueueHead("twelfth"); + + assertEquals("first", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueTail()); + assertEquals("fourth", queue.dequeueTail()); + assertEquals("fifth", queue.dequeueTail()); + assertEquals("sixth", queue.dequeueTail()); + assertEquals("seventh", queue.dequeueTail()); + assertEquals("eighth", queue.dequeueTail()); + assertEquals("ninth", queue.dequeueTail()); + assertEquals("tenth", queue.dequeueTail()); + assertEquals("eleventh", queue.dequeueTail()); + assertEquals("twelfth", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededWithWrappedElementsTail() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("third"); + queue.enqueueTail("fourth"); + queue.enqueueTail("fifth"); + queue.enqueueTail("sixth"); + + assertEquals("first", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueHead()); + + queue.enqueueTail("seventh"); + queue.enqueueTail("eighth"); + queue.enqueueTail("ninth"); + queue.enqueueTail("tenth"); + queue.enqueueTail("eleventh"); + queue.enqueueTail("twelfth"); + queue.enqueueTail("thirteenth"); + queue.enqueueTail("fourteenth"); + queue.enqueueTail("fifteenth"); + + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertEquals("eleventh", queue.dequeueHead()); + assertEquals("twelfth", queue.dequeueHead()); + assertEquals("thirteenth", queue.dequeueHead()); + assertEquals("fourteenth", queue.dequeueHead()); + assertEquals("fifteenth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededWithWrappedElementsHead() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueHead("first"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("third"); + queue.enqueueHead("fourth"); + queue.enqueueHead("fifth"); + queue.enqueueHead("sixth"); + + assertEquals("first", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueTail()); + + queue.enqueueHead("seventh"); + queue.enqueueHead("eighth"); + queue.enqueueHead("ninth"); + queue.enqueueHead("tenth"); + queue.enqueueHead("eleventh"); + queue.enqueueHead("twelfth"); + queue.enqueueHead("thirteenth"); + queue.enqueueHead("fourteenth"); + queue.enqueueHead("fifteenth"); + + assertEquals("fourth", queue.dequeueTail()); + assertEquals("fifth", queue.dequeueTail()); + assertEquals("sixth", queue.dequeueTail()); + assertEquals("seventh", queue.dequeueTail()); + assertEquals("eighth", queue.dequeueTail()); + assertEquals("ninth", queue.dequeueTail()); + assertEquals("tenth", queue.dequeueTail()); + assertEquals("eleventh", queue.dequeueTail()); + assertEquals("twelfth", queue.dequeueTail()); + assertEquals("thirteenth", queue.dequeueTail()); + assertEquals("fourteenth", queue.dequeueTail()); + assertEquals("fifteenth", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testSerialization_empty() throws Exception { + Deque original = new ArrayDeque(3); + Deque clone = TestTools.serialize(original); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueueTail("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testSerialization_fullArray() throws Exception { + Deque queue = new ArrayDeque(3); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + public void testSerialization_wrappedArray() throws Exception { + Deque queue = new ArrayDeque(3); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + queue.dequeueHead(); + queue.enqueueTail("fourth"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeTests.java new file mode 100644 index 0000000000..cbdf7976e9 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeTests.java @@ -0,0 +1,290 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +// subclass MultiThreadedTestCase for subclasses of this class +@SuppressWarnings("nls") +public abstract class DequeTests + extends MultiThreadedTestCase +{ + public DequeTests(String name) { + super(name); + } + + abstract Deque buildDeque(); + + public void testIsEmpty() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("zero"); + assertFalse(queue.isEmpty()); + queue.dequeueHead(); + assertFalse(queue.isEmpty()); + queue.dequeueHead(); + assertFalse(queue.isEmpty()); + queue.dequeueTail(); + assertTrue(queue.isEmpty()); + } + + public void testEnqueueTailAndDequeueHead() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueTail(first); + queue.enqueueTail(second); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.dequeueHead()); + } + + public void testEnqueueHeadAndDequeueTail() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueHead(first); + queue.enqueueHead(second); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.dequeueTail()); + } + + public void testEnqueueAndDequeue() { + Deque queue = this.buildDeque(); + String negative = "negative"; + String zero = "zero"; + String first = "first"; + String second = "second"; + + queue.enqueueTail(first); + queue.enqueueTail(second); + queue.enqueueHead(zero); + queue.enqueueHead(negative); + assertEquals(negative, queue.dequeueHead()); + assertEquals(second, queue.dequeueTail()); + assertEquals(zero, queue.dequeueHead()); + assertEquals(first, queue.dequeueTail()); + + assertTrue(queue.isEmpty()); + } + + public void testEnqueueTailAndPeekHead() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueTail(first); + queue.enqueueTail(second); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.dequeueHead()); + } + + public void testEnqueueHeadAndPeekTail() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueHead(first); + queue.enqueueHead(second); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.dequeueTail()); + } + + public void testEnqueueAndPeek() { + Deque queue = this.buildDeque(); + String negative = "negative"; + String zero = "zero"; + String first = "first"; + String second = "second"; + + queue.enqueueTail(first); + queue.enqueueTail(second); + queue.enqueueHead(zero); + queue.enqueueHead(negative); + assertEquals(negative, queue.peekHead()); + assertEquals(negative, queue.peekHead()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.peekTail()); + + assertEquals(negative, queue.dequeueHead()); + assertEquals(zero, queue.peekHead()); + assertEquals(zero, queue.peekHead()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.peekTail()); + + assertEquals(second, queue.dequeueTail()); + assertEquals(zero, queue.peekHead()); + assertEquals(first, queue.peekTail()); + + assertEquals(first, queue.dequeueTail()); + assertEquals(zero, queue.peekHead()); + assertEquals(zero, queue.peekTail()); + + assertEquals(zero, queue.dequeueTail()); + + assertTrue(queue.isEmpty()); + } + + public void testEmptyDequeExceptionPeekHead() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueTail(first); + queue.enqueueTail(second); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.dequeueHead()); + + boolean exCaught = false; + try { + queue.peekHead(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyDequeExceptionPeekTail() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueHead(first); + queue.enqueueHead(second); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.dequeueTail()); + + boolean exCaught = false; + try { + queue.peekTail(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyDequeExceptionDequeueHead() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueTail(first); + queue.enqueueTail(second); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.dequeueHead()); + + boolean exCaught = false; + try { + queue.dequeueHead(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyDequeExceptionDequeueTail() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + queue.enqueueHead(first); + queue.enqueueHead(second); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.dequeueTail()); + + boolean exCaught = false; + try { + queue.dequeueTail(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testClone() { + Deque queue = this.buildDeque(); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + + @SuppressWarnings("unchecked") + Deque clone = (Deque) ObjectTools.execute(queue, "clone"); + this.verifyClone(queue, clone); + } + + public void testSerialization() throws Exception { + Deque queue = this.buildDeque(); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + protected void verifyClone(Deque original, Deque clone) { + assertNotSame(original, clone); + assertEquals(original.peekHead(), clone.peekHead()); + assertEquals(original.dequeueHead(), clone.dequeueHead()); + assertEquals(original.peekHead(), clone.peekHead()); + assertEquals(original.dequeueHead(), clone.dequeueHead()); + assertEquals(original.isEmpty(), clone.isEmpty()); + assertEquals(original.peekTail(), clone.peekTail()); + assertEquals(original.dequeueTail(), clone.dequeueTail()); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueueTail("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testToString() throws Exception { + Deque queue = this.buildDeque(); + assertEquals("[]", queue.toString()); + queue.enqueueTail("first"); + assertEquals("[first]", queue.toString()); + queue.enqueueTail("second"); + assertEquals("[first, second]", queue.toString()); + queue.enqueueTail("third"); + assertEquals("[first, second, third]", queue.toString()); + queue.enqueueHead("foo"); + assertEquals("[foo, first, second, third]", queue.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeToolsTests.java new file mode 100644 index 0000000000..c30026bf69 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/DequeToolsTests.java @@ -0,0 +1,832 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.ClassTools; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.StringTools; +import org.eclipse.jpt.common.utility.internal.comparator.ComparatorTools; +import org.eclipse.jpt.common.utility.internal.deque.ArrayDeque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.LinkedDeque; +import org.eclipse.jpt.common.utility.internal.deque.PriorityDeque; +import org.eclipse.jpt.common.utility.internal.deque.SynchronizedDeque; +import org.eclipse.jpt.common.utility.internal.queue.ArrayQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.stack.ArrayStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.transformer.Transformer; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class DequeToolsTests + extends TestCase +{ + public DequeToolsTests(String name) { + super(name); + } + + // ********** enqueue all ********** + + public void testEnqueueTailAllIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertTrue(DequeTools.enqueueTailAll(deque, iterable)); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testEnqueueTailAllIterable_empty() { + ArrayList iterable = new ArrayList(); + Deque deque = DequeTools.arrayDeque(); + assertFalse(DequeTools.enqueueTailAll(deque, iterable)); + assertTrue(deque.isEmpty()); + } + + public void testEnqueueHeadAllIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertTrue(DequeTools.enqueueHeadAll(deque, iterable)); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testEnqueueHeadAllIterable_empty() { + ArrayList iterable = new ArrayList(); + Deque deque = DequeTools.arrayDeque(); + assertFalse(DequeTools.enqueueHeadAll(deque, iterable)); + assertTrue(deque.isEmpty()); + } + + public void testEnqueueTailAllIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertTrue(DequeTools.enqueueTailAll(deque, iterable.iterator())); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testEnqueueHeadAllIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertTrue(DequeTools.enqueueHeadAll(deque, iterable.iterator())); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testEnqueueTailAllArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertTrue(DequeTools.enqueueTailAll(deque, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testEnqueueTailAllArray_empty() { + ArrayList iterable = new ArrayList(); + Deque deque = DequeTools.arrayDeque(); + assertFalse(DequeTools.enqueueTailAll(deque, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertTrue(deque.isEmpty()); + } + + public void testEnqueueHeadAllArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertTrue(DequeTools.enqueueHeadAll(deque, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testEnqueueHeadAllArray_empty() { + ArrayList iterable = new ArrayList(); + Deque deque = DequeTools.arrayDeque(); + assertFalse(DequeTools.enqueueHeadAll(deque, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertTrue(deque.isEmpty()); + } + + + // ********** drain ********** + + public void testDrainHead() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayList list = DequeTools.drainHead(d); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainTail() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayList list = DequeTools.drainTail(d); + assertEquals("one", list.get(2)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(0)); + } + + public void testDrainHeadToCollection() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayList list = new ArrayList(); + assertTrue(DequeTools.drainHeadTo(d, list)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainHeadToCollection_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayList list = new ArrayList(); + assertFalse(DequeTools.drainHeadTo(d, list)); + assertTrue(list.isEmpty()); + } + + public void testDrainTailToCollection() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayList list = new ArrayList(); + assertTrue(DequeTools.drainTailTo(d, list)); + assertEquals("one", list.get(2)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(0)); + } + + public void testDrainTailToCollection_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayList list = new ArrayList(); + assertFalse(DequeTools.drainTailTo(d, list)); + assertTrue(list.isEmpty()); + } + + public void testDrainHeadToListIndex() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Deque deque = DequeTools.arrayDeque(); + deque.enqueueTail("aaa"); + deque.enqueueTail("bbb"); + deque.enqueueTail("ccc"); + assertTrue(DequeTools.drainHeadTo(deque, list, 2)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("aaa", list.get(2)); + assertEquals("bbb", list.get(3)); + assertEquals("ccc", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testDrainHeadToListIndex_end() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Deque deque = DequeTools.arrayDeque(); + deque.enqueueTail("aaa"); + deque.enqueueTail("bbb"); + deque.enqueueTail("ccc"); + assertTrue(DequeTools.drainHeadTo(deque, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + assertEquals("aaa", list.get(3)); + assertEquals("bbb", list.get(4)); + assertEquals("ccc", list.get(5)); + } + + public void testDrainHeadToListIndex_empty() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertFalse(DequeTools.drainHeadTo(deque, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainTailToListIndex() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Deque deque = DequeTools.arrayDeque(); + deque.enqueueTail("aaa"); + deque.enqueueTail("bbb"); + deque.enqueueTail("ccc"); + assertTrue(DequeTools.drainTailTo(deque, list, 2)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("ccc", list.get(2)); + assertEquals("bbb", list.get(3)); + assertEquals("aaa", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testDrainTailToListIndex_end() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Deque deque = DequeTools.arrayDeque(); + deque.enqueueTail("aaa"); + deque.enqueueTail("bbb"); + deque.enqueueTail("ccc"); + assertTrue(DequeTools.drainTailTo(deque, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + assertEquals("ccc", list.get(3)); + assertEquals("bbb", list.get(4)); + assertEquals("aaa", list.get(5)); + } + + public void testDrainTailToListIndex_empty() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Deque deque = DequeTools.arrayDeque(); + assertFalse(DequeTools.drainTailTo(deque, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainHeadToStack() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayStack stack = StackTools.arrayStack(); + assertTrue(DequeTools.drainHeadTo(d, stack)); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testDrainHeadToStack_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayStack stack = StackTools.arrayStack(); + assertFalse(DequeTools.drainHeadTo(d, stack)); + assertTrue(stack.isEmpty()); + } + + public void testDrainTailToStack() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayStack stack = StackTools.arrayStack(); + assertTrue(DequeTools.drainTailTo(d, stack)); + assertEquals("one", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("three", stack.pop()); + } + + public void testDrainTailToStack_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayStack stack = StackTools.arrayStack(); + assertFalse(DequeTools.drainTailTo(d, stack)); + assertTrue(stack.isEmpty()); + } + + public void testDrainHeadToQueue() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayQueue queue = QueueTools.arrayQueue(); + assertTrue(DequeTools.drainHeadTo(d, queue)); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testDrainHeadToQueue_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayQueue queue = QueueTools.arrayQueue(); + assertFalse(DequeTools.drainHeadTo(d, queue)); + assertTrue(queue.isEmpty()); + } + + public void testDrainTailToQueue() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayQueue queue = QueueTools.arrayQueue(); + assertTrue(DequeTools.drainTailTo(d, queue)); + assertEquals("three", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("one", queue.dequeue()); + } + + public void testDrainTailToQueue_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayQueue queue = QueueTools.arrayQueue(); + assertFalse(DequeTools.drainTailTo(d, queue)); + assertTrue(queue.isEmpty()); + } + + public void testDrainHeadToDeque() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayDeque d2 = DequeTools.arrayDeque(); + assertTrue(DequeTools.drainHeadTo(d, d2)); + assertEquals("one", d2.dequeueHead()); + assertEquals("two", d2.dequeueHead()); + assertEquals("three", d2.dequeueHead()); + } + + public void testDrainHeadToDeque_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayDeque d2 = DequeTools.arrayDeque(); + assertFalse(DequeTools.drainHeadTo(d, d2)); + assertTrue(d2.isEmpty()); + } + + public void testDrainTailToDeque() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("one"); + d.enqueueTail("two"); + d.enqueueTail("three"); + ArrayDeque d2 = DequeTools.arrayDeque(); + assertTrue(DequeTools.drainTailTo(d, d2)); + assertEquals("one", d2.dequeueHead()); + assertEquals("two", d2.dequeueHead()); + assertEquals("three", d2.dequeueHead()); + } + + public void testDrainTailToDeque_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + ArrayDeque d2 = DequeTools.arrayDeque(); + assertFalse(DequeTools.drainTailTo(d, d2)); + assertTrue(d2.isEmpty()); + } + + public void testDrainHeadToMapTransformer() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("zero"); + d.enqueueTail("one"); + d.enqueueTail("two"); + Mapmap = new HashMap(); + assertTrue(DequeTools.drainHeadTo(d, map, FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testDrainHeadToMapTransformer_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + Mapmap = new HashMap(); + assertFalse(DequeTools.drainHeadTo(d, map, FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testDrainTailToMapTransformer() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("zero"); + d.enqueueTail("one"); + d.enqueueTail("two"); + Mapmap = new HashMap(); + assertTrue(DequeTools.drainTailTo(d, map, FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testDrainTailToMapTransformer_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + Mapmap = new HashMap(); + assertFalse(DequeTools.drainTailTo(d, map, FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testDrainHeadToMapTransformerTransformer() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("zero"); + d.enqueueTail("one"); + d.enqueueTail("two"); + Mapmap = new HashMap(); + assertTrue(DequeTools.drainHeadTo(d, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testDrainHeadToMapTransformerTransformer_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + Mapmap = new HashMap(); + assertFalse(DequeTools.drainHeadTo(d, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertTrue(map.isEmpty()); + } + + public void testDrainTailToMapTransformerTransformer() { + ArrayDeque d = DequeTools.arrayDeque(); + d.enqueueTail("zero"); + d.enqueueTail("one"); + d.enqueueTail("two"); + Mapmap = new HashMap(); + assertTrue(DequeTools.drainTailTo(d, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testDrainTailToMapTransformerTransformer_empty() { + ArrayDeque d = DequeTools.arrayDeque(); + Mapmap = new HashMap(); + assertFalse(DequeTools.drainTailTo(d, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertTrue(map.isEmpty()); + } + + public static final Transformer FIRST_LETTER_TRANSFORMER = new FirstLetterTransformer(); + + /* CU private */ static class FirstLetterTransformer + implements Transformer + { + public String transform(String string) { + return string.substring(0, 1); + } + @Override + public String toString() { + return this.getClass().getSimpleName(); + } + } + + public static final Transformer EMPHASIZER = new StringTools.CharDelimiter('*'); + + + // ********** array deque ********** + + public void testArrayDeque() { + ArrayDeque d = DequeTools.arrayDeque(); + assertTrue(d.isEmpty()); + } + + public void testArrayDequeInt() { + ArrayDeque d = DequeTools.arrayDeque(20); + assertTrue(d.isEmpty()); + assertEquals(20, ((Object[]) ObjectTools.get(d, "elements")).length); + } + + public void testArrayDequeIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(iterable); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testArrayDequeIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(iterable, 5); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseArrayDequeIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseArrayDeque(iterable); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testReverseArrayDequeIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseArrayDeque(iterable, 77); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testArrayDequeIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(iterable.iterator()); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testArrayDequeIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(iterable.iterator(), 5); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseArrayDequeIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseArrayDeque(iterable.iterator()); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testReverseArrayDequeIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseArrayDeque(iterable.iterator(), 42); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testArrayDequeArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.arrayDeque(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseArrayDequeArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseArrayDeque(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + // ********** linked deque ********** + + public void testLinkedDeque() { + LinkedDeque d = DequeTools.linkedDeque(); + assertTrue(d.isEmpty()); + } + + public void testLinkedDequeInt() { + LinkedDeque d = DequeTools.linkedDeque(20); + assertTrue(d.isEmpty()); + } + + public void testLinkedDequeIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.linkedDeque(iterable); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testLinkedDequeIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.linkedDeque(iterable, 5); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseLinkedDequeIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseLinkedDeque(iterable); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testReverseLinkedDequeIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseLinkedDeque(iterable, 77); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testLinkedDequeIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.linkedDeque(iterable.iterator()); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testLinkedDequeIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.linkedDeque(iterable.iterator(), 5); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseLinkedDequeIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseLinkedDeque(iterable.iterator()); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testReverseLinkedDequeIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseLinkedDeque(iterable.iterator(), 42); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + public void testLinkedDequeArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.linkedDeque(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseLinkedDequeArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseLinkedDeque(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("one", deque.dequeueTail()); + assertEquals("two", deque.dequeueTail()); + assertEquals("three", deque.dequeueTail()); + } + + // ********** fixed-capacity array deque ********** + + public void testFixedCapacityArrayDequeCollection() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.fixedCapacityArrayDeque(iterable); + assertEquals("one", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("three", deque.dequeueHead()); + } + + public void testReverseFixedCapacityArrayDequeCollection() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Deque deque = DequeTools.reverseFixedCapacityArrayDeque(iterable); + assertEquals("three", deque.dequeueHead()); + assertEquals("two", deque.dequeueHead()); + assertEquals("one", deque.dequeueHead()); + } + + // ********** misc ********** + + public void testPriorityDequeComparator() { + PriorityDeque deque = DequeTools.priorityDeque(ComparatorTools.reverseComparator()); + String first = "first"; + String second = "second"; + + deque.enqueue(first); + deque.enqueueTail(second); + assertEquals(second, deque.dequeueHead()); + assertEquals(first, deque.dequeueHead()); + } + + public void testSynchronizedDequeObject() { + Object lock = new Object(); + SynchronizedDeque deque = DequeTools.synchronizedDeque(lock); + String first = "first"; + String second = "second"; + + deque.enqueueTail(first); + deque.enqueueTail(second); + assertEquals(first, deque.dequeueHead()); + assertEquals(second, deque.dequeueHead()); + assertEquals(lock, deque.getMutex()); + } + + public void testSynchronizedDequeDequeObject() { + Object lock = new Object(); + Deque innerDeque = DequeTools.arrayDeque(); + String first = "first"; + String second = "second"; + innerDeque.enqueueTail(first); + innerDeque.enqueueTail(second); + + SynchronizedDeque deque = DequeTools.synchronizedDeque(innerDeque, lock); + assertEquals(first, deque.dequeueHead()); + assertEquals(second, deque.dequeueHead()); + assertEquals(lock, deque.getMutex()); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ClassTools.newInstance(DequeTools.class); + fail("bogus: " + at); + } 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/deque/EmptyDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/EmptyDequeTests.java new file mode 100644 index 0000000000..0b525b0a69 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/EmptyDequeTests.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.EmptyDeque; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class EmptyDequeTests + extends TestCase +{ + public EmptyDequeTests(String name) { + super(name); + } + + public void testEnqueueTail() { + Deque deque = DequeTools.emptyDeque(); + boolean exCaught = false; + try { + deque.enqueueTail("junk"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEnqueueHead() { + Deque deque = EmptyDeque.instance(); + boolean exCaught = false; + try { + deque.enqueueHead("junk"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDequeueHead() { + Deque deque = EmptyDeque.instance(); + boolean exCaught = false; + try { + String bogus = deque.dequeueHead(); + fail(bogus); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDequeueTail() { + Deque deque = EmptyDeque.instance(); + boolean exCaught = false; + try { + String bogus = deque.dequeueTail(); + fail(bogus); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testPeekHead() { + Deque deque = EmptyDeque.instance(); + boolean exCaught = false; + try { + String bogus = deque.peekHead(); + fail(bogus); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testPeekTail() { + Deque deque = EmptyDeque.instance(); + boolean exCaught = false; + try { + String bogus = deque.peekTail(); + fail(bogus); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIsEmpty() { + Deque deque = EmptyDeque.instance(); + assertTrue(deque.isEmpty()); + } + + public void testToString() { + Deque deque = EmptyDeque.instance(); + assertEquals("[]", deque.toString()); + } + + public void testSerialization() throws Exception { + Deque deque = EmptyDeque.instance(); + assertSame(deque, TestTools.serialize(deque)); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityArrayDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityArrayDequeTests.java new file mode 100644 index 0000000000..b9014e12ad --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityArrayDequeTests.java @@ -0,0 +1,341 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.FixedCapacityArrayDeque; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class FixedCapacityArrayDequeTests + extends DequeTests +{ + public FixedCapacityArrayDequeTests(String name) { + super(name); + } + + @Override + FixedCapacityArrayDeque buildDeque() { + return this.buildDeque(10); + } + + FixedCapacityArrayDeque buildDeque(int capacity) { + return DequeTools.fixedCapacityArrayDeque(capacity); + } + + public void testInitialCapacityConstructor() { + boolean exCaught = false; + try { + Deque queue = DequeTools.arrayDeque(-1); + fail("bogus deque: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIsFull() { + FixedCapacityArrayDeque queue = this.buildDeque(3); + assertTrue(queue.isEmpty()); + assertFalse(queue.isFull()); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + assertFalse(queue.isEmpty()); + assertTrue(queue.isFull()); + } + + public void testWrappedElementsTail() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("third"); + queue.enqueueTail("fourth"); + queue.enqueueTail("fifth"); + queue.enqueueTail("sixth"); + + // make room for 11 and 12 + assertEquals("first", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueHead()); + + queue.enqueueTail("seventh"); + queue.enqueueTail("eighth"); + queue.enqueueTail("ninth"); + queue.enqueueTail("tenth"); + queue.enqueueTail("eleventh"); + queue.enqueueTail("twelfth"); + + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertEquals("eleventh", queue.dequeueHead()); + assertEquals("twelfth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testWrappedElementsHead() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueHead("first"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("third"); + queue.enqueueHead("fourth"); + queue.enqueueHead("fifth"); + queue.enqueueHead("sixth"); + + // make room for 11 and 12 + assertEquals("first", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueTail()); + + queue.enqueueHead("seventh"); + queue.enqueueHead("eighth"); + queue.enqueueHead("ninth"); + queue.enqueueHead("tenth"); + queue.enqueueHead("eleventh"); + queue.enqueueHead("twelfth"); + + assertEquals("fourth", queue.dequeueTail()); + assertEquals("fifth", queue.dequeueTail()); + assertEquals("sixth", queue.dequeueTail()); + assertEquals("seventh", queue.dequeueTail()); + assertEquals("eighth", queue.dequeueTail()); + assertEquals("ninth", queue.dequeueTail()); + assertEquals("tenth", queue.dequeueTail()); + assertEquals("eleventh", queue.dequeueTail()); + assertEquals("twelfth", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededTail() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("third"); + queue.enqueueTail("fourth"); + queue.enqueueTail("fifth"); + queue.enqueueTail("sixth"); + queue.enqueueTail("seventh"); + queue.enqueueTail("eighth"); + queue.enqueueTail("ninth"); + queue.enqueueTail("tenth"); + + boolean exCaught = false; + try { + queue.enqueueTail("eleventh"); + fail("bogus queue: " + queue); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + + assertEquals("first", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueHead()); + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededHead() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueHead("first"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("third"); + queue.enqueueHead("fourth"); + queue.enqueueHead("fifth"); + queue.enqueueHead("sixth"); + queue.enqueueHead("seventh"); + queue.enqueueHead("eighth"); + queue.enqueueHead("ninth"); + queue.enqueueHead("tenth"); + + boolean exCaught = false; + try { + queue.enqueueHead("eleventh"); + fail("bogus queue: " + queue); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("first", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueTail()); + assertEquals("fourth", queue.dequeueTail()); + assertEquals("fifth", queue.dequeueTail()); + assertEquals("sixth", queue.dequeueTail()); + assertEquals("seventh", queue.dequeueTail()); + assertEquals("eighth", queue.dequeueTail()); + assertEquals("ninth", queue.dequeueTail()); + assertEquals("tenth", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededWithWrappedElementsTail() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("third"); + queue.enqueueTail("fourth"); + queue.enqueueTail("fifth"); + queue.enqueueTail("sixth"); + + assertEquals("first", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueHead()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueHead()); + + queue.enqueueTail("seventh"); + queue.enqueueTail("eighth"); + queue.enqueueTail("ninth"); + queue.enqueueTail("tenth"); + queue.enqueueTail("eleventh"); + queue.enqueueTail("twelfth"); + queue.enqueueTail("thirteenth"); + + boolean exCaught = false; + try { + queue.enqueueTail("fourteenth"); + fail("bogus queue: " + queue); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("fourth", queue.dequeueHead()); + assertEquals("fifth", queue.dequeueHead()); + assertEquals("sixth", queue.dequeueHead()); + assertEquals("seventh", queue.dequeueHead()); + assertEquals("eighth", queue.dequeueHead()); + assertEquals("ninth", queue.dequeueHead()); + assertEquals("tenth", queue.dequeueHead()); + assertEquals("eleventh", queue.dequeueHead()); + assertEquals("twelfth", queue.dequeueHead()); + assertEquals("thirteenth", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededWithWrappedElementsHead() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + queue.enqueueHead("first"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("second"); + assertFalse(queue.isEmpty()); + queue.enqueueHead("third"); + queue.enqueueHead("fourth"); + queue.enqueueHead("fifth"); + queue.enqueueHead("sixth"); + + assertEquals("first", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeueTail()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeueTail()); + + queue.enqueueHead("seventh"); + queue.enqueueHead("eighth"); + queue.enqueueHead("ninth"); + queue.enqueueHead("tenth"); + queue.enqueueHead("eleventh"); + queue.enqueueHead("twelfth"); + queue.enqueueHead("thirteenth"); + + boolean exCaught = false; + try { + queue.enqueueHead("fourteenth"); + fail("bogus queue: " + queue); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("fourth", queue.dequeueTail()); + assertEquals("fifth", queue.dequeueTail()); + assertEquals("sixth", queue.dequeueTail()); + assertEquals("seventh", queue.dequeueTail()); + assertEquals("eighth", queue.dequeueTail()); + assertEquals("ninth", queue.dequeueTail()); + assertEquals("tenth", queue.dequeueTail()); + assertEquals("eleventh", queue.dequeueTail()); + assertEquals("twelfth", queue.dequeueTail()); + assertEquals("thirteenth", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testSerialization_empty() throws Exception { + Deque original = new FixedCapacityArrayDeque(3); + Deque clone = TestTools.serialize(original); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueueTail("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testSerialization_fullArray() throws Exception { + Deque queue = new FixedCapacityArrayDeque(3); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + public void testSerialization_wrappedArray() throws Exception { + Deque queue = new FixedCapacityArrayDeque(3); + queue.enqueueTail("first"); + queue.enqueueTail("second"); + queue.enqueueTail("third"); + queue.dequeueHead(); + queue.enqueueTail("fourth"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityPriorityDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityPriorityDequeTests.java new file mode 100644 index 0000000000..dec17f0356 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/FixedCapacityPriorityDequeTests.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.Comparator; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.FixedCapacityPriorityDeque; + +@SuppressWarnings("nls") +public class FixedCapacityPriorityDequeTests + extends AbstractPriorityDequeTests +{ + public FixedCapacityPriorityDequeTests(String name) { + super(name); + } + + @Override + > FixedCapacityPriorityDeque buildDeque() { + return DequeTools.fixedCapacityPriorityDeque(10); + } + + @Override + > FixedCapacityPriorityDeque buildDeque(int capacity) { + return DequeTools.fixedCapacityPriorityDeque(capacity); + } + + @Override + > FixedCapacityPriorityDeque buildDeque(Comparator comparator, int capacity) { + return DequeTools.fixedCapacityPriorityDeque(comparator, capacity); + } + + public void testIsFull() throws Exception { + FixedCapacityPriorityDeque deque = this.buildDeque(); + assertFalse(deque.isFull()); + deque.enqueue("first"); + assertFalse(deque.isFull()); + deque.enqueue("second"); + assertFalse(deque.isFull()); + deque.enqueue("third"); + deque.enqueue("fourth"); + deque.enqueue("fifth"); + deque.enqueue("sixth"); + deque.enqueue("seventh"); + deque.enqueue("eighth"); + deque.enqueue("ninth"); + deque.enqueue("tenth"); + assertTrue(deque.isFull()); + + deque.dequeueHead(); + assertFalse(deque.isEmpty()); + deque.dequeueHead(); + deque.dequeueHead(); + deque.dequeueHead(); + deque.dequeueHead(); + deque.dequeueHead(); + deque.dequeueHead(); + deque.dequeueHead(); + assertFalse(deque.isFull()); + } + + public void testCapacityExceeded() { + FixedCapacityPriorityDeque deque = this.buildDeque(); + assertTrue(deque.isEmpty()); + deque.enqueue("first"); + assertFalse(deque.isEmpty()); + deque.enqueue("second"); + assertFalse(deque.isEmpty()); + deque.enqueue("third"); + deque.enqueue("fourth"); + deque.enqueue("fifth"); + deque.enqueue("sixth"); + deque.enqueue("seventh"); + deque.enqueue("eighth"); + deque.enqueue("ninth"); + deque.enqueue("tenth"); + + boolean exCaught = false; + try { + deque.enqueue("eleventh"); + fail("bogus deque: " + deque); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("eighth", deque.dequeueHead()); + assertEquals("fifth", deque.dequeueHead()); + assertEquals("first", deque.dequeueHead()); + assertEquals("fourth", deque.dequeueHead()); + assertFalse(deque.isEmpty()); + assertEquals("ninth", deque.dequeueHead()); + assertEquals("second", deque.dequeueHead()); + assertEquals("seventh", deque.dequeueHead()); + assertEquals("sixth", deque.dequeueHead()); + assertFalse(deque.isEmpty()); + assertEquals("tenth", deque.dequeueHead()); + assertEquals("third", deque.dequeueHead()); + assertTrue(deque.isEmpty()); + } + +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/JptCommonUtilityDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/JptCommonUtilityDequeTests.java new file mode 100644 index 0000000000..ac657e3159 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/JptCommonUtilityDequeTests.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * decentralize test creation code + */ +public class JptCommonUtilityDequeTests { + + public static Test suite() { + TestSuite suite = new TestSuite(JptCommonUtilityDequeTests.class.getPackage().getName()); + + suite.addTestSuite(ArrayDequeTests.class); + suite.addTestSuite(DequeToolsTests.class); + suite.addTestSuite(EmptyDequeTests.class); + suite.addTestSuite(FixedCapacityArrayDequeTests.class); + suite.addTestSuite(FixedCapacityPriorityDequeTests.class); + suite.addTestSuite(LinkedDequeTests.class); + suite.addTestSuite(ListDequeTests.class); + suite.addTestSuite(PriorityDequeTests.class); + suite.addTestSuite(ReverseDequeTests.class); + suite.addTestSuite(SynchronizedDequeTests.class); + + return suite; + } + + private JptCommonUtilityDequeTests() { + super(); + throw new UnsupportedOperationException(); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/LinkedDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/LinkedDequeTests.java new file mode 100644 index 0000000000..2a809c51ef --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/LinkedDequeTests.java @@ -0,0 +1,263 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.Arrays; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.LinkedDeque; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class LinkedDequeTests + extends DequeTests +{ + public LinkedDequeTests(String name) { + super(name); + } + + @Override + Deque buildDeque() { + return DequeTools.linkedDeque(); + } + + public void testConstructorInt_IAE() { + boolean exCaught = false; + try { + Deque queue = DequeTools.linkedDeque(-3); + fail("bogus deque: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSize() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + String third = "third"; + + assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.enqueueTail(first); + queue.enqueueTail(second); + assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.enqueueTail(third); + assertEquals(3, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.dequeueHead(); + assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.dequeueHead(); + queue.dequeueHead(); + assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + } + + public void testSize_reverse() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + String third = "third"; + + assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.enqueueHead(first); + queue.enqueueHead(second); + assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.enqueueHead(third); + assertEquals(3, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.dequeueTail(); + assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.dequeueTail(); + queue.dequeueTail(); + assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + } + + public void testBuildElements() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + String third = "third"; + queue.enqueueTail(first); + queue.enqueueTail(second); + queue.enqueueTail(third); + + Object[] elements = new Object[] { first, second, third }; + assertTrue(Arrays.equals(elements, ((Object[]) ObjectTools.execute(queue, "buildElements")))); + } + + public void testBuildElements_reverse() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + String third = "third"; + queue.enqueueHead(first); + queue.enqueueHead(second); + queue.enqueueHead(third); + + Object[] elements = new Object[] { third, second, first }; + assertTrue(Arrays.equals(elements, ((Object[]) ObjectTools.execute(queue, "buildElements")))); + } + + public void testNodeCache_max() { + Deque queue = new LinkedDeque(2); + String first = "first"; + String second = "second"; + String third = "third"; + String fourth = "fourth"; + String fifth = "fifth"; + + Object factory = ObjectTools.get(queue, "nodeFactory"); + + this.verifyNodeCache(0, factory); + queue.enqueueTail(first); + this.verifyNodeCache(0, factory); + queue.enqueueTail(second); + queue.enqueueHead(third); + queue.enqueueHead(fourth); + queue.enqueueTail(fifth); + this.verifyNodeCache(0, factory); + assertNull(ObjectTools.get(factory, "cacheHead")); + + queue.dequeueHead(); + this.verifyNodeCache(1, factory); + queue.dequeueHead(); + this.verifyNodeCache(2, factory); + queue.dequeueTail(); + this.verifyNodeCache(2, factory); + queue.dequeueHead(); + this.verifyNodeCache(2, factory); + queue.dequeueTail(); + this.verifyNodeCache(2, factory); + queue.enqueueTail(first); + this.verifyNodeCache(1, factory); + queue.enqueueTail(second); + this.verifyNodeCache(0, factory); + queue.enqueueTail(third); + this.verifyNodeCache(0, factory); + } + + + public void testNodeCache_unlimited() { + Deque queue = DequeTools.linkedDeque(-1); + String first = "first"; + String second = "second"; + String third = "third"; + String fourth = "fourth"; + String fifth = "fifth"; + + Object factory = ObjectTools.get(queue, "nodeFactory"); + + this.verifyNodeCache(0, factory); + queue.enqueueTail(first); + this.verifyNodeCache(0, factory); + queue.enqueueTail(second); + queue.enqueueHead(third); + queue.enqueueHead(fourth); + queue.enqueueTail(fifth); + this.verifyNodeCache(0, factory); + assertNull(ObjectTools.get(factory, "cacheHead")); + + queue.dequeueHead(); + this.verifyNodeCache(1, factory); + queue.dequeueHead(); + this.verifyNodeCache(2, factory); + queue.dequeueTail(); + this.verifyNodeCache(3, factory); + queue.dequeueHead(); + this.verifyNodeCache(4, factory); + queue.dequeueTail(); + this.verifyNodeCache(5, factory); + queue.enqueueTail(first); + this.verifyNodeCache(4, factory); + queue.enqueueTail(second); + this.verifyNodeCache(3, factory); + queue.enqueueTail(third); + this.verifyNodeCache(2, factory); + queue.enqueueTail(fourth); + this.verifyNodeCache(1, factory); + queue.enqueueTail(fifth); + this.verifyNodeCache(0, factory); + } + + public void verifyNodeCache(int size, Object factory) { + assertEquals(size, ((Integer) ObjectTools.get(factory, "cacheSize")).intValue()); + int nodeCount = 0; + for (Object node = ObjectTools.get(factory, "cacheHead"); node != null; node = ObjectTools.get(node, "next")) { + nodeCount++; + } + assertEquals(size, nodeCount); + } + + public void testNodeToString() { + Deque queue = DequeTools.linkedDeque(); + String first = "first"; + String second = "second"; + String third = "third"; + queue.enqueueTail(first); + queue.enqueueTail(second); + queue.enqueueHead(third); + + Object head = ObjectTools.get(queue, "head"); + assertTrue(head.toString().startsWith("LinkedDeque.Node")); + assertTrue(head.toString().endsWith("(third)")); + } + + public void testSimpleNodeFactoryToString() { + Deque queue = DequeTools.linkedDeque(); + Object factory = ObjectTools.get(queue, "nodeFactory"); + assertEquals("LinkedDeque.SimpleNodeFactory", factory.toString()); + } + + public void testCachingNodeFactoryToString() { + Deque queue = DequeTools.linkedDeque(20); + Object factory = ObjectTools.get(queue, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedDeque.CachingNodeFactory")); + assertTrue(factory.toString().endsWith("(0)")); + } + + public void testClone_caching() throws Exception { + LinkedDeque original = DequeTools.linkedDeque(20); + original.enqueueTail("first"); + + LinkedDeque clone = original.clone(); + assertEquals(original.peekHead(), clone.peekHead()); + assertEquals(original.dequeueHead(), clone.dequeueHead()); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueueTail("second"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + + Object factory = ObjectTools.get(original, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedDeque.CachingNodeFactory")); + } + + public void testSerialization_caching() throws Exception { + Deque original = DequeTools.linkedDeque(20); + original.enqueueTail("first"); + + Deque clone = TestTools.serialize(original); + assertEquals(original.peekHead(), clone.peekHead()); + assertEquals(original.dequeueHead(), clone.dequeueHead()); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueueTail("second"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + + Object factory = ObjectTools.get(original, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedDeque.CachingNodeFactory")); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ListDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ListDequeTests.java new file mode 100644 index 0000000000..24263cb591 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ListDequeTests.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; + +public class ListDequeTests + extends DequeTests +{ + public ListDequeTests(String name) { + super(name); + } + + @Override + Deque buildDeque() { + return DequeTools.adapt(new ArrayList()); + } + + @Override + public void testClone() { + // unsupported + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/PriorityDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/PriorityDequeTests.java new file mode 100644 index 0000000000..cf9833552c --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/PriorityDequeTests.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.Comparator; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.deque.AbstractPriorityDeque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.PriorityDeque; + +@SuppressWarnings("nls") +public class PriorityDequeTests + extends AbstractPriorityDequeTests +{ + public PriorityDequeTests(String name) { + super(name); + } + + @Override + > PriorityDeque buildDeque() { + return DequeTools.priorityDeque(); + } + + @Override + > PriorityDeque buildDeque(int capacity) { + return DequeTools.priorityDeque(capacity); + } + + @Override + > PriorityDeque buildDeque(Comparator comparator, int capacity) { + return DequeTools.priorityDeque(comparator, capacity); + } + + public void testArrayCapacityExceeded() { + AbstractPriorityDeque deque = this.buildDeque(); + assertTrue(deque.isEmpty()); + deque.enqueue(Integer.valueOf(1)); + assertFalse(deque.isEmpty()); + deque.enqueue(Integer.valueOf(2)); + assertFalse(deque.isEmpty()); + deque.enqueue(Integer.valueOf(3)); + deque.enqueue(Integer.valueOf(10)); + deque.enqueue(Integer.valueOf(11)); + deque.enqueue(Integer.valueOf(12)); + deque.enqueue(Integer.valueOf(4)); + deque.enqueue(Integer.valueOf(4)); + deque.enqueue(Integer.valueOf(7)); + deque.enqueue(Integer.valueOf(8)); + deque.enqueue(Integer.valueOf(9)); + deque.enqueue(Integer.valueOf(5)); + deque.enqueue(Integer.valueOf(6)); + deque.enqueue(Integer.valueOf(9)); + + assertEquals(Integer.valueOf(1), deque.dequeueHead()); + assertFalse(deque.isEmpty()); + assertEquals(Integer.valueOf(2), deque.dequeueHead()); + assertFalse(deque.isEmpty()); + assertEquals(Integer.valueOf(3), deque.dequeueHead()); + assertEquals(Integer.valueOf(4), deque.dequeueHead()); + assertEquals(Integer.valueOf(12), deque.dequeueTail()); + assertEquals(Integer.valueOf(4), deque.dequeueHead()); + assertEquals(Integer.valueOf(5), deque.dequeueHead()); + assertEquals(Integer.valueOf(6), deque.dequeueHead()); + assertEquals(Integer.valueOf(7), deque.dequeueHead()); + assertEquals(Integer.valueOf(11), deque.dequeueTail()); + assertEquals(Integer.valueOf(8), deque.dequeueHead()); + assertEquals(Integer.valueOf(10), deque.dequeueTail()); + assertEquals(Integer.valueOf(9), deque.dequeueHead()); + assertEquals(Integer.valueOf(9), deque.dequeueHead()); + assertTrue(deque.isEmpty()); + } + + public void testEnsureCapacity() throws Exception { + PriorityDeque deque = this.buildDeque(); + deque.enqueue("b"); + deque.enqueue("c"); + deque.enqueue("a"); + assertEquals(11, ((Object[]) ObjectTools.get(deque, "elements")).length); + deque.ensureCapacity(420); + assertEquals(421, ((Object[]) ObjectTools.get(deque, "elements")).length); + assertEquals("a", deque.dequeueHead()); + assertEquals("c", deque.dequeueTail()); + assertEquals("b", deque.dequeueHead()); + assertTrue(deque.isEmpty()); + } + + public void testTrimToSize() throws Exception { + PriorityDeque deque = this.buildDeque(); + deque.enqueue("b"); + deque.enqueue("c"); + deque.enqueue("a"); + assertEquals(11, ((Object[]) ObjectTools.get(deque, "elements")).length); + deque.trimToSize(); + assertEquals(4, ((Object[]) ObjectTools.get(deque, "elements")).length); + assertEquals("a", deque.dequeueHead()); + assertEquals("c", deque.dequeueTail()); + assertEquals("b", deque.dequeueHead()); + assertTrue(deque.isEmpty()); + } + + public void testTrimToSize_nop() throws Exception { + PriorityDeque deque = this.buildDeque(3); + deque.enqueue("b"); + deque.enqueue("c"); + deque.enqueue("a"); + assertEquals(4, ((Object[]) ObjectTools.get(deque, "elements")).length); + deque.trimToSize(); + assertEquals(4, ((Object[]) ObjectTools.get(deque, "elements")).length); + assertEquals("a", deque.dequeueHead()); + assertEquals("c", deque.dequeueTail()); + assertEquals("b", deque.dequeueHead()); + assertTrue(deque.isEmpty()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ReverseDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ReverseDequeTests.java new file mode 100644 index 0000000000..ddc4c76e16 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/ReverseDequeTests.java @@ -0,0 +1,282 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.deque; + +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; + +@SuppressWarnings("nls") +public class ReverseDequeTests + extends DequeTests +{ + private Deque original; + + public ReverseDequeTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.original = DequeTools.arrayDeque(); + } + + @Override + public Deque buildDeque() { + return DequeTools.reverse(this.original); + } + + public void testIsEmpty_combo() { + Deque queue = this.buildDeque(); + assertTrue(queue.isEmpty()); + this.original.enqueueTail("first"); + assertFalse(queue.isEmpty()); + queue.enqueueTail("second"); + assertFalse(queue.isEmpty()); + this.original.enqueueHead("zero"); + assertFalse(queue.isEmpty()); + queue.dequeueHead(); + assertFalse(queue.isEmpty()); + queue.dequeueHead(); + assertFalse(queue.isEmpty()); + queue.dequeueTail(); + assertTrue(queue.isEmpty()); + } + + public void testEnqueueTailAndDequeueTail() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueTail(first); + this.original.enqueueTail(second); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.dequeueTail()); + } + + public void testEnqueueHeadAndDequeueHead() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueHead(first); + this.original.enqueueHead(second); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.dequeueHead()); + } + + public void testEnqueueAndDequeue_combo() { + Deque queue = this.buildDeque(); + String negative = "negative"; + String zero = "zero"; + String first = "first"; + String second = "second"; + + this.original.enqueueTail(first); + this.original.enqueueTail(second); + this.original.enqueueHead(zero); + this.original.enqueueHead(negative); + assertEquals(negative, queue.dequeueTail()); + assertEquals(second, queue.dequeueHead()); + assertEquals(zero, queue.dequeueTail()); + assertEquals(first, queue.dequeueHead()); + + assertTrue(queue.isEmpty()); + } + + public void testEnqueueTailAndPeekTail() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueTail(first); + this.original.enqueueTail(second); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.dequeueTail()); + } + + public void testEnqueueHeadAndPeekHead() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueHead(first); + this.original.enqueueHead(second); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.dequeueHead()); + } + + public void testEnqueueAndPeek_combo() { + Deque queue = this.buildDeque(); + String negative = "negative"; + String zero = "zero"; + String first = "first"; + String second = "second"; + + this.original.enqueueTail(first); + this.original.enqueueTail(second); + this.original.enqueueHead(zero); + this.original.enqueueHead(negative); + assertEquals(negative, queue.peekTail()); + assertEquals(negative, queue.peekTail()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.peekHead()); + + assertEquals(negative, queue.dequeueTail()); + assertEquals(zero, queue.peekTail()); + assertEquals(zero, queue.peekTail()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.peekHead()); + + assertEquals(second, queue.dequeueHead()); + assertEquals(zero, queue.peekTail()); + assertEquals(first, queue.peekHead()); + + assertEquals(first, queue.dequeueHead()); + assertEquals(zero, queue.peekTail()); + assertEquals(zero, queue.peekHead()); + + assertEquals(zero, queue.dequeueHead()); + + assertTrue(queue.isEmpty()); + } + + public void testEmptyDequeExceptionPeekTail_combo() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueTail(first); + this.original.enqueueTail(second); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.dequeueTail()); + + boolean exCaught = false; + try { + queue.peekTail(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyDequeExceptionPeekHead_combo() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueHead(first); + this.original.enqueueHead(second); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.dequeueHead()); + + boolean exCaught = false; + try { + queue.peekHead(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyDequeExceptionDequeueTail_combo() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueTail(first); + this.original.enqueueTail(second); + assertEquals(first, queue.peekTail()); + assertEquals(first, queue.dequeueTail()); + assertEquals(second, queue.peekTail()); + assertEquals(second, queue.dequeueTail()); + + boolean exCaught = false; + try { + queue.dequeueTail(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyDequeExceptionDequeueHead_combo() { + Deque queue = this.buildDeque(); + String first = "first"; + String second = "second"; + + this.original.enqueueHead(first); + this.original.enqueueHead(second); + assertEquals(first, queue.peekHead()); + assertEquals(first, queue.dequeueHead()); + assertEquals(second, queue.peekHead()); + assertEquals(second, queue.dequeueHead()); + + boolean exCaught = false; + try { + queue.dequeueHead(); + fail(); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + @Override + public void testClone() { + // unsupported + } + + @Override + public void testToString() throws Exception { + Deque queue = this.buildDeque(); + assertTrue(queue.toString().startsWith("ReverseDeque")); + assertTrue(queue.toString().endsWith("([])")); + queue.enqueueTail("first"); + assertTrue(queue.toString().startsWith("ReverseDeque")); + assertTrue(queue.toString().endsWith("([first])")); + queue.enqueueTail("second"); + assertTrue(queue.toString().startsWith("ReverseDeque")); + assertTrue(queue.toString().endsWith("([second, first])")); + queue.enqueueTail("third"); + assertTrue(queue.toString().startsWith("ReverseDeque")); + assertTrue(queue.toString().endsWith("([third, second, first])")); + queue.enqueueHead("foo"); + assertTrue(queue.toString().startsWith("ReverseDeque")); + assertTrue(queue.toString().endsWith("([third, second, first, foo])")); + } + + public void testCtor_nullDeque() { + boolean exCaught = false; + try { + Deque deque = DequeTools.reverse(null); + fail("bogus deque: " + deque); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/SynchronizedDequeTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/SynchronizedDequeTests.java new file mode 100644 index 0000000000..2f916dda1f --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/deque/SynchronizedDequeTests.java @@ -0,0 +1,1255 @@ +/******************************************************************************* + * Copyright (c) 2015 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.deque; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.deque.Deque; +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.deque.LinkedDeque; +import org.eclipse.jpt.common.utility.internal.deque.SynchronizedDeque; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +@SuppressWarnings("nls") +public class SynchronizedDequeTests + extends DequeTests +{ + private volatile SynchronizedDeque syncDeque; + volatile boolean timeoutOccurred; + volatile long startTime; + volatile long endTime; + volatile Object dequeueHeadObject; + volatile Object dequeueTailObject; + + boolean commandExecuted; + + static final String ITEM_1 = new String(); + static final String ITEM_2 = new String(); + + public SynchronizedDequeTests(String name) { + super(name); + } + + @Override + Deque buildDeque() { + return DequeTools.synchronizedDeque(); + } + + @Override + public void testClone() { + // unsupported + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.syncDeque = DequeTools.synchronizedDeque(); + this.timeoutOccurred = false; + this.startTime = 0; + this.endTime = 0; + this.dequeueHeadObject = null; + } + + // ********** constructor ********** + + public void testConstructorDeque() throws Exception { + Deque innerDeque = DequeTools.arrayDeque(); + SynchronizedDeque stack = DequeTools.synchronizedDeque(innerDeque); + assertNotNull(stack); + assertSame(stack, stack.getMutex()); + } + + public void testConstructorDeque_NPE() throws Exception { + boolean exCaught = false; + try { + Deque stack = DequeTools.synchronizedDeque(null); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorDequeObject() throws Exception { + String mutex = "mutex"; + Deque innerDeque = DequeTools.arrayDeque(); + SynchronizedDeque stack = DequeTools.synchronizedDeque(innerDeque, mutex); + assertNotNull(stack); + assertSame(mutex, stack.getMutex()); + } + + public void testConstructorDequeObject_NPE1() throws Exception { + String mutex = "mutex"; + boolean exCaught = false; + try { + Deque stack = DequeTools.synchronizedDeque(null, mutex); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorDequeObject_NPE2() throws Exception { + Deque innerDeque = DequeTools.arrayDeque(); + boolean exCaught = false; + try { + Deque stack = DequeTools.synchronizedDeque(innerDeque, null); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + // ********** concurrent access ********** + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentDequeueHead() throws Exception { + this.verifyConcurrentDequeueHead(new SlowLinkedDeque(), "first"); + this.verifyConcurrentDequeueHead(new SlowSynchronizedDeque(), "second"); + } + + private void verifyConcurrentDequeueHead(SlowDeque slowDeque, String expected) throws Exception { + slowDeque.enqueueTail("first"); + slowDeque.enqueueTail("second"); + + Thread thread = this.buildThread(this.buildRunnableDequeueHead(slowDeque)); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(expected, slowDeque.dequeueHead()); + thread.join(); + assertTrue(slowDeque.isEmpty()); + } + + private Runnable buildRunnableDequeueHead(final SlowDeque slowDeque) { + return new Runnable() { + public void run() { + slowDeque.slowDequeueHead(); + } + }; + } + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentDequeueTail() throws Exception { + this.verifyConcurrentDequeueTail(new SlowLinkedDeque(), "first"); + this.verifyConcurrentDequeueTail(new SlowSynchronizedDeque(), "second"); + } + + private void verifyConcurrentDequeueTail(SlowDeque slowDeque, String expected) throws Exception { + slowDeque.enqueueHead("first"); + slowDeque.enqueueHead("second"); + + Thread thread = this.buildThread(this.buildRunnableDequeueTail(slowDeque)); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(expected, slowDeque.dequeueTail()); + thread.join(); + assertTrue(slowDeque.isEmpty()); + } + + private Runnable buildRunnableDequeueTail(final SlowDeque slowDeque) { + return new Runnable() { + public void run() { + slowDeque.slowDequeueTail(); + } + }; + } + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentEnqueueTail() throws Exception { + this.verifyConcurrentEnqueueTail(new SlowLinkedDeque(), "second", "first"); + this.verifyConcurrentEnqueueTail(new SlowSynchronizedDeque(), "first", "second"); + } + + private void verifyConcurrentEnqueueTail(SlowDeque slowDeque, String first, String second) throws Exception { + Thread thread = this.buildThread(this.buildRunnableEnqueueTail(slowDeque, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + slowDeque.enqueueTail("second"); + thread.join(); + assertEquals(first, slowDeque.dequeueHead()); + assertEquals(second, slowDeque.dequeueHead()); + assertTrue(slowDeque.isEmpty()); + } + + private Runnable buildRunnableEnqueueTail(final SlowDeque slowDeque, final String element) { + return new Runnable() { + public void run() { + slowDeque.slowEnqueueTail(element); + } + }; + } + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentEnqueueHead() throws Exception { + this.verifyConcurrentEnqueueHead(new SlowLinkedDeque(), "second", "first"); + this.verifyConcurrentEnqueueHead(new SlowSynchronizedDeque(), "first", "second"); + } + + private void verifyConcurrentEnqueueHead(SlowDeque slowDeque, String first, String second) throws Exception { + Thread thread = this.buildThread(this.buildRunnableEnqueueHead(slowDeque, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + slowDeque.enqueueHead("second"); + thread.join(); + assertEquals(first, slowDeque.dequeueTail()); + assertEquals(second, slowDeque.dequeueTail()); + assertTrue(slowDeque.isEmpty()); + } + + private Runnable buildRunnableEnqueueHead(final SlowDeque slowDeque, final String element) { + return new Runnable() { + public void run() { + slowDeque.slowEnqueueHead(element); + } + }; + } + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentIsEmpty() throws Exception { + this.verifyConcurrentIsEmpty(new SlowLinkedDeque(), true); + this.verifyConcurrentIsEmpty(new SlowSynchronizedDeque(), false); + } + + private void verifyConcurrentIsEmpty(SlowDeque slowDeque, boolean empty) throws Exception { + Thread thread = this.buildThread(this.buildRunnableEnqueueTail(slowDeque, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(empty, slowDeque.isEmpty()); + thread.join(); + assertEquals("first", slowDeque.dequeueHead()); + assertTrue(slowDeque.isEmpty()); + } + + + private interface SlowDeque extends Deque { + Object slowDequeueHead(); + Object slowDequeueTail(); + void slowEnqueueTail(E element); + void slowEnqueueHead(E element); + } + + private class SlowLinkedDeque extends LinkedDeque implements SlowDeque { + private static final long serialVersionUID = 1L; + SlowLinkedDeque() { + super(); + } + public Object slowDequeueHead() { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.dequeueHead(); + } + public Object slowDequeueTail() { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.dequeueTail(); + } + public void slowEnqueueTail(E element) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.enqueueTail(element); + } + public void slowEnqueueHead(E element) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.enqueueHead(element); + } + } + + private class SlowSynchronizedDeque extends SynchronizedDeque implements SlowDeque { + private static final long serialVersionUID = 1L; + SlowSynchronizedDeque() { + super(DequeTools.linkedDeque()); + } + public Object slowDequeueHead() { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.dequeueHead(); + } + } + public Object slowDequeueTail() { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.dequeueTail(); + } + } + public void slowEnqueueTail(E element) { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.enqueueTail(element); + } + } + public void slowEnqueueHead(E element) { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.enqueueHead(element); + } + } + } + + + // ********** waits ********** + + public void testWaitUntilEmpty() throws Exception { + this.verifyWaitUntilEmpty(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilEmpty2() throws Exception { + this.verifyWaitUntilEmpty(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilEmptyTimeout() throws Exception { + this.verifyWaitUntilEmpty(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the queue was dequeueHead... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitUntilEmpty(long timeout) throws Exception { + this.syncDeque.enqueueTail(ITEM_1); + Runnable r1 = this.buildRunnable(this.buildDequeueHeadCommand(), this.syncDeque, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitUntilEmptyCommand(timeout), this.syncDeque, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitUntilEmptyCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException { + SynchronizedDequeTests.this.startTime = System.currentTimeMillis(); + SynchronizedDequeTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedDeque); + SynchronizedDequeTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedDeque synchronizedDeque) throws InterruptedException { + if (timeout < 0) { + synchronizedDeque.waitUntilEmpty(); + return false; + } + return ! synchronizedDeque.waitUntilEmpty(timeout); + } + }; + } + + public void testWaitUntilNotEmpty() throws Exception { + this.verifyWaitUntilNotEmpty(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been enqueueTail by t1... + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_1, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilNotEmpty2() throws Exception { + this.verifyWaitUntilNotEmpty(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been enqueueTail by t1... + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_1, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilNotEmptyTimeout() throws Exception { + this.verifyWaitUntilNotEmpty(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and an item should have been enqueueTail by t1... + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_1, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitUntilNotEmpty(long timeout) throws Exception { + Runnable r1 = this.buildRunnable(this.buildEnqueueTailCommand(), this.syncDeque, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitUntilNotEmptyCommand(timeout), this.syncDeque, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitUntilNotEmptyCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException { + SynchronizedDequeTests.this.startTime = System.currentTimeMillis(); + SynchronizedDequeTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedDeque); + SynchronizedDequeTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedDeque synchronizedDeque) throws InterruptedException { + if (timeout < 0) { + synchronizedDeque.waitUntilNotEmpty(); + return false; + } + return ! synchronizedDeque.waitUntilNotEmpty(timeout); + } + }; + } + + public void testWaitToDequeueHead() throws Exception { + this.verifyWaitToDequeueHead(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeueHead by t2... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToDequeueHead2() throws Exception { + this.verifyWaitToDequeueHead(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeueHead by t2... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToDequeueHeadTimeout() throws Exception { + this.verifyWaitToDequeueHead(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the queue was never dequeueHead... + assertNull(this.dequeueHeadObject); + // ...and it still holds the item + assertSame(ITEM_1, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitToDequeueHead(long timeout) throws Exception { + Runnable r1 = this.buildRunnable(this.buildEnqueueTailCommand(), this.syncDeque, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitToDequeueHeadCommand(timeout), this.syncDeque, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitToDequeueHeadCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException { + SynchronizedDequeTests.this.startTime = System.currentTimeMillis(); + this.waitToDequeueHead(synchronizedDeque); + SynchronizedDequeTests.this.endTime = System.currentTimeMillis(); + } + private void waitToDequeueHead(SynchronizedDeque synchronizedDeque) throws InterruptedException { + if (timeout < 0) { + SynchronizedDequeTests.this.dequeueHeadObject = synchronizedDeque.waitToDequeueHead(); + return; + } + try { + SynchronizedDequeTests.this.dequeueHeadObject = synchronizedDeque.waitToDequeueHead(timeout); + } catch (NoSuchElementException ex) { + SynchronizedDequeTests.this.timeoutOccurred = true; + } + } + }; + } + + public void testWaitToDequeueTail() throws Exception { + this.verifyWaitToDequeueTail(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeueTaild by t2... + assertSame(ITEM_1, this.dequeueTailObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToDequeueTail2() throws Exception { + this.verifyWaitToDequeueTail(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeueTaild by t2... + assertSame(ITEM_1, this.dequeueTailObject); + // ...and the queue should be empty + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToDequeueTailTimeout() throws Exception { + this.verifyWaitToDequeueTail(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the queue was never dequeueTaild... + assertNull(this.dequeueTailObject); + // ...and it still holds the item + assertSame(ITEM_1, this.syncDeque.peekTail()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitToDequeueTail(long timeout) throws Exception { + Runnable r1 = this.buildRunnable(this.buildEnqueueHeadCommand(), this.syncDeque, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitToDequeueTailCommand(timeout), this.syncDeque, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitToDequeueTailCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException { + SynchronizedDequeTests.this.startTime = System.currentTimeMillis(); + this.waitToDequeueTail(synchronizedDeque); + SynchronizedDequeTests.this.endTime = System.currentTimeMillis(); + } + private void waitToDequeueTail(SynchronizedDeque synchronizedDeque) throws InterruptedException { + if (timeout < 0) { + SynchronizedDequeTests.this.dequeueTailObject = synchronizedDeque.waitToDequeueTail(); + return; + } + try { + SynchronizedDequeTests.this.dequeueTailObject = synchronizedDeque.waitToDequeueTail(timeout); + } catch (NoSuchElementException ex) { + SynchronizedDequeTests.this.timeoutOccurred = true; + } + } + }; + } + + public void testWaitToEnqueueTail() throws Exception { + this.verifyWaitToEnqueueTail(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and the queue gets dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and an item is enqueueTail on to the queue by t2 + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_2, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToEnqueueTail2() throws Exception { + this.verifyWaitToEnqueueTail(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and the queue gets dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and an item is enqueueTail on to the queue by t2 + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_2, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToEnqueueTailTimeout() throws Exception { + this.verifyWaitToEnqueueTail(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the queue is eventually dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...but nothing is enqueueTail on to the queue by t2 + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitToEnqueueTail(long timeout) throws Exception { + this.syncDeque.enqueueTail(ITEM_1); + Runnable r1 = this.buildRunnable(this.buildDequeueHeadCommand(), this.syncDeque, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitToEnqueueTailCommand(timeout), this.syncDeque, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitToEnqueueTailCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException { + SynchronizedDequeTests.this.startTime = System.currentTimeMillis(); + SynchronizedDequeTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedDeque); + SynchronizedDequeTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedDeque synchronizedDeque) throws InterruptedException { + if (timeout < 0) { + synchronizedDeque.waitToEnqueueTail(ITEM_2); + return false; + } + return ! synchronizedDeque.waitToEnqueueTail(ITEM_2, timeout); + } + }; + } + + public void testWaitToEnqueueHead() throws Exception { + this.verifyWaitToEnqueueHead(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and the queue gets dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and an item is enqueueHead on to the queue by t2 + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_2, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToEnqueueHead2() throws Exception { + this.verifyWaitToEnqueueHead(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and the queue gets dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...and an item is enqueueHead on to the queue by t2 + assertFalse(this.syncDeque.isEmpty()); + assertSame(ITEM_2, this.syncDeque.peekHead()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitToEnqueueHeadTimeout() throws Exception { + this.verifyWaitToEnqueueHead(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the queue is eventually dequeueHead by t1... + assertSame(ITEM_1, this.dequeueHeadObject); + // ...but nothing is enqueueHead on to the queue by t2 + assertTrue(this.syncDeque.isEmpty()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitToEnqueueHead(long timeout) throws Exception { + this.syncDeque.enqueueHead(ITEM_1); + Runnable r1 = this.buildRunnable(this.buildDequeueHeadCommand(), this.syncDeque, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitToEnqueueHeadCommand(timeout), this.syncDeque, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitToEnqueueHeadCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException { + SynchronizedDequeTests.this.startTime = System.currentTimeMillis(); + SynchronizedDequeTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedDeque); + SynchronizedDequeTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedDeque synchronizedDeque) throws InterruptedException { + if (timeout < 0) { + synchronizedDeque.waitToEnqueueHead(ITEM_2); + return false; + } + return ! synchronizedDeque.waitToEnqueueHead(ITEM_2, timeout); + } + }; + } + + private Command buildEnqueueTailCommand() { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) { + synchronizedDeque.enqueueTail(ITEM_1); + } + }; + } + + private Command buildEnqueueHeadCommand() { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) { + synchronizedDeque.enqueueHead(ITEM_1); + } + }; + } + + private Command buildDequeueHeadCommand() { + return new Command() { + public void execute(SynchronizedDeque synchronizedDeque) { + SynchronizedDequeTests.this.dequeueHeadObject = synchronizedDeque.dequeueHead(); + } + }; + } + + private Runnable buildRunnable(final Command command, final SynchronizedDeque synchronizedDeque, final long sleep) { + return new TestRunnable() { + @Override + protected void run_() throws Throwable { + if (sleep != 0) { + Thread.sleep(sleep); + } + command.execute(synchronizedDeque); + } + }; + } + + long calculateElapsedTime() { + return this.endTime - this.startTime; + } + + + // ********** Command interface ********** + + private interface Command { + void execute(SynchronizedDeque synchronizedDeque) throws InterruptedException; + } + + + // ********** execute ********** + + public void testExecute() throws Exception { + org.eclipse.jpt.common.utility.command.Command command = new org.eclipse.jpt.common.utility.command.Command() { + public void execute() { + SynchronizedDequeTests.this.commandExecuted = true; + } + }; + this.commandExecuted = false; + this.syncDeque.execute(command); + assertTrue(this.commandExecuted); + } + + + // ********** additional protocol ********** + + public void testEnqueueTailAllIterable() throws Exception { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + this.syncDeque.enqueueTailAll(list); + assertEquals("one", this.syncDeque.dequeueHead()); + assertEquals("two", this.syncDeque.dequeueHead()); + assertEquals("three", this.syncDeque.dequeueHead()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllIterable_empty() throws Exception { + ArrayList list = new ArrayList(); + this.syncDeque.enqueueTailAll(list); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllObjectArray() throws Exception { + this.syncDeque.enqueueTailAll(new String[] { "one", "two", "three" }); + assertEquals("one", this.syncDeque.dequeueHead()); + assertEquals("two", this.syncDeque.dequeueHead()); + assertEquals("three", this.syncDeque.dequeueHead()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllObjectArray_empty() throws Exception { + this.syncDeque.enqueueTailAll(new String[0]); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllStack() throws Exception { + Stack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + this.syncDeque.enqueueTailAll(stack); + assertEquals("three", this.syncDeque.dequeueHead()); + assertEquals("two", this.syncDeque.dequeueHead()); + assertEquals("one", this.syncDeque.dequeueHead()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllStack_empty() throws Exception { + Stack stack = StackTools.arrayStack(); + this.syncDeque.enqueueTailAll(stack); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllDeque() throws Exception { + Deque queue = DequeTools.arrayDeque(); + queue.enqueueTail("one"); + queue.enqueueTail("two"); + queue.enqueueTail("three"); + this.syncDeque.enqueueTailAll(queue); + assertEquals("one", this.syncDeque.dequeueHead()); + assertEquals("two", this.syncDeque.dequeueHead()); + assertEquals("three", this.syncDeque.dequeueHead()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueTailAllDeque_empty() throws Exception { + Deque queue = DequeTools.arrayDeque(); + this.syncDeque.enqueueTailAll(queue); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testDrainHead() throws Exception { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("three"); + ArrayList list = this.syncDeque.drainHead(); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainHead_empty() throws Exception { + ArrayList list = this.syncDeque.drainHead(); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testDrainHeadToCollection() throws Exception { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("three"); + ArrayList list = new ArrayList(); + assertTrue(this.syncDeque.drainHeadTo(list)); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainHeadToCollection_empty() throws Exception { + ArrayList list = new ArrayList(); + assertFalse(this.syncDeque.drainHeadTo(list)); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testDrainHeadToListInt() throws Exception { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.syncDeque.drainHeadTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("one", list.get(2)); + assertEquals("two", list.get(3)); + assertEquals("three", list.get(4)); + assertEquals("ccc", list.get(5)); + } + + public void testDrainHeadToListInt_end() throws Exception { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.syncDeque.drainHeadTo(list, 3)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + assertEquals("one", list.get(3)); + assertEquals("two", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testDrainHeadToListInt_empty() throws Exception { + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertFalse(this.syncDeque.drainHeadTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + } + + public void testDrainHeadToStack() throws Exception { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("three"); + Stack stack = StackTools.arrayStack(); + assertTrue(this.syncDeque.drainHeadTo(stack)); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + assertTrue(stack.isEmpty()); + } + + public void testDrainHeadToStack_empty() throws Exception { + Stack stack = StackTools.arrayStack(); + assertFalse(this.syncDeque.drainHeadTo(stack)); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(stack.isEmpty()); + } + + public void testDrainHeadToDeque() throws Exception { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("three"); + Deque queue = DequeTools.arrayDeque(); + assertTrue(this.syncDeque.drainHeadTo(queue)); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("one", queue.dequeueHead()); + assertEquals("two", queue.dequeueHead()); + assertEquals("three", queue.dequeueHead()); + assertTrue(queue.isEmpty()); + } + + public void testDrainHeadToDeque_empty() throws Exception { + Deque queue = DequeTools.arrayDeque(); + assertFalse(this.syncDeque.drainHeadTo(queue)); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(queue.isEmpty()); + } + + public void testDrainHeadToMapTransformer() { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("zero"); + Mapmap = new HashMap(); + assertTrue(this.syncDeque.drainHeadTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testDrainHeadToMapTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.syncDeque.drainHeadTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testDrainHeadToMapTransformerTransformer() { + this.syncDeque.enqueueTail("one"); + this.syncDeque.enqueueTail("two"); + this.syncDeque.enqueueTail("zero"); + Mapmap = new HashMap(); + assertTrue(this.syncDeque.drainHeadTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testDrainHeadToMapTransformerTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.syncDeque.drainHeadTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertTrue(map.isEmpty()); + } + + public void testEnqueueHeadAllIterable() throws Exception { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + this.syncDeque.enqueueHeadAll(list); + assertEquals("one", this.syncDeque.dequeueTail()); + assertEquals("two", this.syncDeque.dequeueTail()); + assertEquals("three", this.syncDeque.dequeueTail()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllIterable_empty() throws Exception { + ArrayList list = new ArrayList(); + this.syncDeque.enqueueHeadAll(list); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllObjectArray() throws Exception { + this.syncDeque.enqueueHeadAll(new String[] { "one", "two", "three" }); + assertEquals("one", this.syncDeque.dequeueTail()); + assertEquals("two", this.syncDeque.dequeueTail()); + assertEquals("three", this.syncDeque.dequeueTail()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllObjectArray_empty() throws Exception { + this.syncDeque.enqueueHeadAll(new String[0]); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllStack() throws Exception { + Stack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + this.syncDeque.enqueueHeadAll(stack); + assertEquals("three", this.syncDeque.dequeueTail()); + assertEquals("two", this.syncDeque.dequeueTail()); + assertEquals("one", this.syncDeque.dequeueTail()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllStack_empty() throws Exception { + Stack stack = StackTools.arrayStack(); + this.syncDeque.enqueueHeadAll(stack); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllDeque() throws Exception { + Deque queue = DequeTools.arrayDeque(); + queue.enqueueHead("one"); + queue.enqueueHead("two"); + queue.enqueueHead("three"); + this.syncDeque.enqueueHeadAll(queue); + assertEquals("one", this.syncDeque.dequeueTail()); + assertEquals("two", this.syncDeque.dequeueTail()); + assertEquals("three", this.syncDeque.dequeueTail()); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testEnqueueHeadAllDeque_empty() throws Exception { + Deque queue = DequeTools.arrayDeque(); + this.syncDeque.enqueueHeadAll(queue); + assertTrue(this.syncDeque.isEmpty()); + } + + public void testDrainTail() throws Exception { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("three"); + ArrayList list = this.syncDeque.drainTail(); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainTail_empty() throws Exception { + ArrayList list = this.syncDeque.drainTail(); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testDrainTailToCollection() throws Exception { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("three"); + ArrayList list = new ArrayList(); + assertTrue(this.syncDeque.drainTailTo(list)); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainTailToCollection_empty() throws Exception { + ArrayList list = new ArrayList(); + assertFalse(this.syncDeque.drainTailTo(list)); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testDrainTailToListInt() throws Exception { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.syncDeque.drainTailTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("one", list.get(2)); + assertEquals("two", list.get(3)); + assertEquals("three", list.get(4)); + assertEquals("ccc", list.get(5)); + } + + public void testDrainTailToListInt_end() throws Exception { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.syncDeque.drainTailTo(list, 3)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + assertEquals("one", list.get(3)); + assertEquals("two", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testDrainTailToListInt_empty() throws Exception { + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertFalse(this.syncDeque.drainTailTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + } + + public void testDrainTailToStack() throws Exception { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("three"); + Stack stack = StackTools.arrayStack(); + assertTrue(this.syncDeque.drainTailTo(stack)); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + assertTrue(stack.isEmpty()); + } + + public void testDrainTailToStack_empty() throws Exception { + Stack stack = StackTools.arrayStack(); + assertFalse(this.syncDeque.drainTailTo(stack)); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(stack.isEmpty()); + } + + public void testDrainTailToDeque() throws Exception { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("three"); + Deque queue = DequeTools.arrayDeque(); + assertTrue(this.syncDeque.drainTailTo(queue)); + assertTrue(this.syncDeque.isEmpty()); + assertEquals("one", queue.dequeueTail()); + assertEquals("two", queue.dequeueTail()); + assertEquals("three", queue.dequeueTail()); + assertTrue(queue.isEmpty()); + } + + public void testDrainTailToDeque_empty() throws Exception { + Deque queue = DequeTools.arrayDeque(); + assertFalse(this.syncDeque.drainTailTo(queue)); + assertTrue(this.syncDeque.isEmpty()); + assertTrue(queue.isEmpty()); + } + + public void testDrainTailToMapTransformer() { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("zero"); + Mapmap = new HashMap(); + assertTrue(this.syncDeque.drainTailTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testDrainTailToMapTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.syncDeque.drainTailTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testDrainTailToMapTransformerTransformer() { + this.syncDeque.enqueueHead("one"); + this.syncDeque.enqueueHead("two"); + this.syncDeque.enqueueHead("zero"); + Mapmap = new HashMap(); + assertTrue(this.syncDeque.drainTailTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testDrainTailToMapTransformerTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.syncDeque.drainTailTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertTrue(map.isEmpty()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/eol/CheckWinEOL.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/eol/CheckWinEOL.java index 7f362da4c9..ca86f6ba5d 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/eol/CheckWinEOL.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/eol/CheckWinEOL.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License * v1.0, both of which accompany this distribution. @@ -47,7 +47,7 @@ public class CheckWinEOL { Iterable invalidJavaFiles = getAllJavaFilesWithInvalidWinEOL(rootDirectoryName); int count = 0; System.out.println("Java files with bogus EOL:"); - for (String invalidFileName : CollectionTools.sortedSet(IterableTools.transform(invalidJavaFiles, FILE_ABSOLUTE_PATH_TRANSFORMER))) { + for (String invalidFileName : CollectionTools.treeSet(IterableTools.transform(invalidJavaFiles, FILE_ABSOLUTE_PATH_TRANSFORMER))) { count++; System.out.print('\t'); System.out.println(invalidFileName); diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/io/FileToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/io/FileToolsTests.java index 2e2996fb25..500a313ce5 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/io/FileToolsTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/io/FileToolsTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2012 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -54,22 +54,22 @@ public class FileToolsTests } public void testFilesIn() { - Collection files = CollectionTools.collection(FileTools.files(this.tempDir.getPath())); + Collection files = CollectionTools.hashBag(FileTools.files(this.tempDir.getPath())); assertEquals("invalid file count", 3, files.size()); } public void testDirectoriesIn() { - Collection files = CollectionTools.collection(FileTools.directories(this.tempDir.getPath())); + Collection files = CollectionTools.hashBag(FileTools.directories(this.tempDir.getPath())); assertEquals("invalid directory count", 2, files.size()); } public void testFilesInTree() { - Collection files = CollectionTools.collection(FileTools.allFiles(this.tempDir.getPath())); + Collection files = CollectionTools.hashBag(FileTools.allFiles(this.tempDir.getPath())); assertEquals("invalid file count", 9, files.size()); } public void testDirectoriesInTree() { - Collection files = CollectionTools.collection(FileTools.allDirectories(this.tempDir.getPath())); + Collection files = CollectionTools.hashBag(FileTools.allDirectories(this.tempDir.getPath())); assertEquals("invalid directory count", 3, files.size()); } @@ -159,7 +159,7 @@ public class FileToolsTests FileFilter filter = this.buildFileFilter(prefix); Iterator filteredFilesIterator = FileTools.filter(FileTools.files(this.tempDir), filter); - Collection filteredFiles = CollectionTools.collection(filteredFilesIterator); + Collection filteredFiles = CollectionTools.hashBag(filteredFilesIterator); assertEquals(2, filteredFiles.size()); assertTrue(filteredFiles.contains(testFile1)); assertTrue(filteredFiles.contains(testFile2)); diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/GraphIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/GraphIterableTests.java index 679225ac79..95715eef43 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/GraphIterableTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/GraphIterableTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -121,7 +121,7 @@ public class GraphIterableTests } void setNeighbors(GraphNode[] neighbors) { - this.neighbors = ListTools.list(neighbors); + this.neighbors = ListTools.arrayList(neighbors); } public Iterable getNeighbors() { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/QueueIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/QueueIterableTests.java index 2695501acd..1d8ee7a7fa 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/QueueIterableTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/QueueIterableTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -10,10 +10,9 @@ package org.eclipse.jpt.common.utility.tests.internal.iterable; import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.collection.Queue; -import org.eclipse.jpt.common.utility.internal.collection.LinkedQueue; import org.eclipse.jpt.common.utility.internal.iterable.QueueIterable; +import org.eclipse.jpt.common.utility.internal.queue.LinkedQueue; +import org.eclipse.jpt.common.utility.queue.Queue; @SuppressWarnings("nls") public class QueueIterableTests extends TestCase { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/StackIterableTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/StackIterableTests.java index e28542f74a..3235a9ae34 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/StackIterableTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterable/StackIterableTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -12,10 +12,9 @@ package org.eclipse.jpt.common.utility.tests.internal.iterable; import java.util.Iterator; import junit.framework.TestCase; - -import org.eclipse.jpt.common.utility.collection.Stack; -import org.eclipse.jpt.common.utility.internal.collection.LinkedStack; import org.eclipse.jpt.common.utility.internal.iterable.StackIterable; +import org.eclipse.jpt.common.utility.internal.stack.LinkedStack; +import org.eclipse.jpt.common.utility.stack.Stack; @SuppressWarnings("nls") public class StackIterableTests extends TestCase { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/GraphIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/GraphIteratorTests.java index bb47dbe089..27792741fe 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/GraphIteratorTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/GraphIteratorTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 Oracle. All rights reserved. + * Copyright (c) 2005, 2015 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. @@ -141,7 +141,7 @@ public class GraphIteratorTests } void setNeighbors(GraphNode[] neighbors) { - this.neighbors = ListTools.list(neighbors); + this.neighbors = ListTools.arrayList(neighbors); } public Iterator neighbors() { diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/ReadOnlyCompositeListIteratorTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/ReadOnlyCompositeListIteratorTests.java index 72786c244a..0776ef1bc3 100644 --- a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/ReadOnlyCompositeListIteratorTests.java +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/iterator/ReadOnlyCompositeListIteratorTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -200,8 +200,8 @@ public class ReadOnlyCompositeListIteratorTests List> list = new ArrayList>(); list.add(integerList); list.add(floatList); - Transformer, ListIterator> transformer = ListTools.readOnlyListIteratorTransformer(); - ListIterator> numberIterators = IteratorTools.transform(list.listIterator(), transformer); + Transformer, ListIterator> transformer = ListTools.readOnlyListIteratorTransformer(); + ListIterator> numberIterators = IteratorTools.transform(list.listIterator(), transformer); ListIterator li = IteratorTools.concatenateReadOnly(numberIterators); 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/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 index 977a946187..b52a11b403 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -131,7 +131,7 @@ public class CollectionAspectAdapterTests extends TestCase { } public void testSubjectHolder() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.aa1.iterator())); assertNull(this.event1); this.subjectHolder1.setValue(this.subject2); @@ -139,7 +139,7 @@ public class CollectionAspectAdapterTests extends TestCase { assertEquals(this.event1Type, CHANGE); assertEquals(this.aa1, this.event1.getSource()); assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals(this.subject2Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject2Names(), CollectionTools.hashBag(this.aa1.iterator())); this.event1 = null; this.event1Type = null; @@ -157,11 +157,11 @@ public class CollectionAspectAdapterTests extends TestCase { assertEquals(this.event1Type, CHANGE); assertEquals(this.aa1, this.event1.getSource()); assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.aa1.iterator())); } public void testAdd() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.aa1.iterator())); assertNull(this.event1); this.subject1.addName("jam"); @@ -172,7 +172,7 @@ public class CollectionAspectAdapterTests extends TestCase { assertEquals("jam", ((CollectionAddEvent) this.event1).getItems().iterator().next()); Collection namesPlus = this.subject1Names(); namesPlus.add("jam"); - assertEquals(namesPlus, CollectionTools.bag(this.aa1.iterator())); + assertEquals(namesPlus, CollectionTools.hashBag(this.aa1.iterator())); this.event1 = null; this.event1Type = null; @@ -183,11 +183,11 @@ public class CollectionAspectAdapterTests extends TestCase { assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); assertEquals("jaz", ((CollectionAddEvent) this.event1).getItems().iterator().next()); namesPlus.add("jaz"); - assertEquals(namesPlus, CollectionTools.bag(this.aa1.iterator())); + assertEquals(namesPlus, CollectionTools.hashBag(this.aa1.iterator())); } public void testRemove() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.aa1.iterator())); assertNull(this.event1); this.subject1.removeName("foo"); @@ -198,7 +198,7 @@ public class CollectionAspectAdapterTests extends TestCase { assertEquals("foo", ((CollectionRemoveEvent) this.event1).getItems().iterator().next()); Collection namesMinus = this.subject1Names(); namesMinus.remove("foo"); - assertEquals(namesMinus, CollectionTools.bag(this.aa1.iterator())); + assertEquals(namesMinus, CollectionTools.hashBag(this.aa1.iterator())); this.event1 = null; this.event1Type = null; @@ -209,11 +209,11 @@ public class CollectionAspectAdapterTests extends TestCase { assertEquals(CollectionValueModel.VALUES, this.event1.getCollectionName()); assertEquals("bar", ((CollectionRemoveEvent) this.event1).getItems().iterator().next()); namesMinus.remove("bar"); - assertEquals(namesMinus, CollectionTools.bag(this.aa1.iterator())); + assertEquals(namesMinus, CollectionTools.hashBag(this.aa1.iterator())); } public void testCollectionChange() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.aa1.iterator())); assertNull(this.event1); this.subject1.addTwoNames("jam", "jaz"); @@ -224,12 +224,12 @@ public class CollectionAspectAdapterTests extends TestCase { Collection namesPlus2 = this.subject1Names(); namesPlus2.add("jam"); namesPlus2.add("jaz"); - assertEquals(namesPlus2, CollectionTools.bag(this.aa1.iterator())); + assertEquals(namesPlus2, CollectionTools.hashBag(this.aa1.iterator())); } public void testIterator() { - assertEquals(this.subject1Names(), CollectionTools.bag(this.subject1.names())); - assertEquals(this.subject1Names(), CollectionTools.bag(this.aa1.iterator())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.subject1.names())); + assertEquals(this.subject1Names(), CollectionTools.hashBag(this.aa1.iterator())); } public void testSize() { 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 index dbd9f43d2a..659b3d11f6 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -73,7 +73,7 @@ public class CollectionListValueModelAdapterTests extends TestCase { } private Collection adapterCollection() { - return CollectionTools.collection(this.adapter.iterator()); + return CollectionTools.hashBag(this.adapter.iterator()); } public void testStaleValue() { @@ -114,7 +114,7 @@ public class CollectionListValueModelAdapterTests extends TestCase { Collection adapterCollection = this.adapterCollection(); assertEquals(this.wrappedCollection, adapterCollection); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection, CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection, synchCollection); } @@ -136,7 +136,7 @@ public class CollectionListValueModelAdapterTests extends TestCase { Collection adapterCollection = this.adapterCollection(); assertEquals(this.wrappedCollection, adapterCollection); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection, CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection, synchCollection); } 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 index 7f02e0dad0..bdf7a7e20b 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -56,7 +56,7 @@ public class CollectionPropertyValueModelAdapterTests extends TestCase { } private Collection wrappedCollection() { - return CollectionTools.collection(this.wrappedCollectionHolder.iterator()); + return CollectionTools.hashBag(this.wrappedCollectionHolder.iterator()); } public void testValue() { 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 index 7827461785..22dd60c3b1 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -71,51 +71,51 @@ public class CompositeCollectionValueModelTests assertEquals(3, familiesSynch.size()); assertEquals(12, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(12, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); jetsons.removeMember(jetsons.memberNamed("Astro")); assertEquals(3, familiesSynch.size()); assertEquals(11, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(11, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); jetsons.removeMember(jetsons.memberNamed("Judy")); assertEquals(3, familiesSynch.size()); assertEquals(10, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(10, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); jetsons.addMember("Fido"); assertEquals(3, familiesSynch.size()); assertEquals(11, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(11, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); this.neighborhood.removeFamily(jetsons); assertEquals(2, familiesSynch.size()); assertEquals(7, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(7, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); Family bears = this.neighborhood.addFamily("Bear"); bears.addMember("Yogi"); assertEquals(3, familiesSynch.size()); assertEquals(8, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(8, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); bears.addMember("Boo-Boo"); assertEquals(3, familiesSynch.size()); assertEquals(9, IteratorTools.size(this.neighborhood.allMembers())); assertEquals(9, membersSynch.size()); - assertEquals(CollectionTools.bag(this.neighborhood.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(this.neighborhood.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); Neighborhood n2 = new Neighborhood("Hanna-Barbera 2"); this.neighborhoodHolder.setValue(n2); @@ -123,8 +123,8 @@ public class CompositeCollectionValueModelTests assertEquals(3, familiesSynch.size()); assertEquals(12, IteratorTools.size(n2.allMembers())); assertEquals(12, membersSynch.size()); - assertEquals(CollectionTools.bag(n2.allMembers()), membersSynch); - assertEquals(membersSynch, CollectionTools.bag(compositeCVM.iterator())); + assertEquals(CollectionTools.hashBag(n2.allMembers()), membersSynch); + assertEquals(membersSynch, CollectionTools.hashBag(compositeCVM.iterator())); } public void testNoTransformer() { 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 index 604397e227..2a356d3e17 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -103,7 +103,7 @@ public class ExtendedListValueModelWrapperTests extends TestCase { public void testIterator() { this.extendedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - assertEquals(this.buildExtendedList(), ListTools.list(this.extendedListHolder.iterator())); + assertEquals(this.buildExtendedList(), ListTools.arrayList(this.extendedListHolder.iterator())); } public void testSize() { @@ -121,7 +121,7 @@ public class ExtendedListValueModelWrapperTests extends TestCase { } private boolean extendedListContainsAny(Collection items) { - List extendedList = ListTools.list(this.extendedListHolder.iterator()); + List extendedList = ListTools.arrayList(this.extendedListHolder.iterator()); for (Iterator stream = items.iterator(); stream.hasNext(); ) { if (extendedList.contains(stream.next())) { return true; @@ -226,7 +226,7 @@ public class ExtendedListValueModelWrapperTests extends TestCase { this.eventType = null; this.listHolder.addAll(0, this.buildList()); this.verifyEvent(ADD); - assertEquals(this.buildList(), ListTools.list(((ListAddEvent) this.event).getItems())); + assertEquals(this.buildList(), ListTools.arrayList(((ListAddEvent) this.event).getItems())); this.event = null; this.eventType = null; 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 index 20067751fd..df7106b2eb 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -134,14 +134,14 @@ public class ListAspectAdapterTests extends TestCase { } public void testSubjectHolder() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(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(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject2Names(), ListTools.arrayList(this.aa1.listIterator())); this.event1 = null; this.subjectHolder1.setValue(null); @@ -155,11 +155,11 @@ public class ListAspectAdapterTests extends TestCase { assertNotNull(this.event1); assertEquals(this.aa1, this.event1.getSource()); assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); } public void testAdd() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); assertNull(this.event1); this.subject1.addName("jam"); @@ -170,7 +170,7 @@ public class ListAspectAdapterTests extends TestCase { assertEquals("jam", ((ListAddEvent) this.event1).getItems().iterator().next()); List namesPlus = this.subject1Names(); namesPlus.add("jam"); - assertEquals(namesPlus, ListTools.list(this.aa1.listIterator())); + assertEquals(namesPlus, ListTools.arrayList(this.aa1.listIterator())); this.event1 = null; this.aa1.add(2, "jaz"); @@ -180,11 +180,11 @@ public class ListAspectAdapterTests extends TestCase { assertEquals(2, ((ListAddEvent) this.event1).getIndex()); assertEquals("jaz", ((ListAddEvent) this.event1).getItems().iterator().next()); namesPlus.add(2, "jaz"); - assertEquals(namesPlus, ListTools.list(this.aa1.listIterator())); + assertEquals(namesPlus, ListTools.arrayList(this.aa1.listIterator())); } public void testDefaultAdd() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); assertNull(this.event1); List items = new ArrayList(); @@ -202,11 +202,11 @@ public class ListAspectAdapterTests extends TestCase { assertEquals("jam", ((ListAddEvent) this.event1).getItems().iterator().next()); List namesPlus = this.subject1Names(); namesPlus.addAll(2, items); - assertEquals(namesPlus, ListTools.list(this.aa1.listIterator())); + assertEquals(namesPlus, ListTools.arrayList(this.aa1.listIterator())); } public void testRemove() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); assertNull(this.event1); String removedName = this.subject1.removeName(0); // should be "foo" @@ -217,7 +217,7 @@ public class ListAspectAdapterTests extends TestCase { assertEquals(removedName, ((ListRemoveEvent) this.event1).getItems().iterator().next()); List namesMinus = this.subject1Names(); namesMinus.remove(0); - assertEquals(namesMinus, ListTools.list(this.aa1.listIterator())); + assertEquals(namesMinus, ListTools.arrayList(this.aa1.listIterator())); this.event1 = null; Object removedItem = this.aa1.remove(0); @@ -227,11 +227,11 @@ public class ListAspectAdapterTests extends TestCase { assertEquals(0, ((ListRemoveEvent) this.event1).getIndex()); assertEquals(removedItem, ((ListRemoveEvent) this.event1).getItems().iterator().next()); namesMinus.remove(0); - assertEquals(namesMinus, ListTools.list(this.aa1.listIterator())); + assertEquals(namesMinus, ListTools.arrayList(this.aa1.listIterator())); } public void testDefaultLength() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); assertNull(this.event1); List items = new ArrayList(); @@ -248,11 +248,11 @@ public class ListAspectAdapterTests extends TestCase { List namesPlus = this.subject1Names(); namesPlus.remove(1); namesPlus.remove(1); - assertEquals(namesPlus, ListTools.list(this.aa1.listIterator())); + assertEquals(namesPlus, ListTools.arrayList(this.aa1.listIterator())); } public void testReplace() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); assertNull(this.event1); String replacedName = this.subject1.setName(0, "jelly"); // should be "foo" @@ -264,7 +264,7 @@ public class ListAspectAdapterTests extends TestCase { assertEquals(replacedName, ((ListReplaceEvent) this.event1).getOldItems().iterator().next()); List namesChanged = this.subject1Names(); namesChanged.set(0, "jelly"); - assertEquals(namesChanged, ListTools.list(this.aa1.listIterator())); + assertEquals(namesChanged, ListTools.arrayList(this.aa1.listIterator())); this.event1 = null; replacedName = this.subject1.setName(1, "roll"); // should be "bar" @@ -277,11 +277,11 @@ public class ListAspectAdapterTests extends TestCase { namesChanged = this.subject1Names(); namesChanged.set(0, "jelly"); namesChanged.set(1, "roll"); - assertEquals(namesChanged, ListTools.list(this.aa1.listIterator())); + assertEquals(namesChanged, ListTools.arrayList(this.aa1.listIterator())); } public void testListChange() { - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); assertNull(this.event1); this.subject1.addTwoNames("jam", "jaz"); @@ -291,12 +291,12 @@ public class ListAspectAdapterTests extends TestCase { List namesPlus2 = this.subject1Names(); namesPlus2.add(0, "jaz"); namesPlus2.add(0, "jam"); - assertEquals(namesPlus2, ListTools.list(this.aa1.listIterator())); + assertEquals(namesPlus2, ListTools.arrayList(this.aa1.listIterator())); } public void testIterator() { - assertEquals(this.subject1Names(), ListTools.list(this.subject1.names())); - assertEquals(this.subject1Names(), ListTools.list(this.aa1.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.subject1.names())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.aa1.listIterator())); } public void testGet() { 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 index 9d82c240b6..a3e0d7f446 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -54,7 +54,7 @@ public class ListCollectionValueModelAdapterTests extends TestCase { } private Collection wrappedCollection() { - return CollectionTools.collection(this.wrappedList.iterator()); + return CollectionTools.hashBag(this.wrappedList.iterator()); } @Override @@ -73,7 +73,7 @@ public class ListCollectionValueModelAdapterTests extends TestCase { this.wrappedListHolder.add(0, "foo"); this.wrappedListHolder.add(1, "bar"); this.wrappedListHolder.add(2, "baz"); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(3, adapterCollection.size()); assertEquals(this.wrappedCollection(), adapterCollection); } @@ -87,17 +87,17 @@ public class ListCollectionValueModelAdapterTests extends TestCase { this.wrappedListHolder.add(0, "foo"); this.wrappedListHolder.add(1, "bar"); this.wrappedListHolder.add(2, "baz"); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(3, adapterCollection.size()); assertEquals(this.wrappedCollection(), adapterCollection); this.adapter.removeCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); + adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(0, adapterCollection.size()); assertEquals(new HashBag(), adapterCollection); this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); + adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(3, adapterCollection.size()); assertEquals(this.wrappedCollection(), adapterCollection); } @@ -114,9 +114,9 @@ public class ListCollectionValueModelAdapterTests extends TestCase { this.wrappedListHolder.add(5, "jaz"); assertEquals(6, this.wrappedList.size()); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals(this.wrappedCollection(), CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection(), CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection(), synchCollection); } @@ -135,9 +135,9 @@ public class ListCollectionValueModelAdapterTests extends TestCase { assertFalse(this.wrappedList.contains("foo")); assertEquals(4, this.wrappedList.size()); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(this.wrappedCollection(), adapterCollection); - assertEquals(this.wrappedCollection(), CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection(), CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection(), synchCollection); } @@ -164,7 +164,7 @@ public class ListCollectionValueModelAdapterTests extends TestCase { assertFalse(this.wrappedList.contains("foo")); assertEquals(4, this.wrappedList.size()); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(this.wrappedCollection(), adapterCollection); } @@ -182,7 +182,7 @@ public class ListCollectionValueModelAdapterTests extends TestCase { this.wrappedListHolder.add(0, "foo"); this.wrappedListHolder.add(1, "bar"); this.wrappedListHolder.add(2, "baz"); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(3, adapterCollection.size()); this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, new TestListener() { @Override @@ -198,7 +198,7 @@ public class ListCollectionValueModelAdapterTests extends TestCase { } }); this.wrappedListHolder.set(0, "joo"); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); + adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(3, adapterCollection.size()); assertEquals(this.wrappedCollection(), adapterCollection); } 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 index e667223953..e345b5b475 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -125,14 +125,14 @@ public final class ListCuratorTests } public void testSubjectHolder() { - assertEquals(this.subject1Names(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(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(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject2Names(), ListTools.arrayList(this.curator.listIterator())); this.event1 = null; this.subjectHolder1.setValue(null); @@ -146,11 +146,11 @@ public final class ListCuratorTests assertNotNull(this.event1); assertEquals(this.curator, this.event1.getSource()); assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); - assertEquals(this.subject1Names(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.curator.listIterator())); } public void testAdd() { - assertEquals(this.subject1Names(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.curator.listIterator())); assertNull(this.event1); this.subject1.addString("echo"); @@ -161,7 +161,7 @@ public final class ListCuratorTests assertEquals("echo", ((ListAddEvent) this.event1).getItems().iterator().next()); List stringsPlus = this.subject1Names(); stringsPlus.add("echo"); - assertEquals(stringsPlus, ListTools.list(this.curator.listIterator())); + assertEquals(stringsPlus, ListTools.arrayList(this.curator.listIterator())); this.event1 = null; this.subject1.addString(0, "zulu"); @@ -171,11 +171,11 @@ public final class ListCuratorTests assertEquals(0, ((ListAddEvent) this.event1).getIndex()); assertEquals("zulu", ((ListAddEvent) this.event1).getItems().iterator().next()); stringsPlus.add(0, "zulu"); - assertEquals(stringsPlus, ListTools.list(this.curator.listIterator())); + assertEquals(stringsPlus, ListTools.arrayList(this.curator.listIterator())); } public void testRemove() { - assertEquals(this.subject1Names(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.curator.listIterator())); assertNull(this.event1); String removedString = this.subject1.removeString(0); // should be "alpha" @@ -186,7 +186,7 @@ public final class ListCuratorTests assertEquals(removedString, ((ListRemoveEvent) this.event1).getItems().iterator().next()); List stringsMinus = this.subject1Names(); stringsMinus.remove(0); - assertEquals(stringsMinus, ListTools.list(this.curator.listIterator())); + assertEquals(stringsMinus, ListTools.arrayList(this.curator.listIterator())); removedString = this.subject1.removeString(2); // should be "delta" assertNotNull(this.event1); @@ -195,11 +195,11 @@ public final class ListCuratorTests assertEquals(2, ((ListRemoveEvent) this.event1).getIndex()); assertEquals(removedString, ((ListRemoveEvent) this.event1).getItems().iterator().next()); stringsMinus.remove(2); - assertEquals(stringsMinus, ListTools.list(this.curator.listIterator())); + assertEquals(stringsMinus, ListTools.arrayList(this.curator.listIterator())); } public void testCompleteListChange() { - assertEquals(this.subject1Names(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.curator.listIterator())); assertNull(this.event1); this.subject1.setStrings(this.subject2Names()); @@ -207,20 +207,20 @@ public final class ListCuratorTests assertEquals(this.curator, this.event1.getSource()); assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); List newStrings = this.subject2Names(); - assertEquals(newStrings, ListTools.list(this.curator.listIterator())); + assertEquals(newStrings, ListTools.arrayList(this.curator.listIterator())); } public void testPartialListChange() { - List startingList = ListTools.list(this.curator.listIterator()); + List startingList = ListTools.arrayList(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 newStrings = ListTools.list(new String[] {new String("bravo"), new String("alpha"), "echo", "delta", "foxtrot"}); + List newStrings = ListTools.arrayList(new String[] {new String("bravo"), new String("alpha"), "echo", "delta", "foxtrot"}); this.subject1.setStrings(newStrings); - List finalList = ListTools.list(this.curator.listIterator()); + List finalList = ListTools.arrayList(this.curator.listIterator()); assertNotNull(this.event1); assertEquals(this.curator, this.event1.getSource()); assertEquals(ListValueModel.LIST_VALUES, this.event1.getListName()); @@ -230,8 +230,8 @@ public final class ListCuratorTests } public void testIterator() { - assertEquals(this.subject1Names(), ListTools.list(this.subject1.strings())); - assertEquals(this.subject1Names(), ListTools.list(this.curator.listIterator())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.subject1.strings())); + assertEquals(this.subject1Names(), ListTools.arrayList(this.curator.listIterator())); } public void testGet() { @@ -339,7 +339,7 @@ public final class ListCuratorTests } public void setStrings(String[] strings) { - this.strings = ListTools.list(strings); + this.strings = ListTools.arrayList(strings); this.fireStateChanged(); } } 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 index 7ba6e13ee0..c2c087d88b 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -50,7 +50,7 @@ public class PropertyCollectionValueModelAdapterTests extends TestCase { } private Collection wrappedCollection() { - return CollectionTools.collection(new SingleElementIterator(this.wrappedValueHolder.getValue())); + return CollectionTools.hashBag(new SingleElementIterator(this.wrappedValueHolder.getValue())); } @Override @@ -65,7 +65,7 @@ public class PropertyCollectionValueModelAdapterTests extends TestCase { public void itemsAdded(CollectionAddEvent e) {/* OK */} }); this.wrappedValueHolder.setValue("foo"); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(1, adapterCollection.size()); assertEquals(this.wrappedCollection(), adapterCollection); assertEquals("foo", adapterCollection.iterator().next()); @@ -78,18 +78,18 @@ public class PropertyCollectionValueModelAdapterTests extends TestCase { }; this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); this.wrappedValueHolder.setValue("foo"); - Collection adapterCollection = CollectionTools.collection(this.adapter.iterator()); + Collection adapterCollection = CollectionTools.hashBag(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()); + adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(0, adapterCollection.size()); assertEquals(new HashBag(), adapterCollection); this.adapter.addCollectionChangeListener(CollectionValueModel.VALUES, listener); - adapterCollection = CollectionTools.collection(this.adapter.iterator()); + adapterCollection = CollectionTools.hashBag(this.adapter.iterator()); assertEquals(1, adapterCollection.size()); assertEquals(this.wrappedCollection(), adapterCollection); assertEquals("foo", adapterCollection.iterator().next()); 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 index 4b34f92d22..d6b0aff0d6 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -53,7 +53,7 @@ public class PropertyListValueModelAdapterTests extends TestCase { } private Collection wrappedList() { - return ListTools.list(new SingleElementIterator(this.wrappedValueHolder.getValue())); + return ListTools.arrayList(new SingleElementIterator(this.wrappedValueHolder.getValue())); } @Override @@ -69,7 +69,7 @@ public class PropertyListValueModelAdapterTests extends TestCase { }); assertFalse(this.adapter.iterator().hasNext()); this.wrappedValueHolder.setValue("foo"); - List adapterList = ListTools.list(this.adapter.iterator()); + List adapterList = ListTools.arrayList(this.adapter.iterator()); assertEquals(1, adapterList.size()); assertEquals(this.wrappedList(), adapterList); assertEquals("foo", adapterList.iterator().next()); @@ -108,18 +108,18 @@ public class PropertyListValueModelAdapterTests extends TestCase { }; this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, listener); this.wrappedValueHolder.setValue("foo"); - List adapterList = ListTools.list(this.adapter.iterator()); + List adapterList = ListTools.arrayList(this.adapter.iterator()); assertEquals(1, adapterList.size()); assertEquals(this.wrappedList(), adapterList); assertEquals("foo", adapterList.iterator().next()); this.adapter.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - adapterList = ListTools.list(this.adapter.iterator()); + adapterList = ListTools.arrayList(this.adapter.iterator()); assertEquals(0, adapterList.size()); assertEquals(new ArrayList(), adapterList); this.adapter.addListChangeListener(ListValueModel.LIST_VALUES, listener); - adapterList = ListTools.list(this.adapter.iterator()); + adapterList = ListTools.arrayList(this.adapter.iterator()); assertEquals(1, adapterList.size()); assertEquals(this.wrappedList(), adapterList); assertEquals("foo", adapterList.iterator().next()); 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 index 0b72b434e0..411d8bce06 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -297,21 +297,21 @@ public class SetCollectionValueModelTests extends TestCase { } private void verify(CollectionValueModel cvm, String... expectedItems) { - Bag actual = CollectionTools.bag(cvm); - Bag expected = CollectionTools.bag(expectedItems); + Bag actual = CollectionTools.hashBag(cvm); + Bag expected = CollectionTools.hashBag(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())); + assertEquals(CollectionTools.hashBag(expectedItems), CollectionTools.hashBag(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())); + assertEquals(CollectionTools.hashBag(expectedItems), CollectionTools.hashBag(event.getItems())); } private void verifyEvent(CollectionClearEvent event, Object source) { @@ -322,7 +322,7 @@ public class SetCollectionValueModelTests extends TestCase { 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())); + assertEquals(CollectionTools.hashBag(expectedItems), CollectionTools.hashBag(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 index d4592b8a9c..2960323aba 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -97,8 +97,8 @@ public class SimpleCollectionValueModelTests extends TestCase { } public void testIterator() { - assertEquals(this.buildBag(), CollectionTools.bag(this.bagHolder.iterator())); - assertEquals(this.buildSet(), CollectionTools.set(this.setHolder.iterator())); + assertEquals(this.buildBag(), CollectionTools.hashBag(this.bagHolder.iterator())); + assertEquals(this.buildSet(), CollectionTools.hashSet(this.setHolder.iterator())); } public void testSize() { @@ -123,7 +123,7 @@ public class SimpleCollectionValueModelTests extends TestCase { } private boolean bagHolderContainsAny(Collection items) { - Bag bag = CollectionTools.bag(this.bagHolder.iterator()); + Bag bag = CollectionTools.hashBag(this.bagHolder.iterator()); for (String string : items) { if (bag.contains(string)) { return true; @@ -133,7 +133,7 @@ public class SimpleCollectionValueModelTests extends TestCase { } private boolean setHolderContainsAny(Collection items) { - Set set = CollectionTools.set(this.setHolder.iterator()); + Set set = CollectionTools.hashSet(this.setHolder.iterator()); for (String string : items) { if (set.contains(string)) { return true; @@ -291,7 +291,7 @@ public class SimpleCollectionValueModelTests extends TestCase { this.bagEventType = null; this.bagHolder.addAll(this.buildBag()); this.verifyBagEvent(ADD); - assertEquals(this.buildBag(), CollectionTools.bag(((CollectionAddEvent) this.bagEvent).getItems())); + assertEquals(this.buildBag(), CollectionTools.hashBag(((CollectionAddEvent) this.bagEvent).getItems())); } private void verifySetChange() { 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 index 2730490235..f4ce67b071 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -89,15 +89,15 @@ public class SimpleListValueModelTests extends TestCase { } public void testIterator() { - assertEquals(this.buildList(), ListTools.list(this.listHolder.iterator())); + assertEquals(this.buildList(), ListTools.arrayList(this.listHolder.iterator())); } public void testListIterator() { - assertEquals(this.buildList(), ListTools.list(this.listHolder.listIterator())); + assertEquals(this.buildList(), ListTools.arrayList(this.listHolder.listIterator())); } public void testListIteratorInt() { - assertEquals(ListTools.list(this.buildList().listIterator(1)), ListTools.list(this.listHolder.listIterator(1))); + assertEquals(ListTools.arrayList(this.buildList().listIterator(1)), ListTools.arrayList(this.listHolder.listIterator(1))); } public void testSize() { @@ -113,7 +113,7 @@ public class SimpleListValueModelTests extends TestCase { } private boolean listContainsAny(Collection items) { - Set set = CollectionTools.set(this.listHolder.iterator()); + Set set = CollectionTools.hashSet(this.listHolder.iterator()); for (Iterator stream = items.iterator(); stream.hasNext(); ) { if (set.contains(stream.next())) { return true; @@ -287,7 +287,7 @@ public class SimpleListValueModelTests extends TestCase { this.eventType = null; this.listHolder.addAll(0, this.buildList()); this.verifyEvent(ADD); - assertEquals(this.buildList(), ListTools.list(((ListAddEvent) this.event).getItems())); + assertEquals(this.buildList(), ListTools.arrayList(((ListAddEvent) this.event).getItems())); this.event = null; this.eventType = null; 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 index 83752b4735..060018bcde 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -69,7 +69,7 @@ public class SortedListValueModelAdapterTests extends TestCase { Collection sortedSet = new TreeSet(comparator); sortedSet.addAll(expected); List expectedList = new ArrayList(sortedSet); - List actualList = ListTools.list(actual.iterator()); + List actualList = ListTools.arrayList(actual.iterator()); assertEquals(expectedList, actualList); } @@ -100,7 +100,7 @@ public class SortedListValueModelAdapterTests extends TestCase { assertEquals(6, this.wrappedCollection.size()); this.verifyList(this.wrappedCollection, this.adapter); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection, CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection, synchCollection); } @@ -120,7 +120,7 @@ public class SortedListValueModelAdapterTests extends TestCase { assertEquals(4, this.wrappedCollection.size()); this.verifyList(this.wrappedCollection, this.adapter); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection, CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection, synchCollection); } @@ -161,12 +161,12 @@ public class SortedListValueModelAdapterTests extends TestCase { assertEquals(6, this.wrappedCollection.size()); this.verifyList(this.wrappedCollection, this.adapter); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection, CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection, synchCollection); this.adapter.setComparator(ComparatorTools.reverseComparator()); this.verifyList(this.wrappedCollection, this.adapter, ComparatorTools.reverseComparator()); - assertEquals(this.wrappedCollection, CollectionTools.collection(synchList.iterator())); + assertEquals(this.wrappedCollection, CollectionTools.hashBag(synchList.iterator())); assertEquals(this.wrappedCollection, synchCollection); } 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 index e2a384aec0..985de8b3e3 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -66,7 +66,7 @@ public class SortedListValueModelWrapperTests extends TestCase { Collection sortedSet = new TreeSet(comparator); sortedSet.addAll(expected); List expectedList = new ArrayList(sortedSet); - List actualList = ListTools.list(actual); + List actualList = ListTools.arrayList(actual); assertEquals(expectedList, actualList); } @@ -98,7 +98,7 @@ public class SortedListValueModelWrapperTests extends TestCase { this.verifyList(this.list, this.sortedListModel); assertEquals(this.list, synchList); - assertEquals(ListTools.list(this.sortedListModel), sortedSynchList); + assertEquals(ListTools.arrayList(this.sortedListModel), sortedSynchList); } public void testRemoveItem() { @@ -118,7 +118,7 @@ public class SortedListValueModelWrapperTests extends TestCase { this.verifyList(this.list, this.sortedListModel); assertEquals(this.list, synchList); - assertEquals(ListTools.list(this.sortedListModel), sortedSynchList); + assertEquals(ListTools.arrayList(this.sortedListModel), sortedSynchList); } public void testReplaceItem() { @@ -138,7 +138,7 @@ public class SortedListValueModelWrapperTests extends TestCase { this.verifyList(this.list, this.sortedListModel); assertEquals(this.list, synchList); - assertEquals(ListTools.list(this.sortedListModel), sortedSynchList); + assertEquals(ListTools.arrayList(this.sortedListModel), sortedSynchList); } public void testListSynch() { @@ -179,7 +179,7 @@ public class SortedListValueModelWrapperTests extends TestCase { this.verifyList(this.list, this.sortedListModel); assertEquals(this.list, synchList); - assertEquals(ListTools.list(this.sortedListModel), sortedSynchList); + assertEquals(ListTools.arrayList(this.sortedListModel), sortedSynchList); this.sortedListModel.setComparator(ComparatorTools.reverseComparator()); this.verifyList(this.list, this.sortedListModel, ComparatorTools.reverseComparator()); 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 index 43fcc4603c..dc88239288 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -53,7 +53,7 @@ public class StaticCollectionValueModelTests extends TestCase { } public void testIterator() { - assertEquals(buildCollection(), CollectionTools.bag(this.collectionHolder.iterator())); + assertEquals(buildCollection(), CollectionTools.hashBag(this.collectionHolder.iterator())); } public void testSize() { 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 index c02f54d7a2..151b98b5e4 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -56,7 +56,7 @@ public class StaticListValueModelTests extends TestCase { } public void testIterator() { - assertEquals(buildList(), ListTools.list(this.listHolder.listIterator())); + assertEquals(buildList(), ListTools.arrayList(this.listHolder.listIterator())); } public void testSize() { 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 index ecc491ff1c..4cd4659dc4 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -126,16 +126,16 @@ public class TransformationListValueModelTests extends TestCase { public void testIterator() { this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, this.buildListener()); - assertEquals(this.buildTransformedList(), ListTools.list(this.transformedListHolder.iterator())); + assertEquals(this.buildTransformedList(), ListTools.arrayList(this.transformedListHolder.iterator())); } public void testStaleValues() { ListChangeListener listener = this.buildListener(); this.transformedListHolder.addListChangeListener(ListValueModel.LIST_VALUES, listener); - assertEquals(this.buildTransformedList(), ListTools.list(this.transformedListHolder.iterator())); + assertEquals(this.buildTransformedList(), ListTools.arrayList(this.transformedListHolder.iterator())); this.transformedListHolder.removeListChangeListener(ListValueModel.LIST_VALUES, listener); - assertEquals(Collections.EMPTY_LIST, ListTools.list(this.transformedListHolder.iterator())); + assertEquals(Collections.EMPTY_LIST, ListTools.arrayList(this.transformedListHolder.iterator())); } public void testSize() { @@ -152,7 +152,7 @@ public class TransformationListValueModelTests extends TestCase { } private boolean transformedListContainsAny(Collection items) { - List transformedList = ListTools.list(this.transformedListHolder.iterator()); + List transformedList = ListTools.arrayList(this.transformedListHolder.iterator()); for (Iterator stream = items.iterator(); stream.hasNext(); ) { if (transformedList.contains(stream.next())) { return true; @@ -229,7 +229,7 @@ public class TransformationListValueModelTests extends TestCase { this.eventType = null; this.listHolder.addAll(0, this.buildList()); this.verifyEvent(ADD); - assertEquals(this.buildTransformedList(), ListTools.list(((ListAddEvent) this.event).getItems())); + assertEquals(this.buildTransformedList(), ListTools.arrayList(((ListAddEvent) this.event).getItems())); this.event = null; this.eventType = null; 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 index 82677aac1c..00f0b39ca9 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -230,7 +230,7 @@ public class TableModelAdapterTests } private List sortedNames() { - return new ArrayList(CollectionTools.sortedSet(this.crowd.peopleNames())); + return new ArrayList(CollectionTools.treeSet(this.crowd.peopleNames())); } private TableModelListener buildSingleEventListener() { 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 index 04ebcba194..69a3d405b4 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2012 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -242,7 +242,7 @@ public class TreeModelAdapterUITest { if (stream == null) { return Collections.emptyList(); } - return ListTools.list(new EnumerationIterator(stream)); + return ListTools.arrayList(new EnumerationIterator(stream)); } // ********** behavior ********** diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ArrayQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ArrayQueueTests.java new file mode 100644 index 0000000000..9329535119 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ArrayQueueTests.java @@ -0,0 +1,250 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.queue; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.queue.ArrayQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class ArrayQueueTests + extends QueueTests +{ + public ArrayQueueTests(String name) { + super(name); + } + + @Override + Queue buildQueue() { + return QueueTools.arrayQueue(); + } + + public void testConstructor_IAE() { + boolean exCaught = false; + try { + Queue queue = QueueTools.arrayQueue(-1); + fail("bogus deque: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEnsureCapacity() { + ArrayQueue queue = QueueTools.arrayQueue(0); + queue.ensureCapacity(7); + assertEquals(7, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testTrimToSize() { + ArrayQueue queue = QueueTools.arrayQueue(10); + queue.enqueue("foo"); + queue.enqueue("bar"); + queue.trimToSize(); + assertEquals(2, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testTrimToSize_noChange() { + ArrayQueue queue = QueueTools.arrayQueue(2); + queue.enqueue("foo"); + queue.enqueue("bar"); + queue.trimToSize(); + assertEquals(2, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testCollectionConstructor() { + ArrayList c = new ArrayList(); + c.add("first"); + c.add("second"); + c.add("third"); + c.add("fourth"); + c.add("fifth"); + c.add("sixth"); + c.add("seventh"); + c.add("eighth"); + c.add("ninth"); + c.add("tenth"); // force some free space + Queue queue = QueueTools.arrayQueue(c); + + assertFalse(queue.isEmpty()); + assertEquals("first", queue.peek()); + queue.enqueue("eleventh"); + queue.enqueue("twelfth"); + + assertEquals("first", queue.peek()); + assertEquals("first", queue.dequeue()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.peek()); + assertEquals("third", queue.dequeue()); + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertEquals("eleventh", queue.dequeue()); + assertEquals("twelfth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testWrappedElements() { + Queue queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + + // make room for 11 and 12 + assertEquals("first", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeue()); + + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + queue.enqueue("eleventh"); + queue.enqueue("twelfth"); + + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertEquals("eleventh", queue.dequeue()); + assertEquals("twelfth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceeded() { + Queue queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + queue.enqueue("eleventh"); + queue.enqueue("twelfth"); + + assertEquals("first", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeue()); + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertEquals("eleventh", queue.dequeue()); + assertEquals("twelfth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededWithWrappedElements() { + Queue queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + + assertEquals("first", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeue()); + + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + queue.enqueue("eleventh"); + queue.enqueue("twelfth"); + queue.enqueue("thirteenth"); + queue.enqueue("fourteenth"); + queue.enqueue("fifteenth"); + + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertEquals("eleventh", queue.dequeue()); + assertEquals("twelfth", queue.dequeue()); + assertEquals("thirteenth", queue.dequeue()); + assertEquals("fourteenth", queue.dequeue()); + assertEquals("fifteenth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testSerialization_empty() throws Exception { + Queue original = new ArrayQueue(3); + Queue clone = TestTools.serialize(original); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("fourth"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testSerialization_fullArray() throws Exception { + Queue queue = new ArrayQueue(3); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + public void testSerialization_wrappedArray() throws Exception { + Queue queue = new ArrayQueue(3); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + queue.dequeue(); + queue.enqueue("fourth"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/DequeQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/DequeQueueTests.java new file mode 100644 index 0000000000..7bbc809da1 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/DequeQueueTests.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.queue.Queue; + +public class DequeQueueTests + extends QueueTests +{ + public DequeQueueTests(String name) { + super(name); + } + + @Override + Queue buildQueue() { + return QueueTools.adapt(DequeTools.arrayDeque()); + } + + @Override + public void testClone() { + // unsupported + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/EmptyQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/EmptyQueueTests.java new file mode 100644 index 0000000000..e8ec2c36aa --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/EmptyQueueTests.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.internal.queue.EmptyQueue; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class EmptyQueueTests + extends TestCase +{ + public EmptyQueueTests(String name) { + super(name); + } + + public void testEnqueue() { + Queue queue = EmptyQueue.instance(); + boolean exCaught = false; + try { + queue.enqueue("junk"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testDequeue() { + Queue queue = EmptyQueue.instance(); + boolean exCaught = false; + try { + String bogus = queue.dequeue(); + fail(bogus); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testPeek() { + Queue queue = EmptyQueue.instance(); + boolean exCaught = false; + try { + String bogus = queue.peek(); + fail(bogus); + } catch (NoSuchElementException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIsEmpty() { + Queue queue = EmptyQueue.instance(); + assertTrue(queue.isEmpty()); + } + + public void testToString() { + Queue queue = EmptyQueue.instance(); + assertEquals("[]", queue.toString()); + } + + public void testSerialization() throws Exception { + Queue queue = EmptyQueue.instance(); + assertSame(queue, TestTools.serialize(queue)); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/FixedCapacityArrayQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/FixedCapacityArrayQueueTests.java new file mode 100644 index 0000000000..51dde90d22 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/FixedCapacityArrayQueueTests.java @@ -0,0 +1,216 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.internal.queue.FixedCapacityArrayQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.queue.Queue; + +@SuppressWarnings("nls") +public class FixedCapacityArrayQueueTests + extends QueueTests +{ + public FixedCapacityArrayQueueTests(String name) { + super(name); + } + + @Override + FixedCapacityArrayQueue buildQueue() { + return QueueTools.fixedCapacityArrayQueue(10); + } + + public void testCollectionConstructor() { + ArrayList c = new ArrayList(); + c.add("first"); + c.add("second"); + c.add("third"); + c.add("fourth"); + c.add("fifth"); + c.add("sixth"); + c.add("seventh"); + c.add("eighth"); + c.add("ninth"); + c.add("tenth"); + Queue queue = QueueTools.fixedCapacityArrayQueue(c); + + assertFalse(queue.isEmpty()); + assertEquals("first", queue.peek()); + assertEquals("first", queue.dequeue()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.peek()); + assertEquals("third", queue.dequeue()); + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testIsFull() { + FixedCapacityArrayQueue queue = this.buildQueue(); + assertFalse(queue.isFull()); + queue.enqueue("first"); + assertFalse(queue.isFull()); + queue.enqueue("second"); + assertFalse(queue.isFull()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + assertTrue(queue.isFull()); + + queue.dequeue(); + assertFalse(queue.isEmpty()); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + assertFalse(queue.isFull()); + } + + public void testWrappedElements() { + Queue queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + + // make room for 11 and 12 + assertEquals("first", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeue()); + + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + queue.enqueue("eleventh"); + queue.enqueue("twelfth"); + + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertEquals("eleventh", queue.dequeue()); + assertEquals("twelfth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceeded() { + Queue queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + + boolean exCaught = false; + try { + queue.enqueue("eleventh"); + fail("bogus"); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertEquals("first", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeue()); + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testArrayCapacityExceededWithWrappedElements() { + Queue queue = this.buildQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue("first"); + assertFalse(queue.isEmpty()); + queue.enqueue("second"); + assertFalse(queue.isEmpty()); + queue.enqueue("third"); + queue.enqueue("fourth"); + queue.enqueue("fifth"); + queue.enqueue("sixth"); + + assertEquals("first", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("second", queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals("third", queue.dequeue()); + + queue.enqueue("seventh"); + queue.enqueue("eighth"); + queue.enqueue("ninth"); + queue.enqueue("tenth"); + queue.enqueue("eleventh"); + queue.enqueue("twelfth"); + queue.enqueue("thirteenth"); + + boolean exCaught = false; + try { + queue.enqueue("fourteenth"); + fail("bogus"); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + + assertEquals("fourth", queue.dequeue()); + assertEquals("fifth", queue.dequeue()); + assertEquals("sixth", queue.dequeue()); + assertEquals("seventh", queue.dequeue()); + assertEquals("eighth", queue.dequeue()); + assertEquals("ninth", queue.dequeue()); + assertEquals("tenth", queue.dequeue()); + assertEquals("eleventh", queue.dequeue()); + assertEquals("twelfth", queue.dequeue()); + assertEquals("thirteenth", queue.dequeue()); + assertTrue(queue.isEmpty()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/JptCommonUtilityQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/JptCommonUtilityQueueTests.java new file mode 100644 index 0000000000..4bf7ac7906 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/JptCommonUtilityQueueTests.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * decentralize test creation code + */ +public class JptCommonUtilityQueueTests { + + public static Test suite() { + TestSuite suite = new TestSuite(JptCommonUtilityQueueTests.class.getPackage().getName()); + + suite.addTestSuite(ArrayQueueTests.class); + suite.addTestSuite(DequeQueueTests.class); + suite.addTestSuite(EmptyQueueTests.class); + suite.addTestSuite(FixedCapacityArrayQueueTests.class); + suite.addTestSuite(LinkedQueueTests.class); + suite.addTestSuite(ListQueueTests.class); + suite.addTestSuite(PriorityQueueTests.class); + suite.addTestSuite(QueueToolsTests.class); + suite.addTestSuite(StackQueueTests.class); + suite.addTestSuite(SynchronizedQueueTests.class); + + return suite; + } + + private JptCommonUtilityQueueTests() { + super(); + throw new UnsupportedOperationException(); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/LinkedQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/LinkedQueueTests.java new file mode 100644 index 0000000000..3795806607 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/LinkedQueueTests.java @@ -0,0 +1,230 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.queue; + +import java.util.Arrays; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.queue.LinkedQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class LinkedQueueTests + extends QueueTests +{ + public LinkedQueueTests(String name) { + super(name); + } + + @Override + Queue buildQueue() { + return QueueTools.linkedQueue(); + } + + public void testConstructorInt_IAE() { + boolean exCaught = false; + try { + Queue queue = QueueTools.linkedQueue(-3); + fail("bogus queue: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSize() { + Queue queue = this.buildQueue(); + String first = "first"; + String second = "second"; + String third = "third"; + + assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.enqueue(first); + queue.enqueue(second); + assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.enqueue(third); + assertEquals(3, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.dequeue(); + assertEquals(2, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + queue.dequeue(); + queue.dequeue(); + assertEquals(0, ((Integer) ObjectTools.execute(queue, "size")).intValue()); + } + + public void testBuildElements() { + Queue queue = this.buildQueue(); + String first = "first"; + String second = "second"; + String third = "third"; + queue.enqueue(first); + queue.enqueue(second); + queue.enqueue(third); + + Object[] elements = new Object[] { first, second, third }; + assertTrue(Arrays.equals(elements, ((Object[]) ObjectTools.execute(queue, "buildElements")))); + } + + public void testNodeCache_max() { + Queue queue = new LinkedQueue(2); + String first = "first"; + String second = "second"; + String third = "third"; + String fourth = "fourth"; + String fifth = "fifth"; + + Object factory = ObjectTools.get(queue, "nodeFactory"); + + this.verifyNodeCache(0, factory); + queue.enqueue(first); + this.verifyNodeCache(0, factory); + queue.enqueue(second); + queue.enqueue(third); + queue.enqueue(fourth); + queue.enqueue(fifth); + this.verifyNodeCache(0, factory); + assertNull(ObjectTools.get(factory, "cacheHead")); + + queue.dequeue(); + this.verifyNodeCache(1, factory); + queue.dequeue(); + this.verifyNodeCache(2, factory); + queue.dequeue(); + this.verifyNodeCache(2, factory); + queue.dequeue(); + this.verifyNodeCache(2, factory); + queue.dequeue(); + this.verifyNodeCache(2, factory); + queue.enqueue(first); + this.verifyNodeCache(1, factory); + queue.enqueue(second); + this.verifyNodeCache(0, factory); + queue.enqueue(third); + this.verifyNodeCache(0, factory); + } + + public void testNodeCache_unlimited() { + Queue queue = new LinkedQueue(-1); + String first = "first"; + String second = "second"; + String third = "third"; + String fourth = "fourth"; + String fifth = "fifth"; + + Object factory = ObjectTools.get(queue, "nodeFactory"); + + this.verifyNodeCache(0, factory); + queue.enqueue(first); + this.verifyNodeCache(0, factory); + queue.enqueue(second); + queue.enqueue(third); + queue.enqueue(fourth); + queue.enqueue(fifth); + this.verifyNodeCache(0, factory); + assertNull(ObjectTools.get(factory, "cacheHead")); + + queue.dequeue(); + this.verifyNodeCache(1, factory); + queue.dequeue(); + this.verifyNodeCache(2, factory); + queue.dequeue(); + this.verifyNodeCache(3, factory); + queue.dequeue(); + this.verifyNodeCache(4, factory); + queue.dequeue(); + this.verifyNodeCache(5, factory); + queue.enqueue(first); + this.verifyNodeCache(4, factory); + queue.enqueue(second); + this.verifyNodeCache(3, factory); + queue.enqueue(third); + this.verifyNodeCache(2, factory); + queue.enqueue(fourth); + this.verifyNodeCache(1, factory); + queue.enqueue(fifth); + this.verifyNodeCache(0, factory); + } + + public void verifyNodeCache(int size, Object factory) { + assertEquals(size, ((Integer) ObjectTools.get(factory, "cacheSize")).intValue()); + int nodeCount = 0; + for (Object node = ObjectTools.get(factory, "cacheHead"); node != null; node = ObjectTools.get(node, "next")) { + nodeCount++; + } + assertEquals(size, nodeCount); + } + + public void testNodeToString() { + Queue queue = QueueTools.linkedQueue(); + String first = "first"; + String second = "second"; + String third = "third"; + queue.enqueue(first); + queue.enqueue(second); + queue.enqueue(third); + + Object head = ObjectTools.get(queue, "head"); + assertTrue(head.toString().startsWith("LinkedQueue.Node")); + assertTrue(head.toString().endsWith("(first)")); + } + + public void testSimpleNodeFactoryToString() { + Queue queue = QueueTools.linkedQueue(); + Object factory = ObjectTools.get(queue, "nodeFactory"); + assertEquals("LinkedQueue.SimpleNodeFactory", factory.toString()); + } + + public void testCachingNodeFactoryToString() { + Queue queue = QueueTools.linkedQueue(20); + Object factory = ObjectTools.get(queue, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedQueue.CachingNodeFactory")); + assertTrue(factory.toString().endsWith("(0)")); + } + + public void testClone_caching() throws Exception { + LinkedQueue original = QueueTools.linkedQueue(20); + original.enqueue("first"); + + LinkedQueue clone = original.clone(); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.dequeue(), clone.dequeue()); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("second"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + + Object factory = ObjectTools.get(original, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedQueue.CachingNodeFactory")); + } + + public void testSerialization_caching() throws Exception { + Queue original = QueueTools.linkedQueue(20); + original.enqueue("first"); + + Queue clone = TestTools.serialize(original); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.dequeue(), clone.dequeue()); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("second"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + + Object factory = ObjectTools.get(original, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedQueue.CachingNodeFactory")); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ListQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ListQueueTests.java new file mode 100644 index 0000000000..563e6f4a8e --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/ListQueueTests.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.internal.queue.ListQueue; +import org.eclipse.jpt.common.utility.queue.Queue; + +public class ListQueueTests + extends QueueTests +{ + public ListQueueTests(String name) { + super(name); + } + + @Override + Queue buildQueue() { + return new ListQueue(new ArrayList()); + } + + @Override + public void testClone() { + // unsupported + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/PriorityQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/PriorityQueueTests.java new file mode 100644 index 0000000000..4f84c69345 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/PriorityQueueTests.java @@ -0,0 +1,444 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import java.util.Comparator; +import java.util.NoSuchElementException; +import java.util.Random; +import org.eclipse.jpt.common.utility.internal.ArrayTools; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.StringTools; +import org.eclipse.jpt.common.utility.internal.queue.PriorityQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class PriorityQueueTests + extends TestCase +{ + public PriorityQueueTests(String name) { + super(name); + } + + private Queue buildQueue() { + return QueueTools.priorityQueue(); + } + + public void testIsEmpty() { + Queue 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 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 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 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 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() { + Queue queue = this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + @SuppressWarnings("unchecked") + Queue clone = (Queue) ObjectTools.execute(queue, "clone"); + this.verifyClone(queue, clone); + } + + public void testSerialization() throws Exception { + Queue queue = this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + protected void verifyClone(Queue original, Queue 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()); + } + + public void testToString() throws Exception { + Queue queue = this.buildQueue(); + assertEquals("[]", queue.toString()); + queue.enqueue("first"); + assertEquals("[first]", queue.toString()); + queue.enqueue("second"); + assertEquals("[first, second]", queue.toString()); + queue.enqueue("third"); + assertEquals("[first, second, third]", queue.toString()); + } + + public void testArrayCapacityExceeded() { + Queue queue = QueueTools.priorityQueue(); + assertTrue(queue.isEmpty()); + queue.enqueue(Integer.valueOf(1)); + assertFalse(queue.isEmpty()); + queue.enqueue(Integer.valueOf(2)); + assertFalse(queue.isEmpty()); + queue.enqueue(Integer.valueOf(3)); + queue.enqueue(Integer.valueOf(10)); + queue.enqueue(Integer.valueOf(11)); + queue.enqueue(Integer.valueOf(12)); + queue.enqueue(Integer.valueOf(4)); + queue.enqueue(Integer.valueOf(4)); + queue.enqueue(Integer.valueOf(7)); + queue.enqueue(Integer.valueOf(8)); + queue.enqueue(Integer.valueOf(9)); + queue.enqueue(Integer.valueOf(5)); + queue.enqueue(Integer.valueOf(6)); + queue.enqueue(Integer.valueOf(9)); + + assertEquals(Integer.valueOf(1), queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals(Integer.valueOf(2), queue.dequeue()); + assertFalse(queue.isEmpty()); + assertEquals(Integer.valueOf(3), queue.dequeue()); + assertEquals(Integer.valueOf(4), queue.dequeue()); + assertEquals(Integer.valueOf(4), queue.dequeue()); + assertEquals(Integer.valueOf(5), queue.dequeue()); + assertEquals(Integer.valueOf(6), queue.dequeue()); + assertEquals(Integer.valueOf(7), queue.dequeue()); + assertEquals(Integer.valueOf(8), queue.dequeue()); + assertEquals(Integer.valueOf(9), queue.dequeue()); + assertEquals(Integer.valueOf(9), queue.dequeue()); + assertEquals(Integer.valueOf(10), queue.dequeue()); + assertEquals(Integer.valueOf(11), queue.dequeue()); + assertEquals(Integer.valueOf(12), queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testMultipleSizes() throws Exception { + int maxSize = 50; + Random random = new Random(); + for (int size = 1; size <= maxSize; size++) { + Queue queue = QueueTools.priorityQueue(size); + for (int i = size; i-- > 0; ) { + queue.enqueue(Integer.valueOf(random.nextInt())); + } + Integer current = queue.dequeue(); + int i = 1; + do { + if ( ! queue.isEmpty()) { + Integer next = queue.dequeue(); + i++; + assertTrue(current.intValue() <= next.intValue()); + current = next; + } + } while ( ! queue.isEmpty()); + assertEquals(size, i); + } + } + + // instance variable access appears to be slightly faster(!) +// public void testLocalVariablePerformance() throws Exception { +// int minSize = 5000000; +// int executionCount = 10; +// Random random = new Random(); +// for (int x = 0; x < executionCount; x++) { +// int size = minSize + random.nextInt(minSize / 2); +// Integer[] values = new Integer[size]; +// for (int i = size; i-- > 0; ) { +// values[i] = Integer.valueOf(random.nextInt()); +// } +// PriorityQueue queue; +// queue = QueueTools.priorityQueue(size); +// for (Integer value : values) { +// queue.enqueue(value); +// } +// long start = System.currentTimeMillis(); +// while ( ! queue.isEmpty()) { +// queue.dequeue(); +// } +// long execTime = System.currentTimeMillis() - start; +// System.out.println("execution time (local var): " + (execTime / 1000.0)); +// assertTrue(queue.isEmpty()); +// +// queue = QueueTools.priorityQueue(size); +// for (Integer value : values) { +// queue.enqueue(value); +// } +// start = System.currentTimeMillis(); +// while ( ! queue.isEmpty()) { +// queue.dequeueIV(); +// } +// execTime = System.currentTimeMillis() - start; +// System.out.println("execution time (instance var): " + (execTime / 1000.0)); +// System.out.println(); +// assertTrue(queue.isEmpty()); +// } +// } +// + public void testSomethingBig() throws Exception { + int size = 500000; + Queue queue = QueueTools.priorityQueue(size); + Random random = new Random(); + for (int i = size; i-- > 0; ) { + queue.enqueue(Integer.valueOf(random.nextInt())); + } + Integer current = queue.dequeue(); + int i = 1; + do { + if ( ! queue.isEmpty()) { + Integer next = queue.dequeue(); + i++; + assertTrue(current.intValue() <= next.intValue()); + current = next; + } + } while ( ! queue.isEmpty()); + assertEquals(size, i); + } + + public void testEnsureCapacity() throws Exception { + PriorityQueue queue = QueueTools.priorityQueue(); + queue.enqueue("b"); + queue.enqueue("c"); + queue.enqueue("a"); + assertEquals(11, ((Object[]) ObjectTools.get(queue, "elements")).length); + queue.ensureCapacity(420); + assertEquals(421, ((Object[]) ObjectTools.get(queue, "elements")).length); + assertEquals("a", queue.dequeue()); + assertEquals("b", queue.dequeue()); + assertEquals("c", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testTrimToSize() throws Exception { + PriorityQueue queue = QueueTools.priorityQueue(); + queue.enqueue("b"); + queue.enqueue("c"); + queue.enqueue("a"); + assertEquals(11, ((Object[]) ObjectTools.get(queue, "elements")).length); + queue.trimToSize(); + assertEquals(4, ((Object[]) ObjectTools.get(queue, "elements")).length); + assertEquals("a", queue.dequeue()); + assertEquals("b", queue.dequeue()); + assertEquals("c", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testTrimToSize_nop() throws Exception { + PriorityQueue queue = QueueTools.priorityQueue(3); + queue.enqueue("b"); + queue.enqueue("c"); + queue.enqueue("a"); + assertEquals(4, ((Object[]) ObjectTools.get(queue, "elements")).length); + queue.trimToSize(); + assertEquals(4, ((Object[]) ObjectTools.get(queue, "elements")).length); + assertEquals("a", queue.dequeue()); + assertEquals("b", queue.dequeue()); + assertEquals("c", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testConstructor_nullComparator() throws Exception { + boolean exCaught = false; + try { + Queue queue = QueueTools.priorityQueue((Comparator) null, 3); + fail("bogus queue: " + queue); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructor_negativeCapacity() throws Exception { + boolean exCaught = false; + try { + Queue queue = QueueTools.priorityQueue(-7); + fail("bogus queue: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSerialization_fullArray() throws Exception { + Queue queue = QueueTools.priorityQueue(3); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + public void testSerialization_empty() throws Exception { + Queue original = QueueTools.priorityQueue(); + Queue clone = TestTools.serialize(original); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.enqueue("foo"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testConstructorComparatorObjectArrayInt() throws Exception { + int maxSize = 100; + Integer[] array = new Integer[maxSize + 1]; + Random random = new Random(); + for (int size = 1; size <= maxSize; size++) { + ArrayTools.fill(array, null); + for (int i = size + 1; i-- > 1; ) { + array[i] = Integer.valueOf(random.nextInt()); + } + Queue queue = QueueTools.priorityQueue(array, size); + Integer current = queue.dequeue(); + int i = 1; + do { + if ( ! queue.isEmpty()) { + Integer next = queue.dequeue(); + i++; + assertTrue(current.intValue() <= next.intValue()); + current = next; + } + } while ( ! queue.isEmpty()); + assertEquals(size, i); + } + } + + public void testConstructorComparatorObjectArrayInt_nullComparator() throws Exception { + String[] array = new String[5]; + boolean exCaught = false; + try { + Queue queue = QueueTools.priorityQueue(null, array, 3); + fail("bogus queue: " + queue); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorComparatorObjectArrayInt_nullArray() throws Exception { + boolean exCaught = false; + try { + Queue queue = QueueTools.priorityQueue((String[]) null, 3); + fail("bogus queue: " + queue); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorComparatorObjectArrayInt_emptyArray() throws Exception { + boolean exCaught = false; + try { + Queue queue = QueueTools.priorityQueue(StringTools.EMPTY_STRING_ARRAY, 3); + fail("bogus queue: " + queue); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorComparatorObjectArrayInt_negativeSize() throws Exception { + String[] array = new String[5]; + boolean exCaught = false; + try { + Queue queue = QueueTools.priorityQueue(array, -7); + fail("bogus queue: " + queue); + } 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/queue/QueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueTests.java new file mode 100644 index 0000000000..e1503627a7 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueTests.java @@ -0,0 +1,160 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.queue; + +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +// subclass MultiThreadedTestCase for subclasses of this class +@SuppressWarnings("nls") +public abstract class QueueTests + extends MultiThreadedTestCase +{ + public QueueTests(String name) { + super(name); + } + + abstract Queue buildQueue(); + + public void testIsEmpty() { + Queue 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 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 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 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 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() { + Queue queue = this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + @SuppressWarnings("unchecked") + Queue clone = (Queue) ObjectTools.execute(queue, "clone"); + this.verifyClone(queue, clone); + } + + public void testSerialization() throws Exception { + Queue queue = this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + protected void verifyClone(Queue original, Queue 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()); + } + + public void testToString() throws Exception { + Queue queue = this.buildQueue(); + assertEquals("[]", queue.toString()); + queue.enqueue("first"); + assertEquals("[first]", queue.toString()); + queue.enqueue("second"); + assertEquals("[first, second]", queue.toString()); + queue.enqueue("third"); + assertEquals("[first, second, third]", queue.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueToolsTests.java new file mode 100644 index 0000000000..1796eb065d --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/QueueToolsTests.java @@ -0,0 +1,506 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.jpt.common.utility.internal.ClassTools; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.StringTools; +import org.eclipse.jpt.common.utility.internal.comparator.ComparatorTools; +import org.eclipse.jpt.common.utility.internal.queue.ArrayQueue; +import org.eclipse.jpt.common.utility.internal.queue.LinkedQueue; +import org.eclipse.jpt.common.utility.internal.queue.ListQueue; +import org.eclipse.jpt.common.utility.internal.queue.PriorityQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.queue.SynchronizedQueue; +import org.eclipse.jpt.common.utility.internal.stack.ArrayStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.transformer.Transformer; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class QueueToolsTests + extends TestCase +{ + public QueueToolsTests(String name) { + super(name); + } + + // ********** enqueue all ********** + + public void testEnqueueAllIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(); + assertTrue(QueueTools.enqueueAll(queue, iterable)); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testEnqueueAllIterable_empty() { + ArrayList iterable = new ArrayList(); + Queue queue = QueueTools.arrayQueue(); + assertFalse(QueueTools.enqueueAll(queue, iterable)); + assertTrue(queue.isEmpty()); + } + + public void testEnqueueAllIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(); + assertTrue(QueueTools.enqueueAll(queue, iterable.iterator())); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testEnqueueAllArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(); + assertTrue(QueueTools.enqueueAll(queue, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testEnqueueAllArray_empty() { + ArrayList iterable = new ArrayList(); + Queue queue = QueueTools.arrayQueue(); + assertFalse(QueueTools.enqueueAll(queue, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertTrue(queue.isEmpty()); + } + + + // ********** drain ********** + + public void testDrain() { + ArrayQueue queue = QueueTools.arrayQueue(); + queue.enqueue("one"); + queue.enqueue("two"); + queue.enqueue("three"); + ArrayList list = QueueTools.drain(queue); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainToCollection() { + ArrayQueue queue = QueueTools.arrayQueue(); + queue.enqueue("one"); + queue.enqueue("two"); + queue.enqueue("three"); + ArrayList list = new ArrayList(); + assertTrue(QueueTools.drainTo(queue, list)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainToCollection_empty() { + ArrayQueue queue = QueueTools.arrayQueue(); + ArrayList list = new ArrayList(); + assertFalse(QueueTools.drainTo(queue, list)); + assertTrue(list.isEmpty()); + } + + public void testDrainToListIndex() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Queue queue = QueueTools.arrayQueue(); + queue.enqueue("aaa"); + queue.enqueue("bbb"); + queue.enqueue("ccc"); + assertTrue(QueueTools.drainTo(queue, list, 2)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("aaa", list.get(2)); + assertEquals("bbb", list.get(3)); + assertEquals("ccc", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testDrainToListIndex_end() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Queue queue = QueueTools.arrayQueue(); + queue.enqueue("aaa"); + queue.enqueue("bbb"); + queue.enqueue("ccc"); + assertTrue(QueueTools.drainTo(queue, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + assertEquals("aaa", list.get(3)); + assertEquals("bbb", list.get(4)); + assertEquals("ccc", list.get(5)); + } + + public void testDrainToListIndex_empty() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Queue queue = QueueTools.arrayQueue(); + assertFalse(QueueTools.drainTo(queue, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainToStack() { + ArrayQueue queue = QueueTools.arrayQueue(); + queue.enqueue("one"); + queue.enqueue("two"); + queue.enqueue("three"); + ArrayStack stack = StackTools.arrayStack(); + assertTrue(QueueTools.drainTo(queue, stack)); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testDrainToStack_empty() { + ArrayQueue queue = QueueTools.arrayQueue(); + ArrayStack stack = StackTools.arrayStack(); + assertFalse(QueueTools.drainTo(queue, stack)); + assertTrue(stack.isEmpty()); + } + + public void testDrainToQueue() { + ArrayQueue queue1 = QueueTools.arrayQueue(); + queue1.enqueue("one"); + queue1.enqueue("two"); + queue1.enqueue("three"); + ArrayQueue queue2 = QueueTools.arrayQueue(); + assertTrue(QueueTools.drainTo(queue1, queue2)); + assertEquals("one", queue2.dequeue()); + assertEquals("two", queue2.dequeue()); + assertEquals("three", queue2.dequeue()); + } + + public void testDrainToQueue_empty() { + ArrayQueue queue1 = QueueTools.arrayQueue(); + ArrayQueue queue2 = QueueTools.arrayQueue(); + assertFalse(QueueTools.drainTo(queue1, queue2)); + assertTrue(queue2.isEmpty()); + } + + public void testDrainToMapTransformer() { + ArrayQueue queue = QueueTools.arrayQueue(); + queue.enqueue("zero"); + queue.enqueue("one"); + queue.enqueue("two"); + Mapmap = new HashMap(); + assertTrue(QueueTools.drainTo(queue, map, FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testDrainToMapTransformer_empty() { + ArrayQueue queue = QueueTools.arrayQueue(); + Mapmap = new HashMap(); + assertFalse(QueueTools.drainTo(queue, map, FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testDrainToMapTransformerTransformer() { + ArrayQueue queue = QueueTools.arrayQueue(); + queue.enqueue("zero"); + queue.enqueue("one"); + queue.enqueue("two"); + Mapmap = new HashMap(); + assertTrue(QueueTools.drainTo(queue, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testDrainToMapTransformerTransformer_empty() { + ArrayQueue queue = QueueTools.arrayQueue(); + Mapmap = new HashMap(); + assertFalse(QueueTools.drainTo(queue, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertTrue(map.isEmpty()); + } + + public static final Transformer FIRST_LETTER_TRANSFORMER = new FirstLetterTransformer(); + + /* CU private */ static class FirstLetterTransformer + implements Transformer + { + public String transform(String string) { + return string.substring(0, 1); + } + @Override + public String toString() { + return this.getClass().getSimpleName(); + } + } + + public static final Transformer EMPHASIZER = new StringTools.CharDelimiter('*'); + + + // ********** array queue ********** + + public void testArrayQueue() { + ArrayQueue queue = QueueTools.arrayQueue(); + assertTrue(queue.isEmpty()); + } + + public void testArrayQueueInt() { + ArrayQueue queue = QueueTools.arrayQueue(20); + assertTrue(queue.isEmpty()); + assertEquals(20, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testArrayQueueIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(iterable); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testArrayQueueIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(iterable, 5); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testArrayQueueIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(iterable.iterator()); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testArrayQueueIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(iterable.iterator(), 5); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testArrayQueueArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.arrayQueue(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + // ********** linked queue ********** + + public void testLinkedQueue() { + LinkedQueue queue = QueueTools.linkedQueue(); + assertTrue(queue.isEmpty()); + } + + public void testLinkedQueueInt() { + LinkedQueue queue = QueueTools.linkedQueue(20); + assertTrue(queue.isEmpty()); + } + + public void testLinkedQueueIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.linkedQueue(iterable); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testLinkedQueueIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.linkedQueue(iterable, 5); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testLinkedQueueIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.linkedQueue(iterable.iterator()); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testLinkedQueueIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.linkedQueue(iterable.iterator(), 5); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testLinkedQueueArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.linkedQueue(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + // ********** fixed-capacity array queue ********** + + public void testFixedCapacityArrayQueueCollection() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Queue queue = QueueTools.fixedCapacityArrayQueue(iterable); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + // ********** misc ********** + + public void testPriorityQueueComparator() { + PriorityQueue queue = QueueTools.priorityQueue(ComparatorTools.reverseComparator()); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(second, queue.dequeue()); + assertEquals(first, queue.dequeue()); + } + + public void testPriorityQueueObjectArray() { + String first = "first"; + String second = "second"; + String third = "third"; + String[] array = new String[] { null, second, first, third }; + PriorityQueue queue = QueueTools.priorityQueue(array); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.dequeue()); + assertEquals(third, queue.dequeue()); + } + + public void testPriorityQueueComparatorObjectArray() { + String first = "first"; + String second = "second"; + String third = "third"; + String[] array = new String[] { null, first, second, third }; + PriorityQueue queue = QueueTools.priorityQueue(ComparatorTools.reverseComparator(), array); + assertEquals(third, queue.dequeue()); + assertEquals(second, queue.dequeue()); + assertEquals(first, queue.dequeue()); + } + + public void testSynchronizedQueueObject() { + Object lock = new Object(); + SynchronizedQueue queue = QueueTools.synchronizedQueue(lock); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.dequeue()); + assertEquals(lock, queue.getMutex()); + } + + public void testSynchronizedQueueQueueObject() { + Object lock = new Object(); + Queue innerQueue = QueueTools.arrayQueue(); + String first = "first"; + String second = "second"; + innerQueue.enqueue(first); + innerQueue.enqueue(second); + + SynchronizedQueue queue = QueueTools.synchronizedQueue(innerQueue, lock); + assertEquals(first, queue.dequeue()); + assertEquals(second, queue.dequeue()); + assertEquals(lock, queue.getMutex()); + } + + public void testAdaptList() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + ListQueue queue = QueueTools.adapt(list); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + } + + public void testEmptyQueue() { + Queue queue = QueueTools.emptyQueue(); + assertTrue(queue.isEmpty()); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ClassTools.newInstance(QueueTools.class); + fail("bogus: " + at); + } 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/queue/StackQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/StackQueueTests.java new file mode 100644 index 0000000000..b00d3a21a2 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/StackQueueTests.java @@ -0,0 +1,163 @@ +/******************************************************************************* + * Copyright (c) 2015 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.queue; + +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +// subclass MultiThreadedTestCase for subclasses of this class +@SuppressWarnings("nls") +public class StackQueueTests + extends TestCase +{ + public StackQueueTests(String name) { + super(name); + } + + private Queue buildQueue() { + return QueueTools.stackQueue(); + } + + public void testConstructor_NPE() { + boolean exCaught = false; + try { + Queue queue = QueueTools.adapt((Stack) null); + fail("bogus queue: " + queue); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIsEmpty() { + Queue 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 queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(second, queue.dequeue()); + assertEquals(first, queue.dequeue()); + } + + public void testEnqueueAndPeek() { + Queue queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(second, queue.peek()); + assertEquals(second, queue.peek()); + assertEquals(second, queue.dequeue()); + assertEquals(first, queue.peek()); + assertEquals(first, queue.peek()); + assertEquals(first, queue.dequeue()); + } + + public void testEmptyQueueExceptionPeek() { + Queue queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(second, queue.peek()); + assertEquals(second, queue.dequeue()); + assertEquals(first, queue.peek()); + assertEquals(first, queue.dequeue()); + + boolean exCaught = false; + try { + String string = queue.peek(); + fail("bogus element: " + string); + } catch (EmptyStackException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testEmptyQueueExceptionDequeue() { + Queue queue = this.buildQueue(); + String first = "first"; + String second = "second"; + + queue.enqueue(first); + queue.enqueue(second); + assertEquals(second, queue.peek()); + assertEquals(second, queue.dequeue()); + assertEquals(first, queue.peek()); + assertEquals(first, queue.dequeue()); + + boolean exCaught = false; + try { + String string = queue.dequeue(); + fail("bogus element: " + string); + } catch (EmptyStackException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSerialization() throws Exception { + Queue queue = this.buildQueue(); + queue.enqueue("first"); + queue.enqueue("second"); + queue.enqueue("third"); + + this.verifyClone(queue, TestTools.serialize(queue)); + } + + protected void verifyClone(Queue original, Queue 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()); + } + + public void testToString() throws Exception { + Queue queue = this.buildQueue(); + assertEquals("[]", queue.toString()); + queue.enqueue("first"); + assertEquals("[first]", queue.toString()); + queue.enqueue("second"); + assertEquals("[second, first]", queue.toString()); + queue.enqueue("third"); + assertEquals("[third, second, first]", queue.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/SynchronizedQueueTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/SynchronizedQueueTests.java new file mode 100644 index 0000000000..a058941092 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/queue/SynchronizedQueueTests.java @@ -0,0 +1,793 @@ +/******************************************************************************* + * Copyright (c) 2009, 2015 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.queue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.NoSuchElementException; +import org.eclipse.jpt.common.utility.internal.queue.LinkedQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.queue.SynchronizedQueue; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.deque.DequeToolsTests; + +@SuppressWarnings("nls") +public class SynchronizedQueueTests + extends QueueTests +{ + private volatile SynchronizedQueue sq; + volatile boolean timeoutOccurred; + volatile long startTime; + volatile long endTime; + volatile Object dequeuedObject; + + boolean commandExecuted; + + static final String ITEM_1 = new String(); + static final String ITEM_2 = new String(); + + public SynchronizedQueueTests(String name) { + super(name); + } + + @Override + Queue buildQueue() { + return QueueTools.synchronizedQueue(); + } + + @Override + public void testClone() { + // synchronized queue is not cloneable + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.sq = QueueTools.synchronizedQueue(); + this.timeoutOccurred = false; + this.startTime = 0; + this.endTime = 0; + this.dequeuedObject = null; + } + + // ********** constructor ********** + + public void testConstructorQueue() throws Exception { + Queue innerQueue = QueueTools.arrayQueue(); + SynchronizedQueue stack = QueueTools.synchronizedQueue(innerQueue); + assertNotNull(stack); + assertSame(stack, stack.getMutex()); + } + + public void testConstructorQueue_NPE() throws Exception { + boolean exCaught = false; + try { + Queue stack = QueueTools.synchronizedQueue(null); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorQueueObject() throws Exception { + String mutex = "mutex"; + Queue innerQueue = QueueTools.arrayQueue(); + SynchronizedQueue stack = QueueTools.synchronizedQueue(innerQueue, mutex); + assertNotNull(stack); + assertSame(mutex, stack.getMutex()); + } + + public void testConstructorQueueObject_NPE1() throws Exception { + String mutex = "mutex"; + boolean exCaught = false; + try { + Queue stack = QueueTools.synchronizedQueue(null, mutex); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorQueueObject_NPE2() throws Exception { + Queue innerQueue = QueueTools.arrayQueue(); + boolean exCaught = false; + try { + Queue stack = QueueTools.synchronizedQueue(innerQueue, null); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + // ********** concurrent access ********** + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentDequeue() throws Exception { + this.verifyConcurrentDequeue(new SlowLinkedQueue(), "first"); + this.verifyConcurrentDequeue(new SlowSynchronizedQueue(), "second"); + } + + private void verifyConcurrentDequeue(SlowQueue slowQueue, String expected) throws Exception { + slowQueue.enqueue("first"); + slowQueue.enqueue("second"); + + Thread thread = this.buildThread(this.buildRunnableDequeue(slowQueue)); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(expected, slowQueue.dequeue()); + thread.join(); + assertTrue(slowQueue.isEmpty()); + } + + private Runnable buildRunnableDequeue(final SlowQueue slowQueue) { + return new Runnable() { + public void run() { + slowQueue.slowDequeue(); + } + }; + } + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentEnqueue() throws Exception { + this.verifyConcurrentEnqueue(new SlowLinkedQueue(), "second", "first"); + this.verifyConcurrentEnqueue(new SlowSynchronizedQueue(), "first", "second"); + } + + private void verifyConcurrentEnqueue(SlowQueue slowQueue, String first, String second) throws Exception { + Thread thread = this.buildThread(this.buildRunnableEnqueue(slowQueue, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + slowQueue.enqueue("second"); + thread.join(); + assertEquals(first, slowQueue.dequeue()); + assertEquals(second, slowQueue.dequeue()); + assertTrue(slowQueue.isEmpty()); + } + + private Runnable buildRunnableEnqueue(final SlowQueue slowQueue, final String element) { + return new Runnable() { + public void run() { + slowQueue.slowEnqueue(element); + } + }; + } + + /** + * test first with an unsynchronized queue, + * then with a synchronized queue + */ + public void testConcurrentIsEmpty() throws Exception { + this.verifyConcurrentIsEmpty(new SlowLinkedQueue(), true); + this.verifyConcurrentIsEmpty(new SlowSynchronizedQueue(), false); + } + + private void verifyConcurrentIsEmpty(SlowQueue slowQueue, boolean empty) throws Exception { + Thread thread = this.buildThread(this.buildRunnableEnqueue(slowQueue, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(empty, slowQueue.isEmpty()); + thread.join(); + assertEquals("first", slowQueue.dequeue()); + assertTrue(slowQueue.isEmpty()); + } + + + private interface SlowQueue extends Queue { + Object slowDequeue(); + void slowEnqueue(E element); + } + + private class SlowLinkedQueue extends LinkedQueue implements SlowQueue { + private static final long serialVersionUID = 1L; + SlowLinkedQueue() { + super(); + } + public Object slowDequeue() { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.dequeue(); + } + public void slowEnqueue(E element) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.enqueue(element); + } + } + + private class SlowSynchronizedQueue extends SynchronizedQueue implements SlowQueue { + private static final long serialVersionUID = 1L; + SlowSynchronizedQueue() { + super(QueueTools.linkedQueue()); + } + public Object slowDequeue() { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.dequeue(); + } + } + public void slowEnqueue(E element) { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.enqueue(element); + } + } + } + + + // ********** waits ********** + + public void testWaitUntilEmpty() throws Exception { + this.verifyWaitUntilEmpty(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeued by t1... + 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 testWaitUntilEmpty2() throws Exception { + this.verifyWaitUntilEmpty(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been dequeued by t1... + 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 testWaitUntilEmptyTimeout() throws Exception { + this.verifyWaitUntilEmpty(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the queue was dequeued... + 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() < THREE_TICKS); + } + + private void verifyWaitUntilEmpty(long timeout) throws Exception { + this.sq.enqueue(ITEM_1); + Runnable r1 = this.buildRunnable(this.buildDequeueCommand(), this.sq, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitUntilEmptyCommand(timeout), this.sq, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitUntilEmptyCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedQueue synchronizedQueue) throws InterruptedException { + SynchronizedQueueTests.this.startTime = System.currentTimeMillis(); + SynchronizedQueueTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedQueue); + SynchronizedQueueTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedQueue synchronizedQueue) throws InterruptedException { + if (timeout < 0) { + synchronizedQueue.waitUntilEmpty(); + return false; + } + return ! synchronizedQueue.waitUntilEmpty(timeout); + } + }; + } + + public void testWaitUntilNotEmpty() throws Exception { + this.verifyWaitUntilNotEmpty(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been enqueued by t1... + assertFalse(this.sq.isEmpty()); + assertSame(ITEM_1, this.sq.peek()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilNotEmpty2() throws Exception { + this.verifyWaitUntilNotEmpty(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been enqueued by t1... + assertFalse(this.sq.isEmpty()); + assertSame(ITEM_1, this.sq.peek()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilNotEmptyTimeout() throws Exception { + this.verifyWaitUntilNotEmpty(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and an item should have been enqueued by t1... + assertFalse(this.sq.isEmpty()); + assertSame(ITEM_1, this.sq.peek()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitUntilNotEmpty(long timeout) throws Exception { + Runnable r1 = this.buildRunnable(this.buildEnqueueCommand(), this.sq, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitUntilNotEmptyCommand(timeout), this.sq, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitUntilNotEmptyCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedQueue synchronizedQueue) throws InterruptedException { + SynchronizedQueueTests.this.startTime = System.currentTimeMillis(); + SynchronizedQueueTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedQueue); + SynchronizedQueueTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedQueue synchronizedQueue) throws InterruptedException { + if (timeout < 0) { + synchronizedQueue.waitUntilNotEmpty(); + return false; + } + return ! synchronizedQueue.waitUntilNotEmpty(timeout); + } + }; + } + + public void testWaitToDequeue() throws Exception { + this.verifyWaitToDequeue(-1); + // 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 testWaitToDequeue2() 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(); + } + + private Command buildWaitToDequeueCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedQueue synchronizedQueue) throws InterruptedException { + SynchronizedQueueTests.this.startTime = System.currentTimeMillis(); + this.waitToDequeue(synchronizedQueue); + SynchronizedQueueTests.this.endTime = System.currentTimeMillis(); + } + private void waitToDequeue(SynchronizedQueue synchronizedQueue) throws InterruptedException { + if (timeout < 0) { + SynchronizedQueueTests.this.dequeuedObject = synchronizedQueue.waitToDequeue(); + return; + } + try { + SynchronizedQueueTests.this.dequeuedObject = synchronizedQueue.waitToDequeue(timeout); + } catch (NoSuchElementException ex) { + SynchronizedQueueTests.this.timeoutOccurred = true; + } + } + }; + } + + public void testWaitToEnqueue() throws Exception { + this.verifyWaitToEnqueue(-1); + // 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 testWaitToEnqueue2() 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 buildWaitToEnqueueCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedQueue synchronizedQueue) throws InterruptedException { + SynchronizedQueueTests.this.startTime = System.currentTimeMillis(); + SynchronizedQueueTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedQueue); + SynchronizedQueueTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedQueue synchronizedQueue) throws InterruptedException { + if (timeout < 0) { + synchronizedQueue.waitToEnqueue(ITEM_2); + return false; + } + return ! synchronizedQueue.waitToEnqueue(ITEM_2, timeout); + } + }; + } + + private Command buildEnqueueCommand() { + return new Command() { + public void execute(SynchronizedQueue synchronizedQueue) { + synchronizedQueue.enqueue(ITEM_1); + } + }; + } + + private Command buildDequeueCommand() { + return new Command() { + public void execute(SynchronizedQueue synchronizedQueue) { + SynchronizedQueueTests.this.dequeuedObject = synchronizedQueue.dequeue(); + } + }; + } + + private Runnable buildRunnable(final Command command, final SynchronizedQueue 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 synchronizedQueue) throws InterruptedException; + } + + + // ********** execute ********** + + public void testExecute() throws Exception { + org.eclipse.jpt.common.utility.command.Command command = new org.eclipse.jpt.common.utility.command.Command() { + public void execute() { + SynchronizedQueueTests.this.commandExecuted = true; + } + }; + this.commandExecuted = false; + this.sq.execute(command); + assertTrue(this.commandExecuted); + } + + + // ********** additional protocol ********** + + public void testEnqueueAllIterable() throws Exception { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + this.sq.enqueueAll(list); + assertEquals("one", this.sq.dequeue()); + assertEquals("two", this.sq.dequeue()); + assertEquals("three", this.sq.dequeue()); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllIterable_empty() throws Exception { + ArrayList list = new ArrayList(); + this.sq.enqueueAll(list); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllObjectArray() throws Exception { + this.sq.enqueueAll(new String[] { "one", "two", "three" }); + assertEquals("one", this.sq.dequeue()); + assertEquals("two", this.sq.dequeue()); + assertEquals("three", this.sq.dequeue()); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllObjectArray_empty() throws Exception { + this.sq.enqueueAll(new String[0]); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllStack() throws Exception { + Stack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + this.sq.enqueueAll(stack); + assertEquals("three", this.sq.dequeue()); + assertEquals("two", this.sq.dequeue()); + assertEquals("one", this.sq.dequeue()); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllStack_empty() throws Exception { + Stack stack = StackTools.arrayStack(); + this.sq.enqueueAll(stack); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllQueue() throws Exception { + Queue queue = QueueTools.arrayQueue(); + queue.enqueue("one"); + queue.enqueue("two"); + queue.enqueue("three"); + this.sq.enqueueAll(queue); + assertEquals("one", this.sq.dequeue()); + assertEquals("two", this.sq.dequeue()); + assertEquals("three", this.sq.dequeue()); + assertTrue(this.sq.isEmpty()); + } + + public void testEnqueueAllQueue_empty() throws Exception { + Queue queue = QueueTools.arrayQueue(); + this.sq.enqueueAll(queue); + assertTrue(this.sq.isEmpty()); + } + + public void testDrain() throws Exception { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("three"); + ArrayList list = this.sq.drain(); + assertTrue(this.sq.isEmpty()); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrain_empty() throws Exception { + ArrayList list = this.sq.drain(); + assertTrue(this.sq.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testDrainToCollection() throws Exception { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("three"); + ArrayList list = new ArrayList(); + assertTrue(this.sq.drainTo(list)); + assertTrue(this.sq.isEmpty()); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testDrainToCollection_empty() throws Exception { + ArrayList list = new ArrayList(); + assertFalse(this.sq.drainTo(list)); + assertTrue(this.sq.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testDrainToListInt() throws Exception { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.sq.drainTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("one", list.get(2)); + assertEquals("two", list.get(3)); + assertEquals("three", list.get(4)); + assertEquals("ccc", list.get(5)); + } + + public void testDrainToListInt_end() throws Exception { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.sq.drainTo(list, 3)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + assertEquals("one", list.get(3)); + assertEquals("two", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testDrainToListInt_empty() throws Exception { + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertFalse(this.sq.drainTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + } + + public void testDrainToStack() throws Exception { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("three"); + Stack stack = StackTools.arrayStack(); + assertTrue(this.sq.drainTo(stack)); + assertTrue(this.sq.isEmpty()); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + assertTrue(stack.isEmpty()); + } + + public void testDrainToStack_empty() throws Exception { + Stack stack = StackTools.arrayStack(); + assertFalse(this.sq.drainTo(stack)); + assertTrue(this.sq.isEmpty()); + assertTrue(stack.isEmpty()); + } + + public void testDrainToQueue() throws Exception { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("three"); + Queue queue = QueueTools.arrayQueue(); + assertTrue(this.sq.drainTo(queue)); + assertTrue(this.sq.isEmpty()); + assertEquals("one", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("three", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testDrainToQueue_empty() throws Exception { + Queue queue = QueueTools.arrayQueue(); + assertFalse(this.sq.drainTo(queue)); + assertTrue(this.sq.isEmpty()); + assertTrue(queue.isEmpty()); + } + + public void testDrainToMapTransformer() { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("zero"); + Mapmap = new HashMap(); + assertTrue(this.sq.drainTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testDrainToMapTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.sq.drainTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testDrainToMapTransformerTransformer() { + this.sq.enqueue("one"); + this.sq.enqueue("two"); + this.sq.enqueue("zero"); + Mapmap = new HashMap(); + assertTrue(this.sq.drainTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testDrainToMapTransformerTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.sq.drainTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertTrue(map.isEmpty()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ArrayStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ArrayStackTests.java new file mode 100644 index 0000000000..0334b14f57 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ArrayStackTests.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.stack; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.stack.ArrayStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class ArrayStackTests + extends StackTests +{ + public ArrayStackTests(String name) { + super(name); + } + + @Override + Stack buildStack() { + return new ArrayStack(); + } + + public void testCollectionConstructor() { + ArrayList c = new ArrayList(); + c.add("first"); + c.add("second"); + c.add("third"); + c.add("fourth"); + c.add("fifth"); + c.add("sixth"); + c.add("seventh"); + c.add("eighth"); + c.add("ninth"); + c.add("tenth"); // force some free space + Stack stack = StackTools.arrayStack(c); + + assertFalse(stack.isEmpty()); + assertEquals("tenth", stack.peek()); + stack.push("eleventh"); + stack.push("twelfth"); + + assertEquals("twelfth", stack.peek()); + assertEquals("twelfth", stack.pop()); + assertEquals("eleventh", stack.pop()); + assertEquals("tenth", stack.peek()); + assertEquals("tenth", stack.pop()); + assertEquals("ninth", stack.pop()); + assertFalse(stack.isEmpty()); + assertEquals("eighth", stack.peek()); + assertEquals("eighth", stack.pop()); + assertEquals("seventh", stack.pop()); + assertEquals("sixth", stack.pop()); + assertEquals("fifth", stack.pop()); + assertEquals("fourth", stack.pop()); + assertEquals("third", stack.pop()); + assertEquals("second", stack.pop()); + assertEquals("first", stack.pop()); + assertTrue(stack.isEmpty()); + } + + public void testSerialization_fullArray() throws Exception { + Stack stack = new ArrayStack(3); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + this.verifyClone(stack, TestTools.serialize(stack)); + } + + public void testEnsureCapacity() { + ArrayStack queue = StackTools.arrayStack(0); + queue.ensureCapacity(7); + assertEquals(7, ((Object[]) ObjectTools.get(queue, "elements")).length); + } + + public void testTrimToSize() throws Exception { + ArrayStack stack = new ArrayStack(5); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + Object[] elements = (Object[]) ObjectTools.get(stack, "elements"); + assertEquals(5, elements.length); + + stack.trimToSize(); + elements = (Object[]) ObjectTools.get(stack, "elements"); + assertEquals(3, elements.length); + } + + public void testTrimToSize_noChange() throws Exception { + ArrayStack stack = new ArrayStack(3); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + Object[] elements = (Object[]) ObjectTools.get(stack, "elements"); + assertEquals(3, elements.length); + + stack.trimToSize(); + elements = (Object[]) ObjectTools.get(stack, "elements"); + assertEquals(3, elements.length); + } + + public void testConstructorInt_IAE() throws Exception { + boolean exCaught = false; + try { + Stack stack = StackTools.arrayStack(-3); + fail("bogus stack: " + stack); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testToString_empty() throws Exception { + Stack stack = this.buildStack(); + assertEquals("[]", stack.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/DequeStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/DequeStackTests.java new file mode 100644 index 0000000000..2e9ed5afd7 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/DequeStackTests.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2015 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.stack; + +import org.eclipse.jpt.common.utility.internal.deque.DequeTools; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +public class DequeStackTests + extends StackTests +{ + public DequeStackTests(String name) { + super(name); + } + + @Override + Stack buildStack() { + return StackTools.adapt(DequeTools.arrayDeque()); + } + + @Override + public void testClone() { + // unsupported + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/EmptyStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/EmptyStackTests.java new file mode 100644 index 0000000000..6e7e606ca8 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/EmptyStackTests.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2015 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.stack; + +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.internal.stack.EmptyStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class EmptyStackTests + extends TestCase +{ + public EmptyStackTests(String name) { + super(name); + } + + public void testPush() { + Stack stack = StackTools.emptyStack(); + boolean exCaught = false; + try { + stack.push("junk"); + fail(); + } catch (UnsupportedOperationException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testPop() { + Stack stack = EmptyStack.instance(); + boolean exCaught = false; + try { + String bogus = stack.pop(); + fail(bogus); + } catch (EmptyStackException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testPeek() { + Stack stack = EmptyStack.instance(); + boolean exCaught = false; + try { + String bogus = stack.peek(); + fail(bogus); + } catch (EmptyStackException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testIsEmpty() { + Stack stack = EmptyStack.instance(); + assertTrue(stack.isEmpty()); + } + + public void testToString() { + Stack stack = EmptyStack.instance(); + assertEquals("[]", stack.toString()); + } + + public void testSerialization() throws Exception { + Stack stack = EmptyStack.instance(); + assertSame(stack, TestTools.serialize(stack)); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/FixedCapacityArrayStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/FixedCapacityArrayStackTests.java new file mode 100644 index 0000000000..315b4d66ee --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/FixedCapacityArrayStackTests.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * Copyright (c) 2015 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.stack; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.internal.stack.FixedCapacityArrayStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +@SuppressWarnings("nls") +public class FixedCapacityArrayStackTests + extends StackTests +{ + public FixedCapacityArrayStackTests(String name) { + super(name); + } + + @Override + FixedCapacityArrayStack buildStack() { + return StackTools.fixedCapacityArrayStack(10); + } + + public void testCollectionConstructor() { + ArrayList c = new ArrayList(); + c.add("first"); + c.add("second"); + c.add("third"); + c.add("fourth"); + c.add("fifth"); + c.add("sixth"); + c.add("seventh"); + c.add("eighth"); + c.add("ninth"); + c.add("tenth"); + Stack stack = StackTools.fixedCapacityArrayStack(c); + + assertFalse(stack.isEmpty()); + assertEquals("tenth", stack.peek()); + assertEquals("tenth", stack.pop()); + assertEquals("ninth", stack.pop()); + assertFalse(stack.isEmpty()); + assertEquals("eighth", stack.peek()); + assertEquals("eighth", stack.pop()); + assertEquals("seventh", stack.pop()); + assertEquals("sixth", stack.pop()); + assertEquals("fifth", stack.pop()); + assertEquals("fourth", stack.pop()); + assertEquals("third", stack.pop()); + assertEquals("second", stack.pop()); + assertEquals("first", stack.pop()); + assertTrue(stack.isEmpty()); + } + + public void testIsFull() { + FixedCapacityArrayStack stack = this.buildStack(); + assertFalse(stack.isFull()); + stack.push("first"); + assertFalse(stack.isFull()); + stack.push("second"); + assertFalse(stack.isFull()); + stack.push("third"); + stack.push("fourth"); + stack.push("fifth"); + stack.push("sixth"); + stack.push("seventh"); + stack.push("eighth"); + stack.push("ninth"); + stack.push("tenth"); + assertTrue(stack.isFull()); + + stack.pop(); + assertFalse(stack.isEmpty()); + stack.pop(); + stack.pop(); + stack.pop(); + stack.pop(); + stack.pop(); + stack.pop(); + stack.pop(); + assertFalse(stack.isFull()); + } + + public void testArrayCapacityExceeded() { + Stack stack = this.buildStack(); + assertTrue(stack.isEmpty()); + stack.push("first"); + assertFalse(stack.isEmpty()); + stack.push("second"); + assertFalse(stack.isEmpty()); + stack.push("third"); + stack.push("fourth"); + stack.push("fifth"); + stack.push("sixth"); + stack.push("seventh"); + stack.push("eighth"); + stack.push("ninth"); + stack.push("tenth"); + + boolean exCaught = false; + try { + stack.push("eleventh"); + fail("bogus"); + } catch (IllegalStateException ex) { + exCaught = true; + } + assertTrue(exCaught); + + assertFalse(stack.isEmpty()); + assertEquals("tenth", stack.peek()); + assertEquals("tenth", stack.pop()); + assertEquals("ninth", stack.pop()); + assertFalse(stack.isEmpty()); + assertEquals("eighth", stack.peek()); + assertEquals("eighth", stack.pop()); + assertEquals("seventh", stack.pop()); + assertEquals("sixth", stack.pop()); + assertEquals("fifth", stack.pop()); + assertEquals("fourth", stack.pop()); + assertEquals("third", stack.pop()); + assertEquals("second", stack.pop()); + assertEquals("first", stack.pop()); + assertTrue(stack.isEmpty()); + } + + public void testSerialization_fullArray() throws Exception { + Stack stack = new FixedCapacityArrayStack(3); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + this.verifyClone(stack, TestTools.serialize(stack)); + } + + public void testConstructorInt_IAE() throws Exception { + boolean exCaught = false; + try { + Stack stack = StackTools.fixedCapacityArrayStack(-3); + fail("bogus stack: " + stack); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testToString_empty() throws Exception { + Stack stack = this.buildStack(); + assertEquals("[]", stack.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/JptCommonUtilityStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/JptCommonUtilityStackTests.java new file mode 100644 index 0000000000..f1ff723c3e --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/JptCommonUtilityStackTests.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2005, 2015 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.stack; + +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * decentralize test creation code + */ +public class JptCommonUtilityStackTests { + + public static Test suite() { + TestSuite suite = new TestSuite(JptCommonUtilityStackTests.class.getPackage().getName()); + + suite.addTestSuite(ArrayStackTests.class); + suite.addTestSuite(DequeStackTests.class); + suite.addTestSuite(EmptyStackTests.class); + suite.addTestSuite(FixedCapacityArrayStackTests.class); + suite.addTestSuite(LinkedStackTests.class); + suite.addTestSuite(ListStackTests.class); + suite.addTestSuite(StackToolsTests.class); + suite.addTestSuite(SynchronizedStackTests.class); + + return suite; + } + + private JptCommonUtilityStackTests() { + super(); + throw new UnsupportedOperationException(); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/LinkedStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/LinkedStackTests.java new file mode 100644 index 0000000000..74e85690b2 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/LinkedStackTests.java @@ -0,0 +1,214 @@ +/******************************************************************************* + * Copyright (c) 2012, 2015 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.stack; + +import java.util.Arrays; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.stack.LinkedStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +@SuppressWarnings("nls") +public class LinkedStackTests + extends StackTests +{ + public LinkedStackTests(String name) { + super(name); + } + + @Override + Stack buildStack() { + return StackTools.linkedStack(); + } + + public void testConstructorInt_IAE() throws Exception { + boolean exCaught = false; + try { + Stack stack = StackTools.linkedStack(-3); + fail("bogus stack: " + stack); + } catch (IllegalArgumentException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testSize() { + Stack stack = this.buildStack(); + String first = "first"; + String second = "second"; + String third = "third"; + + assertEquals(0, ((Integer) ObjectTools.execute(stack, "size")).intValue()); + stack.push(first); + stack.push(second); + assertEquals(2, ((Integer) ObjectTools.execute(stack, "size")).intValue()); + stack.push(third); + assertEquals(3, ((Integer) ObjectTools.execute(stack, "size")).intValue()); + stack.pop(); + assertEquals(2, ((Integer) ObjectTools.execute(stack, "size")).intValue()); + stack.pop(); + stack.pop(); + assertEquals(0, ((Integer) ObjectTools.execute(stack, "size")).intValue()); + } + + public void testBuildElements() { + Stack stack = this.buildStack(); + String first = "first"; + String second = "second"; + String third = "third"; + stack.push(first); + stack.push(second); + stack.push(third); + + Object[] elements = new Object[] { third, second, first }; + assertTrue(Arrays.equals(elements, ((Object[]) ObjectTools.execute(stack, "buildElements")))); + } + + public void testNodeCache_max() { + Stack stack = new LinkedStack(2); + String first = "first"; + String second = "second"; + String third = "third"; + String fourth = "fourth"; + String fifth = "fifth"; + + Object factory = ObjectTools.get(stack, "nodeFactory"); + + this.verifyNodeCache(0, factory); + stack.push(first); + this.verifyNodeCache(0, factory); + stack.push(second); + stack.push(third); + stack.push(fourth); + stack.push(fifth); + this.verifyNodeCache(0, factory); + assertNull(ObjectTools.get(factory, "cacheHead")); + + stack.pop(); + this.verifyNodeCache(1, factory); + stack.pop(); + this.verifyNodeCache(2, factory); + stack.pop(); + this.verifyNodeCache(2, factory); + stack.pop(); + this.verifyNodeCache(2, factory); + stack.pop(); + this.verifyNodeCache(2, factory); + stack.push(first); + this.verifyNodeCache(1, factory); + stack.push(second); + this.verifyNodeCache(0, factory); + stack.push(third); + this.verifyNodeCache(0, factory); + } + + public void testNodeCache_unlimited() { + Stack stack = new LinkedStack(-1); + String first = "first"; + String second = "second"; + String third = "third"; + String fourth = "fourth"; + String fifth = "fifth"; + + Object factory = ObjectTools.get(stack, "nodeFactory"); + + this.verifyNodeCache(0, factory); + stack.push(first); + this.verifyNodeCache(0, factory); + stack.push(second); + stack.push(third); + stack.push(fourth); + stack.push(fifth); + this.verifyNodeCache(0, factory); + assertNull(ObjectTools.get(factory, "cacheHead")); + + stack.pop(); + this.verifyNodeCache(1, factory); + stack.pop(); + this.verifyNodeCache(2, factory); + stack.pop(); + this.verifyNodeCache(3, factory); + stack.pop(); + this.verifyNodeCache(4, factory); + stack.pop(); + this.verifyNodeCache(5, factory); + stack.push(first); + this.verifyNodeCache(4, factory); + stack.push(second); + this.verifyNodeCache(3, factory); + stack.push(third); + this.verifyNodeCache(2, factory); + stack.push(fourth); + this.verifyNodeCache(1, factory); + stack.push(fifth); + this.verifyNodeCache(0, factory); + } + + public void verifyNodeCache(int size, Object factory) { + assertEquals(size, ((Integer) ObjectTools.get(factory, "cacheSize")).intValue()); + int nodeCount = 0; + for (Object node = ObjectTools.get(factory, "cacheHead"); node != null; node = ObjectTools.get(node, "next")) { + nodeCount++; + } + assertEquals(size, nodeCount); + } + + public void testNodeToString() { + Stack queue = StackTools.linkedStack(); + String first = "first"; + String second = "second"; + String third = "third"; + queue.push(first); + queue.push(second); + queue.push(third); + + Object head = ObjectTools.get(queue, "head"); + assertTrue(head.toString().startsWith("LinkedStack.Node")); + assertTrue(head.toString().endsWith("(third)")); + } + + public void testToString_empty() throws Exception { + Stack stack = this.buildStack(); + assertEquals("[]", stack.toString()); + } + + public void testSimpleNodeFactoryToString() { + Stack queue = StackTools.linkedStack(); + Object factory = ObjectTools.get(queue, "nodeFactory"); + assertEquals("LinkedStack.SimpleNodeFactory", factory.toString()); + } + + public void testCachingNodeFactoryToString() { + Stack queue = StackTools.linkedStack(20); + Object factory = ObjectTools.get(queue, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedStack.CachingNodeFactory")); + assertTrue(factory.toString().endsWith("(0)")); + } + + public void testClone_caching() throws Exception { + LinkedStack original = StackTools.linkedStack(20); + original.push("first"); + + LinkedStack clone = original.clone(); + assertEquals(original.peek(), clone.peek()); + assertEquals(original.pop(), clone.pop()); + assertNotSame(original, clone); + assertTrue(original.isEmpty()); + assertEquals(original.isEmpty(), clone.isEmpty()); + + original.push("second"); + assertFalse(original.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + + Object factory = ObjectTools.get(original, "nodeFactory"); + assertTrue(factory.toString().startsWith("LinkedStack.CachingNodeFactory")); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ListStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ListStackTests.java new file mode 100644 index 0000000000..2c0c3e66a9 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/ListStackTests.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2015 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.stack; + +import java.util.ArrayList; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.stack.Stack; + +public class ListStackTests + extends StackTests +{ + public ListStackTests(String name) { + super(name); + } + + @Override + Stack buildStack() { + return StackTools.adapt(new ArrayList()); + } + + @Override + public void testClone() { + // unsupported + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackTests.java new file mode 100644 index 0000000000..54fc775ef1 --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackTests.java @@ -0,0 +1,169 @@ +/******************************************************************************* + * Copyright (c) 2007, 2015 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.stack; + +import java.util.EmptyStackException; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.MultiThreadedTestCase; +import org.eclipse.jpt.common.utility.tests.internal.TestTools; + +//subclass MultiThreadedTestCase for subclasses of this class +@SuppressWarnings("nls") +public abstract class StackTests + extends MultiThreadedTestCase +{ + public StackTests(String name) { + super(name); + } + + abstract Stack buildStack(); + + public void testIsEmpty() { + Stack 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 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 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 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 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() { + Stack stack = this.buildStack(); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + @SuppressWarnings("unchecked") + Stack clone = (Stack) ObjectTools.execute(stack, "clone"); + this.verifyClone(stack, clone); + } + + public void testSerialization() throws Exception { + Stack stack = this.buildStack(); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + this.verifyClone(stack, TestTools.serialize(stack)); + } + + protected void verifyClone(Stack original, Stack 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()); + } + + public void testSerialization_empty() throws Exception { + Stack stack = this.buildStack(); + Stack clone = TestTools.serialize(stack); + assertNotSame(stack, clone); + assertTrue(clone.isEmpty()); + stack.push("fourth"); + assertFalse(stack.isEmpty()); + // clone should still be empty + assertTrue(clone.isEmpty()); + } + + public void testToString() throws Exception { + Stack stack = this.buildStack(); + stack.push("first"); + stack.push("second"); + stack.push("third"); + + assertEquals("[third, second, first]", stack.toString()); + } +} diff --git a/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackToolsTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackToolsTests.java new file mode 100644 index 0000000000..79d0c86c8d --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/StackToolsTests.java @@ -0,0 +1,465 @@ +/******************************************************************************* + * Copyright (c) 2015 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.stack; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.jpt.common.utility.internal.ClassTools; +import org.eclipse.jpt.common.utility.internal.ObjectTools; +import org.eclipse.jpt.common.utility.internal.StringTools; +import org.eclipse.jpt.common.utility.internal.queue.ArrayQueue; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.stack.ArrayStack; +import org.eclipse.jpt.common.utility.internal.stack.LinkedStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.internal.stack.SynchronizedStack; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.transformer.Transformer; +import junit.framework.TestCase; + +@SuppressWarnings("nls") +public class StackToolsTests + extends TestCase +{ + public StackToolsTests(String name) { + super(name); + } + + // ********** push all ********** + + public void testPushAllIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(); + assertTrue(StackTools.pushAll(stack, iterable)); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testPushAllIterable_empty() { + ArrayList iterable = new ArrayList(); + Stack stack = StackTools.arrayStack(); + assertFalse(StackTools.pushAll(stack, iterable)); + assertTrue(stack.isEmpty()); + } + + public void testPushAllIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(); + assertTrue(StackTools.pushAll(stack, iterable.iterator())); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testPushAllArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(); + assertTrue(StackTools.pushAll(stack, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testPushAllArray_empty() { + ArrayList iterable = new ArrayList(); + Stack stack = StackTools.arrayStack(); + assertFalse(StackTools.pushAll(stack, iterable.toArray(StringTools.EMPTY_STRING_ARRAY))); + assertTrue(stack.isEmpty()); + } + + + // ********** pop all ********** + + public void testPopAll() { + ArrayStack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + ArrayList list = StackTools.popAll(stack); + assertEquals("three", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("one", list.get(2)); + } + + public void testPopAllToCollection() { + Stack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + ArrayList list = new ArrayList(); + assertTrue(StackTools.popAllTo(stack, list)); + assertEquals("three", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("one", list.get(2)); + } + + public void testPopAllToCollection_empty() { + ArrayStack stack = StackTools.arrayStack(); + ArrayList list = new ArrayList(); + assertFalse(StackTools.popAllTo(stack, list)); + assertTrue(list.isEmpty()); + } + + public void testPopAllToListIndex() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Stack stack = StackTools.arrayStack(); + stack.push("aaa"); + stack.push("bbb"); + stack.push("ccc"); + assertTrue(StackTools.popAllTo(stack, list, 2)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("ccc", list.get(2)); + assertEquals("bbb", list.get(3)); + assertEquals("aaa", list.get(4)); + assertEquals("three", list.get(5)); + } + + public void testPopAllToListIndex_end() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Stack stack = StackTools.arrayStack(); + stack.push("aaa"); + stack.push("bbb"); + stack.push("ccc"); + assertTrue(StackTools.popAllTo(stack, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + assertEquals("ccc", list.get(3)); + assertEquals("bbb", list.get(4)); + assertEquals("aaa", list.get(5)); + } + + public void testPopAllToListIndex_empty() { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + Stack stack = StackTools.arrayStack(); + assertFalse(StackTools.popAllTo(stack, list, 3)); + assertEquals("one", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("three", list.get(2)); + } + + public void testPopAllToStack() { + ArrayStack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + ArrayStack stack2 = StackTools.arrayStack(); + assertTrue(StackTools.popAllTo(stack, stack2)); + assertEquals("one", stack2.pop()); + assertEquals("two", stack2.pop()); + assertEquals("three", stack2.pop()); + } + + public void testPopAllToStack_empty() { + ArrayStack stack = StackTools.arrayStack(); + ArrayStack stack2 = StackTools.arrayStack(); + assertFalse(StackTools.popAllTo(stack, stack2)); + assertTrue(stack2.isEmpty()); + } + + public void testPopAllToQueue() { + ArrayStack stack = StackTools.arrayStack(); + stack.push("one"); + stack.push("two"); + stack.push("three"); + ArrayQueue queue = QueueTools.arrayQueue(); + assertTrue(StackTools.popAllTo(stack, queue)); + assertEquals("three", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("one", queue.dequeue()); + } + + public void testPopAllToQueue_empty() { + ArrayStack stack = StackTools.arrayStack(); + ArrayQueue queue = QueueTools.arrayQueue(); + assertFalse(StackTools.popAllTo(stack, queue)); + assertTrue(queue.isEmpty()); + } + + public void testPopAllToMapTransformer() { + ArrayStack stack = StackTools.arrayStack(); + stack.push("zero"); + stack.push("one"); + stack.push("two"); + Mapmap = new HashMap(); + assertTrue(StackTools.popAllTo(stack, map, FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testPopAllToMapTransformer_empty() { + ArrayStack stack = StackTools.arrayStack(); + Mapmap = new HashMap(); + assertFalse(StackTools.popAllTo(stack, map, FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testPopAllToMapTransformerTransformer() { + ArrayStack stack = StackTools.arrayStack(); + stack.push("zero"); + stack.push("one"); + stack.push("two"); + Mapmap = new HashMap(); + assertTrue(StackTools.popAllTo(stack, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testPopAllToMapTransformerTransformer_empty() { + ArrayStack stack = StackTools.arrayStack(); + Mapmap = new HashMap(); + assertFalse(StackTools.popAllTo(stack, map, FIRST_LETTER_TRANSFORMER, EMPHASIZER)); + assertTrue(map.isEmpty()); + } + + public static final Transformer FIRST_LETTER_TRANSFORMER = new FirstLetterTransformer(); + + /* CU private */ static class FirstLetterTransformer + implements Transformer + { + public String transform(String string) { + return string.substring(0, 1); + } + @Override + public String toString() { + return this.getClass().getSimpleName(); + } + } + + public static final Transformer EMPHASIZER = new StringTools.CharDelimiter('*'); + + + // ********** array stack ********** + + public void testArrayStack() { + ArrayStack d = StackTools.arrayStack(); + assertTrue(d.isEmpty()); + } + + public void testArrayStackInt() { + ArrayStack d = StackTools.arrayStack(20); + assertTrue(d.isEmpty()); + assertEquals(20, ((Object[]) ObjectTools.get(d, "elements")).length); + } + + public void testArrayStackIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(iterable); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testArrayStackIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(iterable, 5); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testArrayStackIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(iterable.iterator()); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testArrayStackIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(iterable.iterator(), 5); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testArrayStackArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.arrayStack(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + // ********** linked stack ********** + + public void testLinkedStack() { + LinkedStack d = StackTools.linkedStack(); + assertTrue(d.isEmpty()); + } + + public void testLinkedStackInt() { + LinkedStack d = StackTools.linkedStack(20); + assertTrue(d.isEmpty()); + } + + public void testLinkedStackIterable() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.linkedStack(iterable); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testLinkedStackIterableInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.linkedStack(iterable, 5); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testLinkedStackIterator() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.linkedStack(iterable.iterator()); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testLinkedStackIteratorInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.linkedStack(iterable.iterator(), 5); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testLinkedStackArray() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.linkedStack(iterable.toArray(StringTools.EMPTY_STRING_ARRAY)); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + public void testLinkedStackArrayInt() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.linkedStack(iterable.toArray(StringTools.EMPTY_STRING_ARRAY), 2); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + // ********** fixed-capacity array stack ********** + + public void testFixedCapacityArrayStackCollection() { + ArrayList iterable = new ArrayList(); + iterable.add("one"); + iterable.add("two"); + iterable.add("three"); + Stack stack = StackTools.fixedCapacityArrayStack(iterable); + assertEquals("three", stack.pop()); + assertEquals("two", stack.pop()); + assertEquals("one", stack.pop()); + } + + // ********** misc ********** + + public void testSynchronizedStackObject() { + Object lock = new Object(); + SynchronizedStack stack = StackTools.synchronizedStack(lock); + String first = "first"; + String second = "second"; + + stack.push(first); + stack.push(second); + assertEquals(second, stack.pop()); + assertEquals(first, stack.pop()); + assertEquals(lock, stack.getMutex()); + } + + public void testSynchronizedStackStackObject() { + Object lock = new Object(); + Stack innerStack = StackTools.arrayStack(); + String first = "first"; + String second = "second"; + innerStack.push(first); + innerStack.push(second); + + SynchronizedStack stack = StackTools.synchronizedStack(innerStack, lock); + assertEquals(second, stack.pop()); + assertEquals(first, stack.pop()); + assertEquals(lock, stack.getMutex()); + } + + public void testConstructor() { + boolean exCaught = false; + try { + Object at = ClassTools.newInstance(StackTools.class); + fail("bogus: " + at); + } 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/stack/SynchronizedStackTests.java b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/SynchronizedStackTests.java new file mode 100644 index 0000000000..d8bf22803e --- /dev/null +++ b/common/tests/org.eclipse.jpt.common.utility.tests/src/org/eclipse/jpt/common/utility/tests/internal/stack/SynchronizedStackTests.java @@ -0,0 +1,792 @@ +/******************************************************************************* + * Copyright (c) 2007, 2015 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.stack; + +import java.util.ArrayList; +import java.util.EmptyStackException; +import java.util.HashMap; +import java.util.Map; +import org.eclipse.jpt.common.utility.internal.queue.QueueTools; +import org.eclipse.jpt.common.utility.internal.stack.LinkedStack; +import org.eclipse.jpt.common.utility.internal.stack.StackTools; +import org.eclipse.jpt.common.utility.internal.stack.SynchronizedStack; +import org.eclipse.jpt.common.utility.queue.Queue; +import org.eclipse.jpt.common.utility.stack.Stack; +import org.eclipse.jpt.common.utility.tests.internal.deque.DequeToolsTests; + +@SuppressWarnings("nls") +public class SynchronizedStackTests + extends StackTests +{ + private volatile SynchronizedStack ss; + volatile boolean timeoutOccurred; + volatile long startTime; + volatile long endTime; + volatile Object poppedObject; + + boolean commandExecuted; + + static final String ITEM_1 = new String(); + static final String ITEM_2 = new String(); + + public SynchronizedStackTests(String name) { + super(name); + } + + @Override + Stack buildStack() { + return StackTools.synchronizedStack(); + } + + @Override + public void testClone() { + // synchronized stack is not cloneable + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + this.ss = StackTools.synchronizedStack(); + this.timeoutOccurred = false; + this.startTime = 0; + this.endTime = 0; + this.poppedObject = null; + } + + // ********** constructor ********** + + public void testConstructorStack() throws Exception { + Stack innerStack = StackTools.arrayStack(); + SynchronizedStack stack = StackTools.synchronizedStack(innerStack); + assertNotNull(stack); + assertSame(stack, stack.getMutex()); + } + + public void testConstructorStack_NPE() throws Exception { + boolean exCaught = false; + try { + Stack stack = StackTools.synchronizedStack(null); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorStackObject() throws Exception { + String mutex = "mutex"; + Stack innerStack = StackTools.arrayStack(); + SynchronizedStack stack = StackTools.synchronizedStack(innerStack, mutex); + assertNotNull(stack); + assertSame(mutex, stack.getMutex()); + } + + public void testConstructorStackObject_NPE1() throws Exception { + String mutex = "mutex"; + boolean exCaught = false; + try { + Stack stack = StackTools.synchronizedStack(null, mutex); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + public void testConstructorStackObject_NPE2() throws Exception { + Stack innerStack = StackTools.arrayStack(); + boolean exCaught = false; + try { + Stack stack = StackTools.synchronizedStack(innerStack, null); + fail("bogus stack: " + stack); + } catch (NullPointerException ex) { + exCaught = true; + } + assertTrue(exCaught); + } + + // ********** concurrent access ********** + + /** + * test first with an unsynchronized stack, + * then with a synchronized stack + */ + public void testConcurrentPop() throws Exception { + this.verifyConcurrentPop(new SlowLinkedStack(), "second"); + this.verifyConcurrentPop(new SlowSynchronizedStack(), "first"); + } + + private void verifyConcurrentPop(SlowStack slowStack, String expected) throws Exception { + slowStack.push("first"); + slowStack.push("second"); + + Thread thread = this.buildThread(this.buildRunnablePop(slowStack)); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(expected, slowStack.pop()); + thread.join(); + assertTrue(slowStack.isEmpty()); + } + + private Runnable buildRunnablePop(final SlowStack slowStack) { + return new Runnable() { + public void run() { + slowStack.slowPop(); + } + }; + } + + /** + * test first with an unsynchronized stack, + * then with a synchronized stack + */ + public void testConcurrentPush() throws Exception { + this.verifyConcurrentPush(new SlowLinkedStack(), "first", "second"); + this.verifyConcurrentPush(new SlowSynchronizedStack(), "second", "first"); + } + + private void verifyConcurrentPush(SlowStack slowStack, String first, String second) throws Exception { + Thread thread = this.buildThread(this.buildRunnablePush(slowStack, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + slowStack.push("second"); + thread.join(); + assertEquals(first, slowStack.pop()); + assertEquals(second, slowStack.pop()); + assertTrue(slowStack.isEmpty()); + } + + private Runnable buildRunnablePush(final SlowStack slowStack, final String element) { + return new Runnable() { + public void run() { + slowStack.slowPush(element); + } + }; + } + + /** + * test first with an unsynchronized stack, + * then with a synchronized stack + */ + public void testConcurrentIsEmpty() throws Exception { + this.verifyConcurrentIsEmpty(new SlowLinkedStack(), true); + this.verifyConcurrentIsEmpty(new SlowSynchronizedStack(), false); + } + + private void verifyConcurrentIsEmpty(SlowStack slowStack, boolean empty) throws Exception { + Thread thread = this.buildThread(this.buildRunnablePush(slowStack, "first")); + thread.start(); + Thread.sleep(TWO_TICKS); + + assertEquals(empty, slowStack.isEmpty()); + thread.join(); + assertEquals("first", slowStack.pop()); + assertTrue(slowStack.isEmpty()); + } + + + private interface SlowStack extends Stack { + Object slowPop(); + void slowPush(E element); + } + + private class SlowLinkedStack extends LinkedStack implements SlowStack { + private static final long serialVersionUID = 1L; + SlowLinkedStack() { + super(); + } + public Object slowPop() { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.pop(); + } + public void slowPush(E element) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.push(element); + } + } + + private class SlowSynchronizedStack extends SynchronizedStack implements SlowStack { + private static final long serialVersionUID = 1L; + SlowSynchronizedStack() { + super(StackTools.linkedStack()); + } + public Object slowPop() { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + return this.pop(); + } + } + public void slowPush(E element) { + synchronized (this.getMutex()) { + try { + Thread.sleep(5 * TICK); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + this.push(element); + } + } + } + + // ********** waits ********** + + public void testWaitUntilEmpty() throws Exception { + this.verifyWaitUntilEmpty(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been popped by t1... + 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 testWaitUntilEmpty2() throws Exception { + this.verifyWaitUntilEmpty(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been popped by t1... + 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 testWaitUntilEmptyTimeout() throws Exception { + this.verifyWaitUntilEmpty(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and the stack was popped... + 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() < THREE_TICKS); + } + + private void verifyWaitUntilEmpty(long timeout) throws Exception { + this.ss.push(ITEM_1); + Runnable r1 = this.buildRunnable(this.buildPopCommand(), this.ss, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitUntilEmptyCommand(timeout), this.ss, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitUntilEmptyCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedStack synchronizedStack) throws InterruptedException { + SynchronizedStackTests.this.startTime = System.currentTimeMillis(); + SynchronizedStackTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedStack); + SynchronizedStackTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedStack synchronizedStack) throws InterruptedException { + if (timeout < 0) { + synchronizedStack.waitUntilEmpty(); + return false; + } + return ! synchronizedStack.waitUntilEmpty(timeout); + } + }; + } + + public void testWaitUntilNotEmpty() throws Exception { + this.verifyWaitUntilNotEmpty(-1); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been pushed by t1... + assertFalse(this.ss.isEmpty()); + assertSame(ITEM_1, this.ss.peek()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilNotEmpty2() throws Exception { + this.verifyWaitUntilNotEmpty(0); + // no timeout occurs... + assertFalse(this.timeoutOccurred); + // ...and an item should have been pushed by t1... + assertFalse(this.ss.isEmpty()); + assertSame(ITEM_1, this.ss.peek()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() > TICK); + } + + public void testWaitUntilNotEmptyTimeout() throws Exception { + this.verifyWaitUntilNotEmpty(TICK); + // timeout occurs... + assertTrue(this.timeoutOccurred); + // ...and an item should have been pushed by t1... + assertFalse(this.ss.isEmpty()); + assertSame(ITEM_1, this.ss.peek()); + // make a reasonable guess about how long t2 took + assertTrue(this.calculateElapsedTime() < THREE_TICKS); + } + + private void verifyWaitUntilNotEmpty(long timeout) throws Exception { + Runnable r1 = this.buildRunnable(this.buildPushCommand(), this.ss, TWO_TICKS); + Runnable r2 = this.buildRunnable(this.buildWaitUntilNotEmptyCommand(timeout), this.ss, 0); + Thread t1 = this.buildThread(r1); + Thread t2 = this.buildThread(r2); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + + private Command buildWaitUntilNotEmptyCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedStack synchronizedStack) throws InterruptedException { + SynchronizedStackTests.this.startTime = System.currentTimeMillis(); + SynchronizedStackTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedStack); + SynchronizedStackTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedStack synchronizedStack) throws InterruptedException { + if (timeout < 0) { + synchronizedStack.waitUntilNotEmpty(); + return false; + } + return ! synchronizedStack.waitUntilNotEmpty(timeout); + } + }; + } + + public void testWaitToPop() throws Exception { + this.verifyWaitToPop(-1); + // 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 testWaitToPop2() 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(); + } + + private Command buildWaitToPopCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedStack synchronizedStack) throws InterruptedException { + SynchronizedStackTests.this.startTime = System.currentTimeMillis(); + this.waitToPop(synchronizedStack); + SynchronizedStackTests.this.endTime = System.currentTimeMillis(); + } + private void waitToPop(SynchronizedStack synchronizedStack) throws InterruptedException { + if (timeout < 0) { + SynchronizedStackTests.this.poppedObject = synchronizedStack.waitToPop(); + return; + } + try { + SynchronizedStackTests.this.poppedObject = synchronizedStack.waitToPop(timeout); + } catch (EmptyStackException ex) { + SynchronizedStackTests.this.timeoutOccurred = true; + } + } + }; + } + + public void testWaitToPush() throws Exception { + this.verifyWaitToPush(-1); + // 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 testWaitToPush2() 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 buildWaitToPushCommand(final long timeout) { + return new Command() { + public void execute(SynchronizedStack synchronizedStack) throws InterruptedException { + SynchronizedStackTests.this.startTime = System.currentTimeMillis(); + SynchronizedStackTests.this.timeoutOccurred = this.timeoutOccurred(synchronizedStack); + SynchronizedStackTests.this.endTime = System.currentTimeMillis(); + } + private boolean timeoutOccurred(SynchronizedStack synchronizedStack) throws InterruptedException { + if (timeout < 0) { + synchronizedStack.waitToPush(ITEM_2); + return false; + } + return ! synchronizedStack.waitToPush(ITEM_2, timeout); + } + }; + } + + private Command buildPushCommand() { + return new Command() { + public void execute(SynchronizedStack synchronizedStack) { + synchronizedStack.push(ITEM_1); + } + }; + } + + private Command buildPopCommand() { + return new Command() { + public void execute(SynchronizedStack synchronizedStack) { + SynchronizedStackTests.this.poppedObject = synchronizedStack.pop(); + } + }; + } + + private Runnable buildRunnable(final Command command, final SynchronizedStack 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 synchronizedStack) throws InterruptedException; + } + + + // ********** execute ********** + + public void testExecute() throws Exception { + org.eclipse.jpt.common.utility.command.Command command = new org.eclipse.jpt.common.utility.command.Command() { + public void execute() { + SynchronizedStackTests.this.commandExecuted = true; + } + }; + this.commandExecuted = false; + this.ss.execute(command); + assertTrue(this.commandExecuted); + } + + + // ********** additional protocol ********** + + public void testPushAllIterable() throws Exception { + ArrayList list = new ArrayList(); + list.add("one"); + list.add("two"); + list.add("three"); + this.ss.pushAll(list); + assertEquals("three", this.ss.pop()); + assertEquals("two", this.ss.pop()); + assertEquals("one", this.ss.pop()); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllIterable_empty() throws Exception { + ArrayList list = new ArrayList(); + this.ss.pushAll(list); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllObjectArray() throws Exception { + this.ss.pushAll(new String[] { "one", "two", "three" }); + assertEquals("three", this.ss.pop()); + assertEquals("two", this.ss.pop()); + assertEquals("one", this.ss.pop()); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllObjectArray_empty() throws Exception { + this.ss.pushAll(new String[0]); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllStack() throws Exception { + Stack s2 = StackTools.arrayStack(); + s2.push("one"); + s2.push("two"); + s2.push("three"); + this.ss.pushAll(s2); + assertEquals("one", this.ss.pop()); + assertEquals("two", this.ss.pop()); + assertEquals("three", this.ss.pop()); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllStack_empty() throws Exception { + Stack s2 = StackTools.arrayStack(); + this.ss.pushAll(s2); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllQueue() throws Exception { + Queue queue = QueueTools.arrayQueue(); + queue.enqueue("one"); + queue.enqueue("two"); + queue.enqueue("three"); + this.ss.pushAll(queue); + assertEquals("three", this.ss.pop()); + assertEquals("two", this.ss.pop()); + assertEquals("one", this.ss.pop()); + assertTrue(this.ss.isEmpty()); + } + + public void testPushAllQueue_empty() throws Exception { + Queue queue = QueueTools.arrayQueue(); + this.ss.pushAll(queue); + assertTrue(this.ss.isEmpty()); + } + + public void testPopAll() throws Exception { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("three"); + ArrayList list = this.ss.popAll(); + assertTrue(this.ss.isEmpty()); + assertEquals("three", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("one", list.get(2)); + } + + public void testPopAll_empty() throws Exception { + ArrayList list = this.ss.popAll(); + assertTrue(this.ss.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testPopAllToCollection() throws Exception { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("three"); + ArrayList list = new ArrayList(); + assertTrue(this.ss.popAllTo(list)); + assertTrue(this.ss.isEmpty()); + assertEquals("three", list.get(0)); + assertEquals("two", list.get(1)); + assertEquals("one", list.get(2)); + } + + public void testPopAllToCollection_empty() throws Exception { + ArrayList list = new ArrayList(); + assertFalse(this.ss.popAllTo(list)); + assertTrue(this.ss.isEmpty()); + assertTrue(list.isEmpty()); + } + + public void testPopAllToListInt() throws Exception { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.ss.popAllTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("three", list.get(2)); + assertEquals("two", list.get(3)); + assertEquals("one", list.get(4)); + assertEquals("ccc", list.get(5)); + } + + public void testPopAllToListInt_end() throws Exception { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("three"); + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertTrue(this.ss.popAllTo(list, 3)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + assertEquals("three", list.get(3)); + assertEquals("two", list.get(4)); + assertEquals("one", list.get(5)); + } + + public void testPopAllToListInt_empty() throws Exception { + ArrayList list = new ArrayList(); + list.add("aaa"); + list.add("bbb"); + list.add("ccc"); + assertFalse(this.ss.popAllTo(list, 2)); + assertEquals("aaa", list.get(0)); + assertEquals("bbb", list.get(1)); + assertEquals("ccc", list.get(2)); + } + + public void testPopAllToStack() throws Exception { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("three"); + Stack s2 = StackTools.arrayStack(); + assertTrue(this.ss.popAllTo(s2)); + assertTrue(this.ss.isEmpty()); + assertEquals("one", s2.pop()); + assertEquals("two", s2.pop()); + assertEquals("three", s2.pop()); + assertTrue(s2.isEmpty()); + } + + public void testPopAllToStack_empty() throws Exception { + Stack s2 = StackTools.arrayStack(); + assertFalse(this.ss.popAllTo(s2)); + assertTrue(this.ss.isEmpty()); + assertTrue(s2.isEmpty()); + } + + public void testPopAllToQueue() throws Exception { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("three"); + Queue queue = QueueTools.arrayQueue(); + assertTrue(this.ss.popAllTo(queue)); + assertTrue(this.ss.isEmpty()); + assertEquals("three", queue.dequeue()); + assertEquals("two", queue.dequeue()); + assertEquals("one", queue.dequeue()); + assertTrue(queue.isEmpty()); + } + + public void testPopAllToQueue_empty() throws Exception { + Queue queue = QueueTools.arrayQueue(); + assertFalse(this.ss.popAllTo(queue)); + assertTrue(this.ss.isEmpty()); + assertTrue(queue.isEmpty()); + } + + public void testPopAllToMapTransformer() { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("zero"); + Mapmap = new HashMap(); + assertTrue(this.ss.popAllTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertEquals("one", map.get("o")); + assertEquals("two", map.get("t")); + assertEquals("zero", map.get("z")); + } + + public void testPopAllToMapTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.ss.popAllTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER)); + assertTrue(map.isEmpty()); + } + + public void testPopAllToMapTransformerTransformer() { + this.ss.push("one"); + this.ss.push("two"); + this.ss.push("zero"); + Mapmap = new HashMap(); + assertTrue(this.ss.popAllTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertEquals("*one*", map.get("o")); + assertEquals("*two*", map.get("t")); + assertEquals("*zero*", map.get("z")); + } + + public void testPopAllToMapTransformerTransformer_empty() { + Mapmap = new HashMap(); + assertFalse(this.ss.popAllTo(map, DequeToolsTests.FIRST_LETTER_TRANSFORMER, DequeToolsTests.EMPHASIZER)); + assertTrue(map.isEmpty()); + } +} diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/AbstractJaxbNode.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/AbstractJaxbNode.java index 313eff6c4c..05ff36c0c7 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/AbstractJaxbNode.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/AbstractJaxbNode.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2013 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -309,7 +309,7 @@ public abstract class AbstractJaxbNode * updated (false). */ protected void sync(boolean sync) { - HashSet contextElements = CollectionTools.set(this.getContextElements()); + HashSet contextElements = CollectionTools.hashSet(this.getContextElements()); int resourceIndex = 0; for (R resourceElement : this.getResourceElements()) { diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/SchemaLibraryImpl.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/SchemaLibraryImpl.java index c5c5bcbc74..3989aff4bb 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/SchemaLibraryImpl.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/SchemaLibraryImpl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2013 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -54,7 +54,7 @@ public class SchemaLibraryImpl public List getSchemaLocations() { return Collections.unmodifiableList( - ListTools.list( + ListTools.arrayList( IterableTools.transform(this.schemaEntries, SchemaEntry.LOCATION_TRANSFORMER))); } diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/AbstractJaxbContextRoot.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/AbstractJaxbContextRoot.java index c5fcbcd9de..d8a1490d82 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/AbstractJaxbContextRoot.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/AbstractJaxbContextRoot.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2013 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -93,7 +93,7 @@ public abstract class AbstractJaxbContextRoot Set totalTypeNames = new HashSet(); // process types with annotations and in jaxb.index files - for (String typeName: CollectionTools.set(calculateInitialTypeNames())) { // ensure iterable is unique + for (String typeName: CollectionTools.hashSet(calculateInitialTypeNames())) { // ensure iterable is unique totalTypeNames.add(typeName); addType_(buildType(typeName)); } @@ -122,18 +122,18 @@ public abstract class AbstractJaxbContextRoot super.update(); // keep a master list of these so that objects are updated only once - final Set packagesToUpdate = CollectionTools.set(); - final Set typesToUpdate = CollectionTools.set(); + final Set packagesToUpdate = CollectionTools.hashSet(); + final Set typesToUpdate = CollectionTools.hashSet(); // keep a (shrinking) running list of these so that we know which ones we do eventually need to remove - final Set packagesToRemove = CollectionTools.set(this.packages.keySet()); - final Set typesToRemove = CollectionTools.set(this.types.keySet()); + final Set packagesToRemove = CollectionTools.hashSet(this.packages.keySet()); + final Set typesToRemove = CollectionTools.hashSet(this.types.keySet()); // keep a master list of all types that we've processed so we don't process them again - final Set totalTypes = CollectionTools.set(); + final Set totalTypes = CollectionTools.hashSet(); // keep a running list of types that we need to scan for further referenced types - final Set typesToScan = CollectionTools.set(); + final Set typesToScan = CollectionTools.hashSet(); // process packages with annotations first for (String pkg : calculateInitialPackageNames()) { @@ -148,7 +148,7 @@ public abstract class AbstractJaxbContextRoot // calculate initial types (annotated or listed in jaxb.index files) final Set resourceTypesToProcess - = CollectionTools.set(calculateInitialTypeNames()); + = CollectionTools.hashSet(calculateInitialTypeNames()); // store set of types that are referenced (and should therefore be default mapped) final Set referencedTypes = new HashSet(); @@ -215,7 +215,7 @@ public abstract class AbstractJaxbContextRoot * calculate set of packages that can be determined purely by presence of package annotations */ protected Set calculateInitialPackageNames() { - return CollectionTools.set( + return CollectionTools.hashSet( IterableTools.transform(getJaxbProject().getAnnotatedJavaResourcePackages(), JavaResourcePackage.NAME_TRANSFORMER)); } @@ -223,7 +223,7 @@ public abstract class AbstractJaxbContextRoot * calculate set of packages that can be determined from type names */ protected Set calculatePackageNames(Set typeNames) { - Set packageNames = CollectionTools.set(); + Set packageNames = CollectionTools.hashSet(); for (String typeName : typeNames) { JavaType jaxbType = this.types.get(typeName); if (jaxbType != null) { diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/ContextContainerTools.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/ContextContainerTools.java index 1cfff80b7b..fda2038721 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/ContextContainerTools.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/ContextContainerTools.java @@ -1,3 +1,12 @@ +/******************************************************************************* + * Copyright (c) 2010, 2015 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.jaxb.core.internal.context; import java.util.ArrayList; @@ -86,7 +95,7 @@ public class ContextContainerTools { * updated (false). */ protected static void sync(Adapter adapter, boolean sync) { - HashSet contextElements = CollectionTools.set(adapter.getContextElements()); + HashSet contextElements = CollectionTools.hashSet(adapter.getContextElements()); ArrayList contextElementsToSync = new ArrayList(contextElements.size()); int resourceIndex = 0; diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaAttributesContainer.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaAttributesContainer.java index 1da4952d28..7becc89143 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaAttributesContainer.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaAttributesContainer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -137,7 +137,7 @@ public class GenericJavaAttributesContainer */ private void initializePublicMemberAccessAttributes() { this.initializeFieldAttributes(JavaResourceField.IS_RELEVANT_FOR_PUBLIC_MEMBER_ACCESS); - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all persistable resource method getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -169,7 +169,7 @@ public class GenericJavaAttributesContainer private void intializePropertyAccessAttributes() { this.initializeFieldAttributes(JavaResourceAnnotatedElement.IS_ANNOTATED); - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -245,7 +245,7 @@ public class GenericJavaAttributesContainer } private void initializeAnnotatedPropertyAttributes() { - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -312,11 +312,11 @@ public class GenericJavaAttributesContainer * 4. all annotated methods (some will have a matching getter/setter, some will be standalone) */ private void syncPublicMemberAccessAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getAttributes()); this.syncFieldAttributes(contextAttributes, JavaResourceField.IS_RELEVANT_FOR_PUBLIC_MEMBER_ACCESS); - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all persistable resource method getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -347,7 +347,7 @@ public class GenericJavaAttributesContainer * 2. all annotated methods getters/setters */ private void syncFieldAccessAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getAttributes()); this.syncFieldAttributes(contextAttributes, JavaResourceField.IS_RELEVANT_FOR_FIELD_ACCESS); this.syncAnnotatedPropertyAttributes(contextAttributes); @@ -360,11 +360,11 @@ public class GenericJavaAttributesContainer * 3. all annotated methods getters/setters that don't have a matching pair */ private void syncPropertyAccessAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getAttributes()); this.syncFieldAttributes(contextAttributes, JavaResourceAnnotatedElement.IS_ANNOTATED); - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -395,14 +395,14 @@ public class GenericJavaAttributesContainer * 2. all annotated methods getters/setters (some will have a matching getter/setter, some will be standalone) */ private void syncNoneAccessAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getAttributes()); this.syncFieldAttributes(contextAttributes, JavaResourceAnnotatedElement.IS_ANNOTATED); this.syncAnnotatedPropertyAttributes(contextAttributes); } private void syncAnnotatedPropertyAttributes(HashSet contextAttributes) { - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaClassMapping.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaClassMapping.java index ac5290d5dd..9e52c22e3f 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaClassMapping.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaClassMapping.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -532,8 +532,8 @@ public class GenericJavaClassMapping protected void updateIncludedAttributes() { HashSet oldSuperclasses - = CollectionTools.set(this.includedAttributesContainers.keySet()); - Set oldAttributes = CollectionTools.set(getIncludedAttributes()); + = CollectionTools.hashSet(this.includedAttributesContainers.keySet()); + Set oldAttributes = CollectionTools.hashSet(getIncludedAttributes()); if (! isXmlTransient()) { JaxbClassMapping superclass = this.superclass; @@ -554,7 +554,7 @@ public class GenericJavaClassMapping this.includedAttributesContainers.remove(oldSuperclass); } - Set newAttributes = CollectionTools.set(getIncludedAttributes()); + Set newAttributes = CollectionTools.hashSet(getIncludedAttributes()); if (IterableTools.elementsAreDifferent(oldAttributes, newAttributes)) { fireCollectionChanged(INCLUDED_ATTRIBUTES_COLLECTION, newAttributes); } @@ -773,7 +773,7 @@ public class GenericJavaClassMapping // no nonexistent attributes (attributes mapped otherwise allowed) ... // *except* no transient attributes allowed - Bag props = CollectionTools.bag(getPropOrder()); + Bag props = CollectionTools.hashBag(getPropOrder()); Set allAttributes = new HashSet(); Set requiredAttributes = new HashSet(); Set transientAttributes = new HashSet(); diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaXmlNs.java b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaXmlNs.java index aa3b73291f..bfac5bb2c9 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaXmlNs.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.core/src/org/eclipse/jpt/jaxb/core/internal/context/java/GenericJavaXmlNs.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2013 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -133,7 +133,7 @@ public class GenericJavaXmlNs if (schema != null) { result = IterableTools.concatenate(result, schema.getNamespaceProposals()); } - return CollectionTools.set(result); + return CollectionTools.hashSet(result); } diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/ELJaxbContextRootImpl.java b/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/ELJaxbContextRootImpl.java index fb28815eab..7b48deec37 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/ELJaxbContextRootImpl.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/ELJaxbContextRootImpl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -204,7 +204,7 @@ public class ELJaxbContextRootImpl protected void updateOxmFiles() { Collection - unmatchedOxmResources = CollectionTools.collection(getJaxbProject().getOxmResources()); + unmatchedOxmResources = CollectionTools.hashBag(getJaxbProject().getOxmResources()); for (OxmFile oxmFile : getOxmFiles()) { JptXmlResource oxmResource = oxmFile.getOxmResource(); diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/java/ELJavaXmlJoinNode.java b/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/java/ELJavaXmlJoinNode.java index d78f11b5c2..13b36a84ee 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/java/ELJavaXmlJoinNode.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.eclipselink.core/src/org/eclipse/jpt/jaxb/eclipselink/core/internal/context/java/ELJavaXmlJoinNode.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2013 Oracle. All rights reserved. + * Copyright (c) 2012, 2015 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. @@ -159,7 +159,7 @@ public class ELJavaXmlJoinNode StringTools.JAVA_STRING_LITERAL_CONTENT_TRANSFORMER)); } - return CollectionTools.sortedSet(result); + return CollectionTools.treeSet(result); } return EmptyIterable.instance(); diff --git a/jaxb/plugins/org.eclipse.jpt.jaxb.ui/src/org/eclipse/jpt/jaxb/ui/internal/properties/JaxbSchemasPropertiesPage.java b/jaxb/plugins/org.eclipse.jpt.jaxb.ui/src/org/eclipse/jpt/jaxb/ui/internal/properties/JaxbSchemasPropertiesPage.java index e9c98045c6..8992ee6aef 100644 --- a/jaxb/plugins/org.eclipse.jpt.jaxb.ui/src/org/eclipse/jpt/jaxb/ui/internal/properties/JaxbSchemasPropertiesPage.java +++ b/jaxb/plugins/org.eclipse.jpt.jaxb.ui/src/org/eclipse/jpt/jaxb/ui/internal/properties/JaxbSchemasPropertiesPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2013 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -574,7 +574,7 @@ public class JaxbSchemasPropertiesPage @Override protected Collection getAspectValue() { - return CollectionTools.collection(iterator()); + return CollectionTools.hashBag(iterator()); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/AbstractJpaContextModel.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/AbstractJpaContextModel.java index 5260660fc9..4bdbb2261a 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/AbstractJpaContextModel.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/AbstractJpaContextModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -461,7 +461,7 @@ public abstract class AbstractJpaContextModel

*/ protected void sync(boolean sync) { @SuppressWarnings("unchecked") - HashSet contextElements = (HashSet) CollectionTools.set(this.elements.toArray()); + HashSet contextElements = (HashSet) CollectionTools.hashSet(this.elements.toArray()); ArrayList contextElementsToSync = new ArrayList(contextElements.size()); int resourceIndex = 0; diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/ContextContainerTools.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/ContextContainerTools.java index 747df14296..7604c53d18 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/ContextContainerTools.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/ContextContainerTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010 Oracle. All rights reserved. + * Copyright (c) 2010, 2015 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. @@ -94,7 +94,7 @@ public class ContextContainerTools { * updated (false). */ protected static void sync(Adapter adapter, boolean sync) { - HashSet contextElements = CollectionTools.set(adapter.getContextElements()); + HashSet contextElements = CollectionTools.hashSet(adapter.getContextElements()); ArrayList contextElementsToSync = new ArrayList(contextElements.size()); int resourceIndex = 0; diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/MappingTools.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/MappingTools.java index be06988900..ff0de464d5 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/MappingTools.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/MappingTools.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2013 Oracle. All rights reserved. + * Copyright (c) 2006, 2015 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. @@ -535,7 +535,7 @@ public final class MappingTools { * Returns the names of basic array types. */ public static Iterable getBasicArrayTypeNames() { - return ListTools.list(BASIC_ARRAY_TYPE_NAMES); + return ListTools.arrayList(BASIC_ARRAY_TYPE_NAMES); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaPersistentType.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaPersistentType.java index 9761487596..ee47c331c5 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaPersistentType.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaPersistentType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2013 Oracle. All rights reserved. + * Copyright (c) 2006, 2015 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. @@ -445,7 +445,7 @@ public abstract class AbstractJavaPersistentType private void intializePropertyAccessAttributes() { this.initializeFieldAttributes(JavaResourceAnnotatedElement.IS_ANNOTATED); - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -459,7 +459,7 @@ public abstract class AbstractJavaPersistentType } private void initializeAnnotatedPropertyAttributes() { - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -503,7 +503,7 @@ public abstract class AbstractJavaPersistentType * 2. all annotated methods(getters/setters) */ private void syncFieldAccessAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getAttributes()); this.syncFieldAttributes(contextAttributes, JavaResourceField.IS_RELEVANT_FOR_FIELD_ACCESS); this.syncAnnotatedPropertyAttributes(contextAttributes); @@ -516,11 +516,11 @@ public abstract class AbstractJavaPersistentType * 3. all annotated methods getters/setters that don't have a matching pair */ private void syncPropertyAccessAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getAttributes()); this.syncFieldAttributes(contextAttributes, JavaResourceAnnotatedElement.IS_ANNOTATED); - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -546,7 +546,7 @@ public abstract class AbstractJavaPersistentType } private void syncAnnotatedPropertyAttributes(HashSet contextAttributes) { - Collection resourceMethods = CollectionTools.collection(this.getResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaQuery.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaQuery.java index 8563422280..60d7de60a6 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaQuery.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/java/AbstractJavaQuery.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -199,8 +199,8 @@ public abstract class AbstractJavaQuery

hints1 = ListTools.list(this.getHints()); - ArrayList hints2 = ListTools.list(other.getHints()); + ArrayList hints1 = ListTools.arrayList(this.getHints()); + ArrayList hints2 = ListTools.arrayList(other.getHints()); if (hints1.size() != hints2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/AbstractOrmQuery.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/AbstractOrmQuery.java index 6c0cbb7e2b..99b1f545d7 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/AbstractOrmQuery.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/AbstractOrmQuery.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -219,8 +219,8 @@ public abstract class AbstractOrmQuery protected boolean hintsAreEquivalentTo(Query other) { // get fixed lists of the hints - ArrayList hints1 = ListTools.list(this.getHints()); - ArrayList hints2 = ListTools.list(other.getHints()); + ArrayList hints1 = ListTools.arrayList(this.getHints()); + ArrayList hints2 = ListTools.arrayList(other.getHints()); if (hints1.size() != hints2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/SpecifiedOrmPersistentType.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/SpecifiedOrmPersistentType.java index 363f4e14a6..ed3c32f4cb 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/SpecifiedOrmPersistentType.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/orm/SpecifiedOrmPersistentType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2013 Oracle. All rights reserved. + * Copyright (c) 2006, 2015 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. @@ -619,7 +619,7 @@ public abstract class SpecifiedOrmPersistentType * */ private void syncFieldAccessDefaultAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getDefaultAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getDefaultAttributes()); this.syncFieldDefaultAttributes(contextAttributes, this.buildResourceFieldIsRelevant()); if ( ! this.mapping.isMetadataComplete()) { @@ -640,13 +640,13 @@ public abstract class SpecifiedOrmPersistentType * */ private void syncPropertyAccessDefaultAttributes() { - HashSet contextAttributes = CollectionTools.set(this.getDefaultAttributes()); + HashSet contextAttributes = CollectionTools.hashSet(this.getDefaultAttributes()); if ( ! this.mapping.isMetadataComplete()) { this.syncFieldDefaultAttributes(contextAttributes, JavaResourceAnnotatedElement.IS_ANNOTATED); } - Collection resourceMethods = CollectionTools.collection(this.getJavaResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getJavaResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getJavaResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); @@ -688,7 +688,7 @@ public abstract class SpecifiedOrmPersistentType } private void syncAnnotatedPropertyDefaultAttributes(HashSet contextAttributes) { - Collection resourceMethods = CollectionTools.collection(this.getJavaResourceMethods()); + Collection resourceMethods = CollectionTools.hashBag(this.getJavaResourceMethods()); //iterate through all resource methods searching for persistable getters for (JavaResourceMethod getterMethod : this.getJavaResourcePropertyGetters()) { JavaResourceMethod setterMethod = JavaResourceMethod.SET_METHOD_TRANSFORMER.transform(getterMethod); diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/persistence/AbstractPersistenceUnit.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/persistence/AbstractPersistenceUnit.java index 714e21936f..bec46f3395 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/persistence/AbstractPersistenceUnit.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/context/persistence/AbstractPersistenceUnit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -1564,7 +1564,7 @@ public abstract class AbstractPersistenceUnit } public Iterable getUniqueGeneratorNames() { - return CollectionTools.set(this.getNonEmptyGeneratorNames(), this.getGeneratorsSize()); + return CollectionTools.hashSet(this.getNonEmptyGeneratorNames(), this.getGeneratorsSize()); } protected Iterable getNonEmptyGeneratorNames() { @@ -1584,7 +1584,7 @@ public abstract class AbstractPersistenceUnit * @see #buildQueries() */ protected Iterable buildGenerators() { - ArrayList result = ListTools.list(this.getMappingFileGenerators()); + ArrayList result = ListTools.arrayList(this.getMappingFileGenerators()); HashSet mappingFileGeneratorNames = this.convertToNames(result); HashMap> allJavaGenerators = this.mapByName(this.getAllJavaGenerators()); @@ -1664,7 +1664,7 @@ public abstract class AbstractPersistenceUnit * or multiple, non-overridden Java queries with the same name. */ protected Iterable buildQueries() { - ArrayList result = ListTools.list(this.getMappingFileQueries()); + ArrayList result = ListTools.arrayList(this.getMappingFileQueries()); HashSet mappingFileQueryNames = this.convertToNames(result); HashMap> allJavaQueries = this.mapByName(this.getAllJavaQueries()); @@ -1984,7 +1984,7 @@ public abstract class AbstractPersistenceUnit * type mappings (by full qualified class name). */ protected Iterable getActiveTypeMappings(){ - ArrayList result = ListTools.list(this.getMappingFileTypeMappings()); + ArrayList result = ListTools.arrayList(this.getMappingFileTypeMappings()); HashSet mappingFileClassNames = this.convertToClassNames(result); HashMap> javaTypeMappings = this.mapTypeMappingsByClassName(this.getJavaTypeMappings()); @@ -2047,7 +2047,7 @@ public abstract class AbstractPersistenceUnit SubMonitor sm = SubMonitor.convert(monitor, 4); // gather up all the annotated Java types and types listed in the mapping files - HashSet newClasses = CollectionTools.set(this.getJpaProject().getPotentialJavaSourceTypes()); + HashSet newClasses = CollectionTools.hashSet(this.getJpaProject().getPotentialJavaSourceTypes()); HashSet mappingFileTypeNames = this.getMappingFileTypeNames(); // calculate the class refs to be removed @@ -2245,7 +2245,7 @@ public abstract class AbstractPersistenceUnit protected ArrayList extractConvertibleJavaModels(Iterable allJavaModels, Iterable mappingFileModels) { ArrayList convertibleModels = new ArrayList(); - HashSet mappingFileModelNames = this.convertToNames(ListTools.list(mappingFileModels)); + HashSet mappingFileModelNames = this.convertToNames(ListTools.arrayList(mappingFileModels)); HashMap> allJavaModelsByName = this.mapByName(allJavaModels); for (Map.Entry> entry : allJavaModelsByName.entrySet()) { String javaModelName = entry.getKey(); @@ -2300,7 +2300,7 @@ public abstract class AbstractPersistenceUnit } protected void checkForMultiplePersistenceUnitMetadata(List messages) { - ArrayList pumdMappingFileRefs = ListTools.list(this.getPersistenceUnitMetadataMappingFileRefs()); + ArrayList pumdMappingFileRefs = ListTools.arrayList(this.getPersistenceUnitMetadataMappingFileRefs()); if (pumdMappingFileRefs.size() > 1) { for (MappingFileRef mappingFileRef : pumdMappingFileRefs) { messages.add( diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/facet/JpaFacetDataModelProvider.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/facet/JpaFacetDataModelProvider.java index 03788c2111..4c71c2c47b 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/facet/JpaFacetDataModelProvider.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/facet/JpaFacetDataModelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -481,7 +481,7 @@ public abstract class JpaFacetDataModelProvider * put a null entry at the top of the list (for ) */ protected List buildValidConnectionNames() { - List connectionNames = ListTools.sort(ListTools.list(this.getConnectionProfileNames())); + List connectionNames = ListTools.sort(ListTools.arrayList(this.getConnectionProfileNames())); connectionNames.add(0, null); return connectionNames; } @@ -518,7 +518,7 @@ public abstract class JpaFacetDataModelProvider * put an entry for the default at the top of the list */ protected List buildValidStrings(Iterable strings, String defaultString) { - List validStrings = ListTools.list(strings); + List validStrings = ListTools.arrayList(strings); if ((defaultString != null) && ! validStrings.contains(defaultString)) { validStrings.add(0, defaultString); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/GenericContextRoot.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/GenericContextRoot.java index c681173e15..26a6320d0e 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/GenericContextRoot.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/GenericContextRoot.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -277,7 +277,7 @@ public class GenericContextRoot } PersistenceUnit persistenceUnit = persistence.getPersistenceUnits().iterator().next(); - HashBag annotatedTypes = CollectionTools.bag(this.jpaProject.getAnnotatedJavaSourceTypes()); + HashBag annotatedTypes = CollectionTools.hashBag(this.jpaProject.getAnnotatedJavaSourceTypes()); HashBag orphans = annotatedTypes.clone(); for (JavaResourceAbstractType jrat : annotatedTypes) { if (persistenceUnit.specifiesManagedType(jrat.getTypeBinding().getQualifiedName())) { diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/java/GenericJavaTableGenerator.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/java/GenericJavaTableGenerator.java index 2ffa72ec05..9a6051b4c2 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/java/GenericJavaTableGenerator.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/java/GenericJavaTableGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -567,8 +567,8 @@ public class GenericJavaTableGenerator protected boolean uniqueConstraintsAreEquivalentTo(TableGenerator generator) { // get fixed lists of the unique constraints - ArrayList uniqueConstraints1 = ListTools.list(this.getUniqueConstraints()); - ArrayList uniqueConstraints2 = ListTools.list(generator.getUniqueConstraints()); + ArrayList uniqueConstraints1 = ListTools.arrayList(this.getUniqueConstraints()); + ArrayList uniqueConstraints2 = ListTools.arrayList(generator.getUniqueConstraints()); if (uniqueConstraints1.size() != uniqueConstraints2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/orm/GenericOrmTableGenerator.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/orm/GenericOrmTableGenerator.java index 4c02e68e4f..a6820eff0b 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/orm/GenericOrmTableGenerator.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa1/context/orm/GenericOrmTableGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -441,8 +441,8 @@ public class GenericOrmTableGenerator protected boolean uniqueConstraintsAreEquivalentTo(TableGenerator generator) { // get fixed lists of the unique constraints - ArrayList uniqueConstraints1 = ListTools.list(this.getUniqueConstraints()); - ArrayList uniqueConstraints2 = ListTools.list(generator.getUniqueConstraints()); + ArrayList uniqueConstraints1 = ListTools.arrayList(this.getUniqueConstraints()); + ArrayList uniqueConstraints2 = ListTools.arrayList(generator.getUniqueConstraints()); if (uniqueConstraints1.size() != uniqueConstraints2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2/GenericMetamodelSynchronizer2_0.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2/GenericMetamodelSynchronizer2_0.java index 456e7da096..d65e767cbe 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2/GenericMetamodelSynchronizer2_0.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2/GenericMetamodelSynchronizer2_0.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2013 Oracle. All rights reserved. + * Copyright (c) 2009, 2015 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. @@ -24,7 +24,7 @@ import org.eclipse.jpt.common.core.resource.java.JavaResourceAbstractType; import org.eclipse.jpt.common.core.utility.BodySourceWriter; import org.eclipse.jpt.common.utility.internal.ClassNameTools; import org.eclipse.jpt.common.utility.internal.ObjectTools; -import org.eclipse.jpt.common.utility.internal.collection.LinkedStack; +import org.eclipse.jpt.common.utility.internal.stack.LinkedStack; import org.eclipse.jpt.common.utility.io.IndentingPrintWriter; import org.eclipse.jpt.jpa.core.context.AttributeMapping; import org.eclipse.jpt.jpa.core.context.PersistentType; diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/java/GenericJavaNamedStoredProcedureQuery2_1.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/java/GenericJavaNamedStoredProcedureQuery2_1.java index 09b9bc86e0..6d4fc0f8ba 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/java/GenericJavaNamedStoredProcedureQuery2_1.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/java/GenericJavaNamedStoredProcedureQuery2_1.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Oracle. All rights reserved. + * Copyright (c) 2013, 2015 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. @@ -296,8 +296,8 @@ public class GenericJavaNamedStoredProcedureQuery2_1 protected boolean parametersAreEquivalentTo(NamedStoredProcedureQuery2_1 other) { // get fixed lists of the stored procedure parameters - ArrayList parameter1 = ListTools.list(this.getParameters()); - ArrayList parameter2 = ListTools.list(other.getParameters()); + ArrayList parameter1 = ListTools.arrayList(this.getParameters()); + ArrayList parameter2 = ListTools.arrayList(other.getParameters()); if (parameter1.size() != parameter2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/orm/GenericOrmNamedStoredProcedureQuery2_1.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/orm/GenericOrmNamedStoredProcedureQuery2_1.java index 69866642c8..ff89d27beb 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/orm/GenericOrmNamedStoredProcedureQuery2_1.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/internal/jpa2_1/context/orm/GenericOrmNamedStoredProcedureQuery2_1.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Oracle. All rights reserved. + * Copyright (c) 2013, 2015 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. @@ -309,8 +309,8 @@ public class GenericOrmNamedStoredProcedureQuery2_1 protected boolean parametersAreEquivalentTo(NamedStoredProcedureQuery2_1 other) { // get fixed lists of the stored procedure parameters - ArrayList parameter1 = ListTools.list(this.getParameters()); - ArrayList parameter2 = ListTools.list(other.getParameters()); + ArrayList parameter1 = ListTools.arrayList(this.getParameters()); + ArrayList parameter2 = ListTools.arrayList(other.getParameters()); if (parameter1.size() != parameter2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/jpql/spi/JpaMapping.java b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/jpql/spi/JpaMapping.java index 12d2009d4f..10f6043b43 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/jpql/spi/JpaMapping.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.core/src/org/eclipse/jpt/jpa/core/jpql/spi/JpaMapping.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 Oracle. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. @@ -103,7 +103,7 @@ public abstract class JpaMapping implements IMapping { protected ITypeDeclaration[] buildGenericTypeDeclarations() { JavaSpecifiedPersistentAttribute javaPersistentAttribute = mapping.getPersistentAttribute().getJavaPersistentAttribute(); JavaResourceAttribute resource = javaPersistentAttribute == null ? null : javaPersistentAttribute.getResourceAttribute(); - List declarations = ListTools.list(buildGenericTypeDeclarations(resource)); + List declarations = ListTools.arrayList(buildGenericTypeDeclarations(resource)); return declarations.toArray(new ITypeDeclaration[declarations.size()]); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/context/persistence/EclipseLinkPersistenceUnit.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/context/persistence/EclipseLinkPersistenceUnit.java index 66c734d2bc..902a23f655 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/context/persistence/EclipseLinkPersistenceUnit.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/context/persistence/EclipseLinkPersistenceUnit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -440,7 +440,7 @@ public class EclipseLinkPersistenceUnit * unit's scope, with duplicates removed. */ public Iterable getUniqueConverterNames() { - return CollectionTools.set(this.getNonEmptyConverterNames(), this.getConvertersSize()); + return CollectionTools.hashSet(this.getNonEmptyConverterNames(), this.getConvertersSize()); } protected Iterable getNonEmptyConverterNames() { @@ -460,7 +460,7 @@ public class EclipseLinkPersistenceUnit * @see #buildQueries() */ protected Iterable buildConverters() { - ArrayList result = ListTools.list(this.getMappingFileConverters()); + ArrayList result = ListTools.arrayList(this.getMappingFileConverters()); HashSet mappingFileConverterNames = this.convertToNames(result); HashMap> javaConverters = this.mapByName(this.getAllJavaConverters()); @@ -1370,7 +1370,7 @@ public class EclipseLinkPersistenceUnit protected HashMap> extractEclipseLinkConvertibleJavaModels(Iterable allJavaModels, Iterable mappingFileModels, EquivalencyAdapter adapter) { HashMap> convertibleModels = new HashMap>(); - HashSet mappingFileModelNames = this.convertToNames(ListTools.list(mappingFileModels)); + HashSet mappingFileModelNames = this.convertToNames(ListTools.arrayList(mappingFileModels)); HashMap> allJavaModelsByName = this.mapByName(allJavaModels); for (Map.Entry> entry : allJavaModelsByName.entrySet()) { String javaModelName = entry.getKey(); diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/java/EclipseLinkJavaObjectTypeConverter.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/java/EclipseLinkJavaObjectTypeConverter.java index 5916887d72..ac65fd2c67 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/java/EclipseLinkJavaObjectTypeConverter.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/java/EclipseLinkJavaObjectTypeConverter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -299,8 +299,8 @@ public class EclipseLinkJavaObjectTypeConverter protected boolean conversionValuesAreEquivalentTo(EclipseLinkObjectTypeConverter converter) { // get fixed lists of the conversion values - ArrayList conversionValues1 = ListTools.list(this.getConversionValues()); - ArrayList conversionValues2 = ListTools.list(converter.getConversionValues()); + ArrayList conversionValues1 = ListTools.arrayList(this.getConversionValues()); + ArrayList conversionValues2 = ListTools.arrayList(converter.getConversionValues()); if (conversionValues1.size() != conversionValues2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/orm/EclipseLinkOrmObjectTypeConverter.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/orm/EclipseLinkOrmObjectTypeConverter.java index e4c0714a17..8dc5144393 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/orm/EclipseLinkOrmObjectTypeConverter.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/orm/EclipseLinkOrmObjectTypeConverter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -431,8 +431,8 @@ public class EclipseLinkOrmObjectTypeConverter protected boolean conversionValuesAreEquivalentTo(EclipseLinkObjectTypeConverter converter) { // get fixed lists of the conversion values - ArrayList conversionValues1 = ListTools.list(this.getConversionValues()); - ArrayList conversionValues2 = ListTools.list(converter.getConversionValues()); + ArrayList conversionValues1 = ListTools.arrayList(this.getConversionValues()); + ArrayList conversionValues2 = ListTools.arrayList(converter.getConversionValues()); if (conversionValues1.size() != conversionValues2.size()) { return false; } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkCustomization.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkCustomization.java index 8cd1d0c61b..a77196bbf6 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkCustomization.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkCustomization.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -96,7 +96,7 @@ public class EclipseLinkCustomization } private List buildSessionCustomizers() { - return ListTools.list(this.convertToValues(this.getPropertiesSetWithPrefix(ECLIPSELINK_SESSION_CUSTOMIZER))); + return ListTools.arrayList(this.convertToValues(this.getPropertiesSetWithPrefix(ECLIPSELINK_SESSION_CUSTOMIZER))); } private Iterable convertToValues(Iterable properties) { diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkPersistenceUnitProperties.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkPersistenceUnitProperties.java index 97e57fbff9..dbd316c749 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkPersistenceUnitProperties.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.core/src/org/eclipse/jpt/jpa/eclipselink/core/internal/context/persistence/EclipseLinkPersistenceUnitProperties.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2011 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -30,7 +30,7 @@ public abstract class EclipseLinkPersistenceUnitProperties extends AbstractPersi // ******** Convenience methods ******** protected Set getPropertiesSetWithPrefix(String keyPrefix) { - return CollectionTools.set(this.getPersistenceUnit().getPropertiesWithNamePrefix(keyPrefix)); + return CollectionTools.hashSet(this.getPersistenceUnit().getPropertiesWithNamePrefix(keyPrefix)); } /** diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/details/EclipseLinkConversionValueDialog.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/details/EclipseLinkConversionValueDialog.java index 32e3082d66..320f425219 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/details/EclipseLinkConversionValueDialog.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/details/EclipseLinkConversionValueDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2012 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -68,7 +68,7 @@ public class EclipseLinkConversionValueDialog protected EclipseLinkConversionValueStateObject buildStateObject() { String dataValue = null; String objectValue = null; - Set dataValues = CollectionTools.set(this.objectTypeConverter.getDataValues(), this.objectTypeConverter.getDataValuesSize()); + Set dataValues = CollectionTools.hashSet(this.objectTypeConverter.getDataValues(), this.objectTypeConverter.getDataValuesSize()); if (isEditDialog()) { dataValue = this.conversionValue.getDataValue(); objectValue = this.conversionValue.getObjectValue(); diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/customization/EclipseLinkProfilerClassChooser.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/customization/EclipseLinkProfilerClassChooser.java index 6cf5bfdf57..a790902646 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/customization/EclipseLinkProfilerClassChooser.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/customization/EclipseLinkProfilerClassChooser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -169,7 +169,7 @@ public class EclipseLinkProfilerClassChooser private CollectionValueModel buildProfilersCollectionHolder() { return new SimpleCollectionValueModel( - CollectionTools.collection(this.buildProfilers()) + CollectionTools.hashBag(this.buildProfilers()) ); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkLoggerClassChooser.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkLoggerClassChooser.java index c793e897c6..376679fe39 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkLoggerClassChooser.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkLoggerClassChooser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -175,7 +175,7 @@ public class EclipseLinkLoggerClassChooser private CollectionValueModel buildLoggersCollectionHolder() { return new SimpleCollectionValueModel( - CollectionTools.collection(this.buildLoggers()) + CollectionTools.hashBag(this.buildLoggers()) ); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkPersistenceUnitOptionsEditorPage.java b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkPersistenceUnitOptionsEditorPage.java index 1aea403371..db073d071d 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkPersistenceUnitOptionsEditorPage.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.eclipselink.ui/src/org/eclipse/jpt/jpa/eclipselink/ui/internal/persistence/options/EclipseLinkPersistenceUnitOptionsEditorPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -505,7 +505,7 @@ public class EclipseLinkPersistenceUnitOptionsEditorPage private CollectionValueModel buildTargetDatabasesCollectionHolder() { return new SimpleCollectionValueModel( - CollectionTools.collection(buildTargetDatabases()) + CollectionTools.hashBag(buildTargetDatabases()) ); } @@ -637,7 +637,7 @@ public class EclipseLinkPersistenceUnitOptionsEditorPage private CollectionValueModel buildTargetServersCollectionHolder() { return new SimpleCollectionValueModel( - CollectionTools.collection(buildTargetServers()) + CollectionTools.hashBag(buildTargetServers()) ); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaJavaCompletionProposalComputer.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaJavaCompletionProposalComputer.java index ad8a244952..e0fb3020e9 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaJavaCompletionProposalComputer.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaJavaCompletionProposalComputer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -110,7 +110,7 @@ public class JpaJavaCompletionProposalComputer return Collections.emptyList(); } - Collection rootStructureNodes = CollectionTools.collection(jpaFile.getRootStructureNodes()); + Collection rootStructureNodes = CollectionTools.hashBag(jpaFile.getRootStructureNodes()); if (rootStructureNodes.isEmpty()) { return Collections.emptyList(); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaXmlCompletionProposalComputer.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaXmlCompletionProposalComputer.java index f228193646..fa9e632c86 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaXmlCompletionProposalComputer.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/JpaXmlCompletionProposalComputer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 Oracle. All rights reserved. + * Copyright (c) 2012, 2015 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. @@ -224,7 +224,7 @@ public class JpaXmlCompletionProposalComputer extends DefaultJpaXmlCompletionPro JpaFile jpaFile = (JpaFile) file.getAdapter(JpaFile.class); if (jpaFile == null) return Collections.emptyList(); - Collection rootStructureNodes = CollectionTools.collection(jpaFile.getRootStructureNodes()); + Collection rootStructureNodes = CollectionTools.hashBag(jpaFile.getRootStructureNodes()); if (rootStructureNodes.isEmpty()) { return Collections.emptyList(); } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/BaseJoinColumnStateObject.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/BaseJoinColumnStateObject.java index fee1d0c969..657993f27f 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/BaseJoinColumnStateObject.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/BaseJoinColumnStateObject.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -120,7 +120,7 @@ public abstract class BaseJoinColumnStateObject if (table == null) { return EmptyListIterator.instance(); } - return ListTools.list(table.getSortedColumnIdentifiers()).listIterator(); + return ListTools.arrayList(table.getSortedColumnIdentifiers()).listIterator(); } private static int columnsSize(Table table) { @@ -340,8 +340,8 @@ public abstract class BaseJoinColumnStateObject } public void setTable(String table) { - ArrayList oldNames = ListTools.list(this.names()); - ArrayList oldRefColNames = ListTools.list(this.referenceColumnNames()); + ArrayList oldNames = ListTools.arrayList(this.names()); + ArrayList oldRefColNames = ListTools.arrayList(this.referenceColumnNames()); String oldTable = this.table; this.table = table; this.firePropertyChanged(TABLE_PROPERTY, oldTable, table); diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/JoinColumnInJoiningStrategyStateObject.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/JoinColumnInJoiningStrategyStateObject.java index ce6c714ddb..54618cbe6d 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/JoinColumnInJoiningStrategyStateObject.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/JoinColumnInJoiningStrategyStateObject.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2010 Oracle. All rights reserved. + * Copyright (c) 2008, 2015 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. @@ -56,7 +56,7 @@ public class JoinColumnInJoiningStrategyStateObject @Override public ListIterator tables() { Schema schema = getDbSchema(); - return schema == null ? super.tables() : ListTools.list(schema.getSortedTableIdentifiers()).listIterator(); + return schema == null ? super.tables() : ListTools.arrayList(schema.getSortedTableIdentifiers()).listIterator(); } protected Schema getDbSchema() { diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/TemporalTypeCombo.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/TemporalTypeCombo.java index 2708942b5f..f96cd0e87d 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/TemporalTypeCombo.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/details/TemporalTypeCombo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2013 Oracle. All rights reserved. + * Copyright (c) 2006, 2015 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. @@ -90,7 +90,7 @@ public class TemporalTypeCombo extends Pane { } private List buildSortedTemporalTypeList() { - return ListTools.sort(ListTools.list(TemporalType.values()), this.buildTemporalTypeComparator()); + return ListTools.sort(ListTools.arrayList(TemporalType.values()), this.buildTemporalTypeComparator()); } private Comparator buildTemporalTypeComparator() { diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/properties/JpaProjectPropertiesPage.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/properties/JpaProjectPropertiesPage.java index 543daa5b8b..ae844d24df 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/properties/JpaProjectPropertiesPage.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/properties/JpaProjectPropertiesPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -1137,7 +1137,7 @@ public class JpaProjectPropertiesPage } void collectionChanged() { - this.fireCollectionChanged(CollectionValueModel.VALUES, CollectionTools.collection(this.iterator())); + this.fireCollectionChanged(CollectionValueModel.VALUES, CollectionTools.hashBag(this.iterator())); } public Iterator iterator() { @@ -1377,7 +1377,7 @@ public class JpaProjectPropertiesPage private void processJavaProjectDelta(IJavaElementDelta delta) { IJavaProject javaProject = (IJavaProject) delta.getElement(); if (javaProject.equals(this.subject.getJavaProject()) && this.classpathHasChanged(delta)) { - this.fireCollectionChanged(CollectionValueModel.VALUES, CollectionTools.collection(this.iterator())); + this.fireCollectionChanged(CollectionValueModel.VALUES, CollectionTools.hashBag(this.iterator())); } } diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/DatabaseGroup.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/DatabaseGroup.java index 42865003af..470f50db38 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/DatabaseGroup.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/DatabaseGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -210,7 +210,7 @@ public class DatabaseGroup } private SortedSet buildSortedConnectionProfileNames() { - return CollectionTools.sortedSet(this.getConnectionProfileNames()); + return CollectionTools.treeSet(this.getConnectionProfileNames()); } private Iterable getConnectionProfileNames() { diff --git a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/TablesSelectorWizardPage.java b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/TablesSelectorWizardPage.java index 68411e8ffa..ced357776d 100644 --- a/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/TablesSelectorWizardPage.java +++ b/jpa/plugins/org.eclipse.jpt.jpa.ui/src/org/eclipse/jpt/jpa/ui/internal/wizards/gen/TablesSelectorWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -278,7 +278,7 @@ public class TablesSelectorWizardPage extends WizardPage { if(this.fetchTablesJobIsRunning()) { return Collections. emptyList(); } - return CollectionTools.collection(schema.getTables()); + return CollectionTools.hashBag(schema.getTables()); } private Collection
possibleTables() { @@ -636,7 +636,7 @@ public class TablesSelectorWizardPage extends WizardPage { schema.getName())); subMonitor.worked(20); - tables.addAll(CollectionTools.collection(schema.getTables())); + tables.addAll(CollectionTools.hashBag(schema.getTables())); subMonitor.worked(95); } diff --git a/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/java/JavaAttributeOverrideTests.java b/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/java/JavaAttributeOverrideTests.java index 7fa854a6d6..f0d98e76dd 100644 --- a/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/java/JavaAttributeOverrideTests.java +++ b/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/java/JavaAttributeOverrideTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -180,7 +180,7 @@ public class JavaAttributeOverrideTests extends ContextModelTestCase assertEquals("id", attributeOverride.getColumn().getDefaultName()); - JavaPersistentType mappedSuperclass = ListTools.list(getPersistenceUnit().getSpecifiedClassRefs()).get(1).getJavaPersistentType(); + JavaPersistentType mappedSuperclass = ListTools.arrayList(getPersistenceUnit().getSpecifiedClassRefs()).get(1).getJavaPersistentType(); BasicMapping basicMapping = (BasicMapping) mappedSuperclass.getAttributeNamed("id").getMapping(); basicMapping.getColumn().setSpecifiedName("FOO"); @@ -203,7 +203,7 @@ public class JavaAttributeOverrideTests extends ContextModelTestCase assertEquals("AnnotationTestTypeChild", attributeOverride.getColumn().getDefaultTableName()); - JavaPersistentType mappedSuperclass = ListTools.list(getPersistenceUnit().getSpecifiedClassRefs()).get(1).getJavaPersistentType(); + JavaPersistentType mappedSuperclass = ListTools.arrayList(getPersistenceUnit().getSpecifiedClassRefs()).get(1).getJavaPersistentType(); BasicMapping basicMapping = (BasicMapping) mappedSuperclass.getAttributeNamed("id").getMapping(); basicMapping.getColumn().setSpecifiedTableName("BAR"); diff --git a/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/orm/OrmSecondaryTableTests.java b/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/orm/OrmSecondaryTableTests.java index 962bb1033f..d761800fdc 100644 --- a/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/orm/OrmSecondaryTableTests.java +++ b/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/context/orm/OrmSecondaryTableTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Oracle. All rights reserved. + * Copyright (c) 2007, 2015 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. @@ -750,7 +750,7 @@ public class OrmSecondaryTableTests extends ContextModelTestCase javaSecondaryTable.addUniqueConstraint().addColumnName("BAR"); javaSecondaryTable.addUniqueConstraint().addColumnName("BAZ"); - List uniqueConstraints = ListTools.list(ormSecondaryTable.getUniqueConstraints()); + List uniqueConstraints = ListTools.arrayList(ormSecondaryTable.getUniqueConstraints()); assertEquals(3, uniqueConstraints.size()); assertEquals("FOO", uniqueConstraints.get(0).getColumnName(0)); assertEquals("BAR", uniqueConstraints.get(1).getColumnName(0)); diff --git a/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/jpa2/context/persistence/Generic2_0JpaMetadataConversionTests.java b/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/jpa2/context/persistence/Generic2_0JpaMetadataConversionTests.java index 61677e3eff..7f880fd7dd 100644 --- a/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/jpa2/context/persistence/Generic2_0JpaMetadataConversionTests.java +++ b/jpa/tests/org.eclipse.jpt.jpa.core.tests/src/org/eclipse/jpt/jpa/core/tests/internal/jpa2/context/persistence/Generic2_0JpaMetadataConversionTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -244,7 +244,7 @@ public class Generic2_0JpaMetadataConversionTests extends assertEquals(0, entity.getQueryContainer().getNamedNativeQueriesSize()); // test the mapping file queries have correct values - Collection namedNativeQueries = CollectionTools.collection(entityMappings.getQueryContainer().getNamedNativeQueries()); + Collection namedNativeQueries = CollectionTools.hashBag(entityMappings.getQueryContainer().getNamedNativeQueries()); // test the first mapping file query OrmNamedNativeQuery nnq1 = selectModelNamed(namedNativeQueries, "nnq1"); @@ -407,7 +407,7 @@ public class Generic2_0JpaMetadataConversionTests extends assertEquals(0, mappedSuperclass.getQueryContainer().getNamedNativeQueriesSize()); // test the mapping file queries have correct values - Collection namedNativeQueries = CollectionTools.collection(entityMappings.getQueryContainer().getNamedNativeQueries()); + Collection namedNativeQueries = CollectionTools.hashBag(entityMappings.getQueryContainer().getNamedNativeQueries()); // test the first mapping file query OrmNamedNativeQuery nnq1 = selectModelNamed(namedNativeQueries, "nnq1"); diff --git a/jpa/tests/org.eclipse.jpt.jpa.eclipselink.core.tests/src/org/eclipse/jpt/jpa/eclipselink/core/tests/internal/context/persistence/EclipseLink2_2JpaMetadataConversionTests.java b/jpa/tests/org.eclipse.jpt.jpa.eclipselink.core.tests/src/org/eclipse/jpt/jpa/eclipselink/core/tests/internal/context/persistence/EclipseLink2_2JpaMetadataConversionTests.java index 1237aedf73..c810a9e8a0 100644 --- a/jpa/tests/org.eclipse.jpt.jpa.eclipselink.core.tests/src/org/eclipse/jpt/jpa/eclipselink/core/tests/internal/context/persistence/EclipseLink2_2JpaMetadataConversionTests.java +++ b/jpa/tests/org.eclipse.jpt.jpa.eclipselink.core.tests/src/org/eclipse/jpt/jpa/eclipselink/core/tests/internal/context/persistence/EclipseLink2_2JpaMetadataConversionTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 Oracle. All rights reserved. + * Copyright (c) 2011, 2015 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. @@ -449,7 +449,7 @@ public class EclipseLink2_2JpaMetadataConversionTests extends EclipseLink2_2Cont assertEquals(mapping.getConverterContainer().getConvertersSize(), 0); // test the mapping file converter have correct values - Collection customConverters = CollectionTools.collection(entityMappings.getConverterContainer().getCustomConverters()); + Collection customConverters = CollectionTools.hashBag(entityMappings.getConverterContainer().getCustomConverters()); EclipseLinkCustomConverter custom1 = Generic2_0JpaMetadataConversionTests.selectModelNamed(customConverters, "custom1"); assertEquals("custom1", custom1.getName()); assertEquals("foo1", custom1.getConverterClass()); -- cgit v1.2.3