diff options
author | Artur Signell <artur.signell@itmill.com> | 2012-01-27 14:08:53 +0000 |
---|---|---|
committer | Artur Signell <artur.signell@itmill.com> | 2012-01-27 14:08:53 +0000 |
commit | c2722bfeb2552158c9717110b35518a07e13ab85 (patch) | |
tree | b32ead2ac3b8ab68027e12e9bf97394cbad906f1 /tests/server-side/com/vaadin/data/util | |
parent | b1ae3cd70e2ca4656bb28f77ca79fe0efd29dd67 (diff) | |
download | vaadin-framework-c2722bfeb2552158c9717110b35518a07e13ab85.tar.gz vaadin-framework-c2722bfeb2552158c9717110b35518a07e13ab85.zip |
#8311 Converted CRLF to LF in all source files
svn changeset:22797/svn branch:6.7
Diffstat (limited to 'tests/server-side/com/vaadin/data/util')
10 files changed, 4270 insertions, 4270 deletions
diff --git a/tests/server-side/com/vaadin/data/util/AbstractContainerTest.java b/tests/server-side/com/vaadin/data/util/AbstractContainerTest.java index 8f6fb0ab8a..6cbe675fa1 100644 --- a/tests/server-side/com/vaadin/data/util/AbstractContainerTest.java +++ b/tests/server-side/com/vaadin/data/util/AbstractContainerTest.java @@ -1,670 +1,670 @@ -package com.vaadin.data.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import com.vaadin.data.Container;
-import com.vaadin.data.Container.Filterable;
-import com.vaadin.data.Container.ItemSetChangeEvent;
-import com.vaadin.data.Container.ItemSetChangeListener;
-import com.vaadin.data.Container.Sortable;
-import com.vaadin.data.Item;
-import com.vaadin.data.util.filter.SimpleStringFilter;
-
-public abstract class AbstractContainerTest extends TestCase {
-
- /**
- * Helper class for testing e.g. listeners expecting events to be fired.
- */
- protected abstract static class AbstractEventCounter {
- private int eventCount = 0;
- private int lastAssertedEventCount = 0;
-
- /**
- * Increment the event count. To be called by subclasses e.g. from a
- * listener method.
- */
- protected void increment() {
- ++eventCount;
- }
-
- /**
- * Check that no one event has occurred since the previous assert call.
- */
- public void assertNone() {
- Assert.assertEquals(lastAssertedEventCount, eventCount);
- }
-
- /**
- * Check that exactly one event has occurred since the previous assert
- * call.
- */
- public void assertOnce() {
- Assert.assertEquals(++lastAssertedEventCount, eventCount);
- }
-
- /**
- * Reset the counter and the expected count.
- */
- public void reset() {
- eventCount = 0;
- lastAssertedEventCount = 0;
- }
- }
-
- /**
- * Test class for counting item set change events and verifying they have
- * been received.
- */
- protected static class ItemSetChangeCounter extends AbstractEventCounter
- implements ItemSetChangeListener {
-
- public void containerItemSetChange(ItemSetChangeEvent event) {
- increment();
- }
-
- }
-
- // #6043: for items that have been filtered out, Container interface does
- // not specify what to return from getItem() and getContainerProperty(), so
- // need checkGetItemNull parameter for the test to be usable for most
- // current containers
- protected void validateContainer(Container container,
- Object expectedFirstItemId, Object expectedLastItemId,
- Object itemIdInSet, Object itemIdNotInSet,
- boolean checkGetItemNull, int expectedSize) {
- Container.Indexed indexed = null;
- if (container instanceof Container.Indexed) {
- indexed = (Container.Indexed) container;
- }
-
- List<Object> itemIdList = new ArrayList<Object>(container.getItemIds());
-
- // size()
- assertEquals(expectedSize, container.size());
- assertEquals(expectedSize, itemIdList.size());
-
- // first item, last item
- Object first = itemIdList.get(0);
- Object last = itemIdList.get(itemIdList.size() - 1);
-
- assertEquals(expectedFirstItemId, first);
- assertEquals(expectedLastItemId, last);
-
- // containsId
- assertFalse(container.containsId(itemIdNotInSet));
- assertTrue(container.containsId(itemIdInSet));
-
- // getItem
- if (checkGetItemNull) {
- assertNull(container.getItem(itemIdNotInSet));
- }
- assertNotNull(container.getItem(itemIdInSet));
-
- // getContainerProperty
- for (Object propId : container.getContainerPropertyIds()) {
- if (checkGetItemNull) {
- assertNull(container.getContainerProperty(itemIdNotInSet,
- propId));
- }
- assertNotNull(container.getContainerProperty(itemIdInSet, propId));
- }
-
- if (indexed != null) {
- // firstItemId
- assertEquals(first, indexed.firstItemId());
-
- // lastItemId
- assertEquals(last, indexed.lastItemId());
-
- // nextItemId
- assertEquals(itemIdList.get(1), indexed.nextItemId(first));
-
- // prevItemId
- assertEquals(itemIdList.get(itemIdList.size() - 2),
- indexed.prevItemId(last));
-
- // isFirstId
- assertTrue(indexed.isFirstId(first));
- assertFalse(indexed.isFirstId(last));
-
- // isLastId
- assertTrue(indexed.isLastId(last));
- assertFalse(indexed.isLastId(first));
-
- // indexOfId
- assertEquals(0, indexed.indexOfId(first));
- assertEquals(expectedSize - 1, indexed.indexOfId(last));
-
- // getIdByIndex
- assertEquals(indexed.getIdByIndex(0), first);
- assertEquals(indexed.getIdByIndex(expectedSize - 1), last);
-
- }
-
- }
-
- protected static final Object FULLY_QUALIFIED_NAME = "fullyQualifiedName";
- protected static final Object SIMPLE_NAME = "simpleName";
- protected static final Object REVERSE_FULLY_QUALIFIED_NAME = "reverseFullyQualifiedName";
- protected static final Object ID_NUMBER = "idNumber";
-
- protected void testBasicContainerOperations(Container container) {
- initializeContainer(container);
-
- // Basic container
- validateContainer(container, sampleData[0],
- sampleData[sampleData.length - 1], sampleData[10], "abc", true,
- sampleData.length);
- }
-
- protected void testContainerOrdered(Container.Ordered container) {
- Object id = container.addItem();
- assertNotNull(id);
- Item item = container.getItem(id);
- assertNotNull(item);
-
- assertEquals(id, container.firstItemId());
- assertEquals(id, container.lastItemId());
-
- // isFirstId
- assertTrue(container.isFirstId(id));
- assertTrue(container.isFirstId(container.firstItemId()));
- // isLastId
- assertTrue(container.isLastId(id));
- assertTrue(container.isLastId(container.lastItemId()));
-
- // Add a new item before the first
- // addItemAfter
- Object newFirstId = container.addItemAfter(null);
- assertNotNull(newFirstId);
- assertNotNull(container.getItem(newFirstId));
-
- // isFirstId
- assertTrue(container.isFirstId(newFirstId));
- assertTrue(container.isFirstId(container.firstItemId()));
- // isLastId
- assertTrue(container.isLastId(id));
- assertTrue(container.isLastId(container.lastItemId()));
-
- // nextItemId
- assertEquals(id, container.nextItemId(newFirstId));
- assertNull(container.nextItemId(id));
- assertNull(container.nextItemId("not-in-container"));
-
- // prevItemId
- assertEquals(newFirstId, container.prevItemId(id));
- assertNull(container.prevItemId(newFirstId));
- assertNull(container.prevItemId("not-in-container"));
-
- // addItemAfter(Object)
- Object newSecondItemId = container.addItemAfter(newFirstId);
- // order is now: newFirstId, newSecondItemId, id
- assertNotNull(newSecondItemId);
- assertNotNull(container.getItem(newSecondItemId));
- assertEquals(id, container.nextItemId(newSecondItemId));
- assertEquals(newFirstId, container.prevItemId(newSecondItemId));
-
- // addItemAfter(Object,Object)
- String fourthId = "id of the fourth item";
- Item fourth = container.addItemAfter(newFirstId, fourthId);
- // order is now: newFirstId, fourthId, newSecondItemId, id
- assertNotNull(fourth);
- assertEquals(fourth, container.getItem(fourthId));
- assertEquals(newSecondItemId, container.nextItemId(fourthId));
- assertEquals(newFirstId, container.prevItemId(fourthId));
-
- // addItemAfter(Object,Object)
- Object fifthId = new Object();
- Item fifth = container.addItemAfter(null, fifthId);
- // order is now: fifthId, newFirstId, fourthId, newSecondItemId, id
- assertNotNull(fifth);
- assertEquals(fifth, container.getItem(fifthId));
- assertEquals(newFirstId, container.nextItemId(fifthId));
- assertNull(container.prevItemId(fifthId));
-
- }
-
- protected void testContainerIndexed(Container.Indexed container,
- Object itemId, int itemPosition, boolean testAddEmptyItemAt,
- Object newItemId, boolean testAddItemAtWithId) {
- initializeContainer(container);
-
- // indexOfId
- Assert.assertEquals(itemPosition, container.indexOfId(itemId));
-
- // getIdByIndex
- Assert.assertEquals(itemId, container.getIdByIndex(itemPosition));
-
- // addItemAt
- if (testAddEmptyItemAt) {
- Object addedId = container.addItemAt(itemPosition);
- Assert.assertEquals(itemPosition, container.indexOfId(addedId));
- Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId));
- Assert.assertEquals(addedId, container.getIdByIndex(itemPosition));
- Assert.assertEquals(itemId,
- container.getIdByIndex(itemPosition + 1));
-
- Object newFirstId = container.addItemAt(0);
- Assert.assertEquals(0, container.indexOfId(newFirstId));
- Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId));
- Assert.assertEquals(newFirstId, container.firstItemId());
- Assert.assertEquals(newFirstId, container.getIdByIndex(0));
- Assert.assertEquals(itemId,
- container.getIdByIndex(itemPosition + 2));
-
- Object newLastId = container.addItemAt(container.size());
- Assert.assertEquals(container.size() - 1,
- container.indexOfId(newLastId));
- Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId));
- Assert.assertEquals(newLastId, container.lastItemId());
- Assert.assertEquals(newLastId,
- container.getIdByIndex(container.size() - 1));
- Assert.assertEquals(itemId,
- container.getIdByIndex(itemPosition + 2));
-
- Assert.assertTrue(container.removeItem(addedId));
- Assert.assertTrue(container.removeItem(newFirstId));
- Assert.assertTrue(container.removeItem(newLastId));
-
- Assert.assertFalse(
- "Removing non-existing item should indicate failure",
- container.removeItem(addedId));
- }
-
- // addItemAt
- if (testAddItemAtWithId) {
- container.addItemAt(itemPosition, newItemId);
- Assert.assertEquals(itemPosition, container.indexOfId(newItemId));
- Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId));
- Assert.assertEquals(newItemId, container.getIdByIndex(itemPosition));
- Assert.assertEquals(itemId,
- container.getIdByIndex(itemPosition + 1));
- Assert.assertTrue(container.removeItem(newItemId));
- Assert.assertFalse(container.containsId(newItemId));
-
- container.addItemAt(0, newItemId);
- Assert.assertEquals(0, container.indexOfId(newItemId));
- Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId));
- Assert.assertEquals(newItemId, container.firstItemId());
- Assert.assertEquals(newItemId, container.getIdByIndex(0));
- Assert.assertEquals(itemId,
- container.getIdByIndex(itemPosition + 1));
- Assert.assertTrue(container.removeItem(newItemId));
- Assert.assertFalse(container.containsId(newItemId));
-
- container.addItemAt(container.size(), newItemId);
- Assert.assertEquals(container.size() - 1,
- container.indexOfId(newItemId));
- Assert.assertEquals(itemPosition, container.indexOfId(itemId));
- Assert.assertEquals(newItemId, container.lastItemId());
- Assert.assertEquals(newItemId,
- container.getIdByIndex(container.size() - 1));
- Assert.assertEquals(itemId, container.getIdByIndex(itemPosition));
- Assert.assertTrue(container.removeItem(newItemId));
- Assert.assertFalse(container.containsId(newItemId));
- }
- }
-
- protected void testContainerFiltering(Container.Filterable container) {
- initializeContainer(container);
-
- // Filter by "contains ab"
- container.addContainerFilter(new SimpleStringFilter(
- FULLY_QUALIFIED_NAME, "ab", false, false));
-
- validateContainer(container, "com.vaadin.data.BufferedValidatable",
- "com.vaadin.ui.TabSheet",
- "com.vaadin.terminal.gwt.client.Focusable",
- "com.vaadin.data.Buffered", isFilteredOutItemNull(), 20);
-
- // Filter by "contains da" (reversed as ad here)
- container.removeAllContainerFilters();
- container.addContainerFilter(new SimpleStringFilter(
- REVERSE_FULLY_QUALIFIED_NAME, "ad", false, false));
-
- validateContainer(container, "com.vaadin.data.Buffered",
- "com.vaadin.terminal.gwt.server.ComponentSizeValidator",
- "com.vaadin.data.util.IndexedContainer",
- "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility",
- isFilteredOutItemNull(), 37);
- }
-
- /**
- * Override in subclasses to return false if the container getItem() method
- * returns a non-null value for an item that has been filtered out.
- *
- * @return
- */
- protected boolean isFilteredOutItemNull() {
- return true;
- }
-
- protected void testContainerSortingAndFiltering(Container.Sortable sortable) {
- Filterable filterable = (Filterable) sortable;
-
- initializeContainer(sortable);
-
- // Filter by "contains ab"
- filterable.addContainerFilter(new SimpleStringFilter(
- FULLY_QUALIFIED_NAME, "ab", false, false));
-
- // Must be able to sort based on PROP1 for this test
- assertTrue(sortable.getSortableContainerPropertyIds().contains(
- FULLY_QUALIFIED_NAME));
-
- sortable.sort(new Object[] { FULLY_QUALIFIED_NAME },
- new boolean[] { true });
-
- validateContainer(sortable, "com.vaadin.data.BufferedValidatable",
- "com.vaadin.ui.TableFieldFactory",
- "com.vaadin.ui.TableFieldFactory",
- "com.vaadin.data.util.BeanItem", isFilteredOutItemNull(), 20);
- }
-
- protected void testContainerSorting(Container.Filterable container) {
- Container.Sortable sortable = (Sortable) container;
-
- initializeContainer(container);
-
- // Must be able to sort based on PROP1 for this test
- assertTrue(sortable.getSortableContainerPropertyIds().contains(
- FULLY_QUALIFIED_NAME));
- assertTrue(sortable.getSortableContainerPropertyIds().contains(
- REVERSE_FULLY_QUALIFIED_NAME));
-
- sortable.sort(new Object[] { FULLY_QUALIFIED_NAME },
- new boolean[] { true });
-
- validateContainer(container, "com.vaadin.Application",
- "org.vaadin.test.LastClass",
- "com.vaadin.terminal.ApplicationResource", "blah", true,
- sampleData.length);
-
- sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME },
- new boolean[] { true });
-
- validateContainer(container,
- "com.vaadin.terminal.gwt.server.ApplicationPortlet2",
- "com.vaadin.data.util.ObjectProperty",
- "com.vaadin.ui.BaseFieldFactory", "blah", true,
- sampleData.length);
-
- }
-
- protected void initializeContainer(Container container) {
- Assert.assertTrue(container.removeAllItems());
- Object[] propertyIds = container.getContainerPropertyIds().toArray();
- for (Object propertyId : propertyIds) {
- container.removeContainerProperty(propertyId);
- }
-
- container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, "");
- container.addContainerProperty(SIMPLE_NAME, String.class, "");
- container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME,
- String.class, null);
- container.addContainerProperty(ID_NUMBER, Integer.class, null);
-
- for (int i = 0; i < sampleData.length; i++) {
- String id = sampleData[i];
- Item item = container.addItem(id);
-
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]);
- item.getItemProperty(SIMPLE_NAME).setValue(
- getSimpleName(sampleData[i]));
- item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue(
- reverse(sampleData[i]));
- item.getItemProperty(ID_NUMBER).setValue(i);
- }
- }
-
- protected static String getSimpleName(String name) {
- if (name.contains(".")) {
- return name.substring(name.lastIndexOf('.') + 1);
- } else {
- return name;
- }
- }
-
- protected static String reverse(String string) {
- return new StringBuilder(string).reverse().toString();
- }
-
- protected final String[] sampleData = {
- "com.vaadin.annotations.AutoGenerated", "com.vaadin.Application",
- "com.vaadin.data.Buffered", "com.vaadin.data.BufferedValidatable",
- "com.vaadin.data.Container", "com.vaadin.data.Item",
- "com.vaadin.data.Property", "com.vaadin.data.util.BeanItem",
- "com.vaadin.data.util.BeanItemContainer",
- "com.vaadin.data.util.ContainerHierarchicalWrapper",
- "com.vaadin.data.util.ContainerOrderedWrapper",
- "com.vaadin.data.util.DefaultItemSorter",
- "com.vaadin.data.util.FilesystemContainer",
- "com.vaadin.data.util.Filter",
- "com.vaadin.data.util.HierarchicalContainer",
- "com.vaadin.data.util.IndexedContainer",
- "com.vaadin.data.util.ItemSorter",
- "com.vaadin.data.util.MethodProperty",
- "com.vaadin.data.util.ObjectProperty",
- "com.vaadin.data.util.PropertyFormatter",
- "com.vaadin.data.util.PropertysetItem",
- "com.vaadin.data.util.QueryContainer",
- "com.vaadin.data.util.TextFileProperty",
- "com.vaadin.data.Validatable",
- "com.vaadin.data.validator.AbstractStringValidator",
- "com.vaadin.data.validator.AbstractValidator",
- "com.vaadin.data.validator.CompositeValidator",
- "com.vaadin.data.validator.DoubleValidator",
- "com.vaadin.data.validator.EmailValidator",
- "com.vaadin.data.validator.IntegerValidator",
- "com.vaadin.data.validator.NullValidator",
- "com.vaadin.data.validator.RegexpValidator",
- "com.vaadin.data.validator.StringLengthValidator",
- "com.vaadin.data.Validator", "com.vaadin.event.Action",
- "com.vaadin.event.ComponentEventListener",
- "com.vaadin.event.EventRouter", "com.vaadin.event.FieldEvents",
- "com.vaadin.event.ItemClickEvent", "com.vaadin.event.LayoutEvents",
- "com.vaadin.event.ListenerMethod",
- "com.vaadin.event.MethodEventSource",
- "com.vaadin.event.MouseEvents", "com.vaadin.event.ShortcutAction",
- "com.vaadin.launcher.DemoLauncher",
- "com.vaadin.launcher.DevelopmentServerLauncher",
- "com.vaadin.launcher.util.BrowserLauncher",
- "com.vaadin.service.ApplicationContext",
- "com.vaadin.service.FileTypeResolver",
- "com.vaadin.terminal.ApplicationResource",
- "com.vaadin.terminal.ClassResource",
- "com.vaadin.terminal.CompositeErrorMessage",
- "com.vaadin.terminal.DownloadStream",
- "com.vaadin.terminal.ErrorMessage",
- "com.vaadin.terminal.ExternalResource",
- "com.vaadin.terminal.FileResource",
- "com.vaadin.terminal.gwt.client.ApplicationConfiguration",
- "com.vaadin.terminal.gwt.client.ApplicationConnection",
- "com.vaadin.terminal.gwt.client.BrowserInfo",
- "com.vaadin.terminal.gwt.client.ClientExceptionHandler",
- "com.vaadin.terminal.gwt.client.ComponentDetail",
- "com.vaadin.terminal.gwt.client.ComponentDetailMap",
- "com.vaadin.terminal.gwt.client.ComponentLocator",
- "com.vaadin.terminal.gwt.client.Console",
- "com.vaadin.terminal.gwt.client.Container",
- "com.vaadin.terminal.gwt.client.ContainerResizedListener",
- "com.vaadin.terminal.gwt.client.CSSRule",
- "com.vaadin.terminal.gwt.client.DateTimeService",
- "com.vaadin.terminal.gwt.client.DefaultWidgetSet",
- "com.vaadin.terminal.gwt.client.Focusable",
- "com.vaadin.terminal.gwt.client.HistoryImplIEVaadin",
- "com.vaadin.terminal.gwt.client.LocaleNotLoadedException",
- "com.vaadin.terminal.gwt.client.LocaleService",
- "com.vaadin.terminal.gwt.client.MouseEventDetails",
- "com.vaadin.terminal.gwt.client.NullConsole",
- "com.vaadin.terminal.gwt.client.Paintable",
- "com.vaadin.terminal.gwt.client.RenderInformation",
- "com.vaadin.terminal.gwt.client.RenderSpace",
- "com.vaadin.terminal.gwt.client.StyleConstants",
- "com.vaadin.terminal.gwt.client.TooltipInfo",
- "com.vaadin.terminal.gwt.client.ui.Action",
- "com.vaadin.terminal.gwt.client.ui.ActionOwner",
- "com.vaadin.terminal.gwt.client.ui.AlignmentInfo",
- "com.vaadin.terminal.gwt.client.ui.CalendarEntry",
- "com.vaadin.terminal.gwt.client.ui.ClickEventHandler",
- "com.vaadin.terminal.gwt.client.ui.Field",
- "com.vaadin.terminal.gwt.client.ui.Icon",
- "com.vaadin.terminal.gwt.client.ui.layout.CellBasedLayout",
- "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer",
- "com.vaadin.terminal.gwt.client.ui.layout.Margins",
- "com.vaadin.terminal.gwt.client.ui.LayoutClickEventHandler",
- "com.vaadin.terminal.gwt.client.ui.MenuBar",
- "com.vaadin.terminal.gwt.client.ui.MenuItem",
- "com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextArea",
- "com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextToolbar",
- "com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler",
- "com.vaadin.terminal.gwt.client.ui.SubPartAware",
- "com.vaadin.terminal.gwt.client.ui.Table",
- "com.vaadin.terminal.gwt.client.ui.TreeAction",
- "com.vaadin.terminal.gwt.client.ui.TreeImages",
- "com.vaadin.terminal.gwt.client.ui.VAbsoluteLayout",
- "com.vaadin.terminal.gwt.client.ui.VAccordion",
- "com.vaadin.terminal.gwt.client.ui.VButton",
- "com.vaadin.terminal.gwt.client.ui.VCalendarPanel",
- "com.vaadin.terminal.gwt.client.ui.VCheckBox",
- "com.vaadin.terminal.gwt.client.ui.VContextMenu",
- "com.vaadin.terminal.gwt.client.ui.VCssLayout",
- "com.vaadin.terminal.gwt.client.ui.VCustomComponent",
- "com.vaadin.terminal.gwt.client.ui.VCustomLayout",
- "com.vaadin.terminal.gwt.client.ui.VDateField",
- "com.vaadin.terminal.gwt.client.ui.VDateFieldCalendar",
- "com.vaadin.terminal.gwt.client.ui.VEmbedded",
- "com.vaadin.terminal.gwt.client.ui.VFilterSelect",
- "com.vaadin.terminal.gwt.client.ui.VForm",
- "com.vaadin.terminal.gwt.client.ui.VFormLayout",
- "com.vaadin.terminal.gwt.client.ui.VGridLayout",
- "com.vaadin.terminal.gwt.client.ui.VHorizontalLayout",
- "com.vaadin.terminal.gwt.client.ui.VLabel",
- "com.vaadin.terminal.gwt.client.ui.VLink",
- "com.vaadin.terminal.gwt.client.ui.VListSelect",
- "com.vaadin.terminal.gwt.client.ui.VMarginInfo",
- "com.vaadin.terminal.gwt.client.ui.VMenuBar",
- "com.vaadin.terminal.gwt.client.ui.VNativeButton",
- "com.vaadin.terminal.gwt.client.ui.VNativeSelect",
- "com.vaadin.terminal.gwt.client.ui.VNotification",
- "com.vaadin.terminal.gwt.client.ui.VOptionGroup",
- "com.vaadin.terminal.gwt.client.ui.VOptionGroupBase",
- "com.vaadin.terminal.gwt.client.ui.VOrderedLayout",
- "com.vaadin.terminal.gwt.client.ui.VOverlay",
- "com.vaadin.terminal.gwt.client.ui.VPanel",
- "com.vaadin.terminal.gwt.client.ui.VPasswordField",
- "com.vaadin.terminal.gwt.client.ui.VPopupCalendar",
- "com.vaadin.terminal.gwt.client.ui.VPopupView",
- "com.vaadin.terminal.gwt.client.ui.VProgressIndicator",
- "com.vaadin.terminal.gwt.client.ui.VScrollTable",
- "com.vaadin.terminal.gwt.client.ui.VSlider",
- "com.vaadin.terminal.gwt.client.ui.VSplitPanel",
- "com.vaadin.terminal.gwt.client.ui.VSplitPanelHorizontal",
- "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical",
- "com.vaadin.terminal.gwt.client.ui.VTablePaging",
- "com.vaadin.terminal.gwt.client.ui.VTabsheet",
- "com.vaadin.terminal.gwt.client.ui.VTabsheetBase",
- "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel",
- "com.vaadin.terminal.gwt.client.ui.VTextArea",
- "com.vaadin.terminal.gwt.client.ui.VTextField",
- "com.vaadin.terminal.gwt.client.ui.VTextualDate",
- "com.vaadin.terminal.gwt.client.ui.VTime",
- "com.vaadin.terminal.gwt.client.ui.VTree",
- "com.vaadin.terminal.gwt.client.ui.VTwinColSelect",
- "com.vaadin.terminal.gwt.client.ui.VUnknownComponent",
- "com.vaadin.terminal.gwt.client.ui.VUpload",
- "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility",
- "com.vaadin.terminal.gwt.client.ui.VVerticalLayout",
- "com.vaadin.terminal.gwt.client.ui.VView",
- "com.vaadin.terminal.gwt.client.ui.VWindow",
- "com.vaadin.terminal.gwt.client.UIDL",
- "com.vaadin.terminal.gwt.client.Util",
- "com.vaadin.terminal.gwt.client.ValueMap",
- "com.vaadin.terminal.gwt.client.VCaption",
- "com.vaadin.terminal.gwt.client.VCaptionWrapper",
- "com.vaadin.terminal.gwt.client.VDebugConsole",
- "com.vaadin.terminal.gwt.client.VErrorMessage",
- "com.vaadin.terminal.gwt.client.VTooltip",
- "com.vaadin.terminal.gwt.client.VUIDLBrowser",
- "com.vaadin.terminal.gwt.client.WidgetMap",
- "com.vaadin.terminal.gwt.client.WidgetSet",
- "com.vaadin.terminal.gwt.server.AbstractApplicationPortlet",
- "com.vaadin.terminal.gwt.server.AbstractApplicationServlet",
- "com.vaadin.terminal.gwt.server.AbstractCommunicationManager",
- "com.vaadin.terminal.gwt.server.AbstractWebApplicationContext",
- "com.vaadin.terminal.gwt.server.ApplicationPortlet",
- "com.vaadin.terminal.gwt.server.ApplicationPortlet2",
- "com.vaadin.terminal.gwt.server.ApplicationRunnerServlet",
- "com.vaadin.terminal.gwt.server.ApplicationServlet",
- "com.vaadin.terminal.gwt.server.ChangeVariablesErrorEvent",
- "com.vaadin.terminal.gwt.server.CommunicationManager",
- "com.vaadin.terminal.gwt.server.ComponentSizeValidator",
- "com.vaadin.terminal.gwt.server.Constants",
- "com.vaadin.terminal.gwt.server.GAEApplicationServlet",
- "com.vaadin.terminal.gwt.server.HttpServletRequestListener",
- "com.vaadin.terminal.gwt.server.HttpUploadStream",
- "com.vaadin.terminal.gwt.server.JsonPaintTarget",
- "com.vaadin.terminal.gwt.server.PortletApplicationContext",
- "com.vaadin.terminal.gwt.server.PortletApplicationContext2",
- "com.vaadin.terminal.gwt.server.PortletCommunicationManager",
- "com.vaadin.terminal.gwt.server.PortletRequestListener",
- "com.vaadin.terminal.gwt.server.RestrictedRenderResponse",
- "com.vaadin.terminal.gwt.server.SessionExpiredException",
- "com.vaadin.terminal.gwt.server.SystemMessageException",
- "com.vaadin.terminal.gwt.server.WebApplicationContext",
- "com.vaadin.terminal.gwt.server.WebBrowser",
- "com.vaadin.terminal.gwt.widgetsetutils.ClassPathExplorer",
- "com.vaadin.terminal.gwt.widgetsetutils.WidgetMapGenerator",
- "com.vaadin.terminal.gwt.widgetsetutils.WidgetSetBuilder",
- "com.vaadin.terminal.KeyMapper", "com.vaadin.terminal.Paintable",
- "com.vaadin.terminal.PaintException",
- "com.vaadin.terminal.PaintTarget",
- "com.vaadin.terminal.ParameterHandler",
- "com.vaadin.terminal.Resource", "com.vaadin.terminal.Scrollable",
- "com.vaadin.terminal.Sizeable",
- "com.vaadin.terminal.StreamResource",
- "com.vaadin.terminal.SystemError", "com.vaadin.terminal.Terminal",
- "com.vaadin.terminal.ThemeResource",
- "com.vaadin.terminal.UploadStream",
- "com.vaadin.terminal.URIHandler", "com.vaadin.terminal.UserError",
- "com.vaadin.terminal.VariableOwner",
- "com.vaadin.tools.ReflectTools",
- "com.vaadin.tools.WidgetsetCompiler",
- "com.vaadin.ui.AbsoluteLayout", "com.vaadin.ui.AbstractComponent",
- "com.vaadin.ui.AbstractComponentContainer",
- "com.vaadin.ui.AbstractField", "com.vaadin.ui.AbstractLayout",
- "com.vaadin.ui.AbstractOrderedLayout",
- "com.vaadin.ui.AbstractSelect", "com.vaadin.ui.Accordion",
- "com.vaadin.ui.Alignment", "com.vaadin.ui.AlignmentUtils",
- "com.vaadin.ui.BaseFieldFactory", "com.vaadin.ui.Button",
- "com.vaadin.ui.CheckBox", "com.vaadin.ui.ClientWidget",
- "com.vaadin.ui.ComboBox", "com.vaadin.ui.Component",
- "com.vaadin.ui.ComponentContainer", "com.vaadin.ui.CssLayout",
- "com.vaadin.ui.CustomComponent", "com.vaadin.ui.CustomLayout",
- "com.vaadin.ui.DateField", "com.vaadin.ui.DefaultFieldFactory",
- "com.vaadin.ui.Embedded", "com.vaadin.ui.ExpandLayout",
- "com.vaadin.ui.Field", "com.vaadin.ui.FieldFactory",
- "com.vaadin.ui.Form", "com.vaadin.ui.FormFieldFactory",
- "com.vaadin.ui.FormLayout", "com.vaadin.ui.GridLayout",
- "com.vaadin.ui.HorizontalLayout", "com.vaadin.ui.InlineDateField",
- "com.vaadin.ui.Label", "com.vaadin.ui.Layout",
- "com.vaadin.ui.Link", "com.vaadin.ui.ListSelect",
- "com.vaadin.ui.LoginForm", "com.vaadin.ui.MenuBar",
- "com.vaadin.ui.NativeButton", "com.vaadin.ui.NativeSelect",
- "com.vaadin.ui.OptionGroup", "com.vaadin.ui.OrderedLayout",
- "com.vaadin.ui.Panel", "com.vaadin.ui.PopupDateField",
- "com.vaadin.ui.PopupView", "com.vaadin.ui.ProgressIndicator",
- "com.vaadin.ui.RichTextArea", "com.vaadin.ui.Select",
- "com.vaadin.ui.Slider", "com.vaadin.ui.SplitPanel",
- "com.vaadin.ui.Table", "com.vaadin.ui.TableFieldFactory",
- "com.vaadin.ui.TabSheet", "com.vaadin.ui.TextField",
- "com.vaadin.ui.Tree", "com.vaadin.ui.TwinColSelect",
- "com.vaadin.ui.Upload", "com.vaadin.ui.UriFragmentUtility",
- "com.vaadin.ui.VerticalLayout", "com.vaadin.ui.Window",
- "com.vaadin.util.SerializerHelper", "org.vaadin.test.LastClass" };
-
-}
+package com.vaadin.data.util; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.vaadin.data.Container; +import com.vaadin.data.Container.Filterable; +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Container.Sortable; +import com.vaadin.data.Item; +import com.vaadin.data.util.filter.SimpleStringFilter; + +public abstract class AbstractContainerTest extends TestCase { + + /** + * Helper class for testing e.g. listeners expecting events to be fired. + */ + protected abstract static class AbstractEventCounter { + private int eventCount = 0; + private int lastAssertedEventCount = 0; + + /** + * Increment the event count. To be called by subclasses e.g. from a + * listener method. + */ + protected void increment() { + ++eventCount; + } + + /** + * Check that no one event has occurred since the previous assert call. + */ + public void assertNone() { + Assert.assertEquals(lastAssertedEventCount, eventCount); + } + + /** + * Check that exactly one event has occurred since the previous assert + * call. + */ + public void assertOnce() { + Assert.assertEquals(++lastAssertedEventCount, eventCount); + } + + /** + * Reset the counter and the expected count. + */ + public void reset() { + eventCount = 0; + lastAssertedEventCount = 0; + } + } + + /** + * Test class for counting item set change events and verifying they have + * been received. + */ + protected static class ItemSetChangeCounter extends AbstractEventCounter + implements ItemSetChangeListener { + + public void containerItemSetChange(ItemSetChangeEvent event) { + increment(); + } + + } + + // #6043: for items that have been filtered out, Container interface does + // not specify what to return from getItem() and getContainerProperty(), so + // need checkGetItemNull parameter for the test to be usable for most + // current containers + protected void validateContainer(Container container, + Object expectedFirstItemId, Object expectedLastItemId, + Object itemIdInSet, Object itemIdNotInSet, + boolean checkGetItemNull, int expectedSize) { + Container.Indexed indexed = null; + if (container instanceof Container.Indexed) { + indexed = (Container.Indexed) container; + } + + List<Object> itemIdList = new ArrayList<Object>(container.getItemIds()); + + // size() + assertEquals(expectedSize, container.size()); + assertEquals(expectedSize, itemIdList.size()); + + // first item, last item + Object first = itemIdList.get(0); + Object last = itemIdList.get(itemIdList.size() - 1); + + assertEquals(expectedFirstItemId, first); + assertEquals(expectedLastItemId, last); + + // containsId + assertFalse(container.containsId(itemIdNotInSet)); + assertTrue(container.containsId(itemIdInSet)); + + // getItem + if (checkGetItemNull) { + assertNull(container.getItem(itemIdNotInSet)); + } + assertNotNull(container.getItem(itemIdInSet)); + + // getContainerProperty + for (Object propId : container.getContainerPropertyIds()) { + if (checkGetItemNull) { + assertNull(container.getContainerProperty(itemIdNotInSet, + propId)); + } + assertNotNull(container.getContainerProperty(itemIdInSet, propId)); + } + + if (indexed != null) { + // firstItemId + assertEquals(first, indexed.firstItemId()); + + // lastItemId + assertEquals(last, indexed.lastItemId()); + + // nextItemId + assertEquals(itemIdList.get(1), indexed.nextItemId(first)); + + // prevItemId + assertEquals(itemIdList.get(itemIdList.size() - 2), + indexed.prevItemId(last)); + + // isFirstId + assertTrue(indexed.isFirstId(first)); + assertFalse(indexed.isFirstId(last)); + + // isLastId + assertTrue(indexed.isLastId(last)); + assertFalse(indexed.isLastId(first)); + + // indexOfId + assertEquals(0, indexed.indexOfId(first)); + assertEquals(expectedSize - 1, indexed.indexOfId(last)); + + // getIdByIndex + assertEquals(indexed.getIdByIndex(0), first); + assertEquals(indexed.getIdByIndex(expectedSize - 1), last); + + } + + } + + protected static final Object FULLY_QUALIFIED_NAME = "fullyQualifiedName"; + protected static final Object SIMPLE_NAME = "simpleName"; + protected static final Object REVERSE_FULLY_QUALIFIED_NAME = "reverseFullyQualifiedName"; + protected static final Object ID_NUMBER = "idNumber"; + + protected void testBasicContainerOperations(Container container) { + initializeContainer(container); + + // Basic container + validateContainer(container, sampleData[0], + sampleData[sampleData.length - 1], sampleData[10], "abc", true, + sampleData.length); + } + + protected void testContainerOrdered(Container.Ordered container) { + Object id = container.addItem(); + assertNotNull(id); + Item item = container.getItem(id); + assertNotNull(item); + + assertEquals(id, container.firstItemId()); + assertEquals(id, container.lastItemId()); + + // isFirstId + assertTrue(container.isFirstId(id)); + assertTrue(container.isFirstId(container.firstItemId())); + // isLastId + assertTrue(container.isLastId(id)); + assertTrue(container.isLastId(container.lastItemId())); + + // Add a new item before the first + // addItemAfter + Object newFirstId = container.addItemAfter(null); + assertNotNull(newFirstId); + assertNotNull(container.getItem(newFirstId)); + + // isFirstId + assertTrue(container.isFirstId(newFirstId)); + assertTrue(container.isFirstId(container.firstItemId())); + // isLastId + assertTrue(container.isLastId(id)); + assertTrue(container.isLastId(container.lastItemId())); + + // nextItemId + assertEquals(id, container.nextItemId(newFirstId)); + assertNull(container.nextItemId(id)); + assertNull(container.nextItemId("not-in-container")); + + // prevItemId + assertEquals(newFirstId, container.prevItemId(id)); + assertNull(container.prevItemId(newFirstId)); + assertNull(container.prevItemId("not-in-container")); + + // addItemAfter(Object) + Object newSecondItemId = container.addItemAfter(newFirstId); + // order is now: newFirstId, newSecondItemId, id + assertNotNull(newSecondItemId); + assertNotNull(container.getItem(newSecondItemId)); + assertEquals(id, container.nextItemId(newSecondItemId)); + assertEquals(newFirstId, container.prevItemId(newSecondItemId)); + + // addItemAfter(Object,Object) + String fourthId = "id of the fourth item"; + Item fourth = container.addItemAfter(newFirstId, fourthId); + // order is now: newFirstId, fourthId, newSecondItemId, id + assertNotNull(fourth); + assertEquals(fourth, container.getItem(fourthId)); + assertEquals(newSecondItemId, container.nextItemId(fourthId)); + assertEquals(newFirstId, container.prevItemId(fourthId)); + + // addItemAfter(Object,Object) + Object fifthId = new Object(); + Item fifth = container.addItemAfter(null, fifthId); + // order is now: fifthId, newFirstId, fourthId, newSecondItemId, id + assertNotNull(fifth); + assertEquals(fifth, container.getItem(fifthId)); + assertEquals(newFirstId, container.nextItemId(fifthId)); + assertNull(container.prevItemId(fifthId)); + + } + + protected void testContainerIndexed(Container.Indexed container, + Object itemId, int itemPosition, boolean testAddEmptyItemAt, + Object newItemId, boolean testAddItemAtWithId) { + initializeContainer(container); + + // indexOfId + Assert.assertEquals(itemPosition, container.indexOfId(itemId)); + + // getIdByIndex + Assert.assertEquals(itemId, container.getIdByIndex(itemPosition)); + + // addItemAt + if (testAddEmptyItemAt) { + Object addedId = container.addItemAt(itemPosition); + Assert.assertEquals(itemPosition, container.indexOfId(addedId)); + Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); + Assert.assertEquals(addedId, container.getIdByIndex(itemPosition)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 1)); + + Object newFirstId = container.addItemAt(0); + Assert.assertEquals(0, container.indexOfId(newFirstId)); + Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId)); + Assert.assertEquals(newFirstId, container.firstItemId()); + Assert.assertEquals(newFirstId, container.getIdByIndex(0)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 2)); + + Object newLastId = container.addItemAt(container.size()); + Assert.assertEquals(container.size() - 1, + container.indexOfId(newLastId)); + Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId)); + Assert.assertEquals(newLastId, container.lastItemId()); + Assert.assertEquals(newLastId, + container.getIdByIndex(container.size() - 1)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 2)); + + Assert.assertTrue(container.removeItem(addedId)); + Assert.assertTrue(container.removeItem(newFirstId)); + Assert.assertTrue(container.removeItem(newLastId)); + + Assert.assertFalse( + "Removing non-existing item should indicate failure", + container.removeItem(addedId)); + } + + // addItemAt + if (testAddItemAtWithId) { + container.addItemAt(itemPosition, newItemId); + Assert.assertEquals(itemPosition, container.indexOfId(newItemId)); + Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); + Assert.assertEquals(newItemId, container.getIdByIndex(itemPosition)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 1)); + Assert.assertTrue(container.removeItem(newItemId)); + Assert.assertFalse(container.containsId(newItemId)); + + container.addItemAt(0, newItemId); + Assert.assertEquals(0, container.indexOfId(newItemId)); + Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); + Assert.assertEquals(newItemId, container.firstItemId()); + Assert.assertEquals(newItemId, container.getIdByIndex(0)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 1)); + Assert.assertTrue(container.removeItem(newItemId)); + Assert.assertFalse(container.containsId(newItemId)); + + container.addItemAt(container.size(), newItemId); + Assert.assertEquals(container.size() - 1, + container.indexOfId(newItemId)); + Assert.assertEquals(itemPosition, container.indexOfId(itemId)); + Assert.assertEquals(newItemId, container.lastItemId()); + Assert.assertEquals(newItemId, + container.getIdByIndex(container.size() - 1)); + Assert.assertEquals(itemId, container.getIdByIndex(itemPosition)); + Assert.assertTrue(container.removeItem(newItemId)); + Assert.assertFalse(container.containsId(newItemId)); + } + } + + protected void testContainerFiltering(Container.Filterable container) { + initializeContainer(container); + + // Filter by "contains ab" + container.addContainerFilter(new SimpleStringFilter( + FULLY_QUALIFIED_NAME, "ab", false, false)); + + validateContainer(container, "com.vaadin.data.BufferedValidatable", + "com.vaadin.ui.TabSheet", + "com.vaadin.terminal.gwt.client.Focusable", + "com.vaadin.data.Buffered", isFilteredOutItemNull(), 20); + + // Filter by "contains da" (reversed as ad here) + container.removeAllContainerFilters(); + container.addContainerFilter(new SimpleStringFilter( + REVERSE_FULLY_QUALIFIED_NAME, "ad", false, false)); + + validateContainer(container, "com.vaadin.data.Buffered", + "com.vaadin.terminal.gwt.server.ComponentSizeValidator", + "com.vaadin.data.util.IndexedContainer", + "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", + isFilteredOutItemNull(), 37); + } + + /** + * Override in subclasses to return false if the container getItem() method + * returns a non-null value for an item that has been filtered out. + * + * @return + */ + protected boolean isFilteredOutItemNull() { + return true; + } + + protected void testContainerSortingAndFiltering(Container.Sortable sortable) { + Filterable filterable = (Filterable) sortable; + + initializeContainer(sortable); + + // Filter by "contains ab" + filterable.addContainerFilter(new SimpleStringFilter( + FULLY_QUALIFIED_NAME, "ab", false, false)); + + // Must be able to sort based on PROP1 for this test + assertTrue(sortable.getSortableContainerPropertyIds().contains( + FULLY_QUALIFIED_NAME)); + + sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateContainer(sortable, "com.vaadin.data.BufferedValidatable", + "com.vaadin.ui.TableFieldFactory", + "com.vaadin.ui.TableFieldFactory", + "com.vaadin.data.util.BeanItem", isFilteredOutItemNull(), 20); + } + + protected void testContainerSorting(Container.Filterable container) { + Container.Sortable sortable = (Sortable) container; + + initializeContainer(container); + + // Must be able to sort based on PROP1 for this test + assertTrue(sortable.getSortableContainerPropertyIds().contains( + FULLY_QUALIFIED_NAME)); + assertTrue(sortable.getSortableContainerPropertyIds().contains( + REVERSE_FULLY_QUALIFIED_NAME)); + + sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateContainer(container, "com.vaadin.Application", + "org.vaadin.test.LastClass", + "com.vaadin.terminal.ApplicationResource", "blah", true, + sampleData.length); + + sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateContainer(container, + "com.vaadin.terminal.gwt.server.ApplicationPortlet2", + "com.vaadin.data.util.ObjectProperty", + "com.vaadin.ui.BaseFieldFactory", "blah", true, + sampleData.length); + + } + + protected void initializeContainer(Container container) { + Assert.assertTrue(container.removeAllItems()); + Object[] propertyIds = container.getContainerPropertyIds().toArray(); + for (Object propertyId : propertyIds) { + container.removeContainerProperty(propertyId); + } + + container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, ""); + container.addContainerProperty(SIMPLE_NAME, String.class, ""); + container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME, + String.class, null); + container.addContainerProperty(ID_NUMBER, Integer.class, null); + + for (int i = 0; i < sampleData.length; i++) { + String id = sampleData[i]; + Item item = container.addItem(id); + + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]); + item.getItemProperty(SIMPLE_NAME).setValue( + getSimpleName(sampleData[i])); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( + reverse(sampleData[i])); + item.getItemProperty(ID_NUMBER).setValue(i); + } + } + + protected static String getSimpleName(String name) { + if (name.contains(".")) { + return name.substring(name.lastIndexOf('.') + 1); + } else { + return name; + } + } + + protected static String reverse(String string) { + return new StringBuilder(string).reverse().toString(); + } + + protected final String[] sampleData = { + "com.vaadin.annotations.AutoGenerated", "com.vaadin.Application", + "com.vaadin.data.Buffered", "com.vaadin.data.BufferedValidatable", + "com.vaadin.data.Container", "com.vaadin.data.Item", + "com.vaadin.data.Property", "com.vaadin.data.util.BeanItem", + "com.vaadin.data.util.BeanItemContainer", + "com.vaadin.data.util.ContainerHierarchicalWrapper", + "com.vaadin.data.util.ContainerOrderedWrapper", + "com.vaadin.data.util.DefaultItemSorter", + "com.vaadin.data.util.FilesystemContainer", + "com.vaadin.data.util.Filter", + "com.vaadin.data.util.HierarchicalContainer", + "com.vaadin.data.util.IndexedContainer", + "com.vaadin.data.util.ItemSorter", + "com.vaadin.data.util.MethodProperty", + "com.vaadin.data.util.ObjectProperty", + "com.vaadin.data.util.PropertyFormatter", + "com.vaadin.data.util.PropertysetItem", + "com.vaadin.data.util.QueryContainer", + "com.vaadin.data.util.TextFileProperty", + "com.vaadin.data.Validatable", + "com.vaadin.data.validator.AbstractStringValidator", + "com.vaadin.data.validator.AbstractValidator", + "com.vaadin.data.validator.CompositeValidator", + "com.vaadin.data.validator.DoubleValidator", + "com.vaadin.data.validator.EmailValidator", + "com.vaadin.data.validator.IntegerValidator", + "com.vaadin.data.validator.NullValidator", + "com.vaadin.data.validator.RegexpValidator", + "com.vaadin.data.validator.StringLengthValidator", + "com.vaadin.data.Validator", "com.vaadin.event.Action", + "com.vaadin.event.ComponentEventListener", + "com.vaadin.event.EventRouter", "com.vaadin.event.FieldEvents", + "com.vaadin.event.ItemClickEvent", "com.vaadin.event.LayoutEvents", + "com.vaadin.event.ListenerMethod", + "com.vaadin.event.MethodEventSource", + "com.vaadin.event.MouseEvents", "com.vaadin.event.ShortcutAction", + "com.vaadin.launcher.DemoLauncher", + "com.vaadin.launcher.DevelopmentServerLauncher", + "com.vaadin.launcher.util.BrowserLauncher", + "com.vaadin.service.ApplicationContext", + "com.vaadin.service.FileTypeResolver", + "com.vaadin.terminal.ApplicationResource", + "com.vaadin.terminal.ClassResource", + "com.vaadin.terminal.CompositeErrorMessage", + "com.vaadin.terminal.DownloadStream", + "com.vaadin.terminal.ErrorMessage", + "com.vaadin.terminal.ExternalResource", + "com.vaadin.terminal.FileResource", + "com.vaadin.terminal.gwt.client.ApplicationConfiguration", + "com.vaadin.terminal.gwt.client.ApplicationConnection", + "com.vaadin.terminal.gwt.client.BrowserInfo", + "com.vaadin.terminal.gwt.client.ClientExceptionHandler", + "com.vaadin.terminal.gwt.client.ComponentDetail", + "com.vaadin.terminal.gwt.client.ComponentDetailMap", + "com.vaadin.terminal.gwt.client.ComponentLocator", + "com.vaadin.terminal.gwt.client.Console", + "com.vaadin.terminal.gwt.client.Container", + "com.vaadin.terminal.gwt.client.ContainerResizedListener", + "com.vaadin.terminal.gwt.client.CSSRule", + "com.vaadin.terminal.gwt.client.DateTimeService", + "com.vaadin.terminal.gwt.client.DefaultWidgetSet", + "com.vaadin.terminal.gwt.client.Focusable", + "com.vaadin.terminal.gwt.client.HistoryImplIEVaadin", + "com.vaadin.terminal.gwt.client.LocaleNotLoadedException", + "com.vaadin.terminal.gwt.client.LocaleService", + "com.vaadin.terminal.gwt.client.MouseEventDetails", + "com.vaadin.terminal.gwt.client.NullConsole", + "com.vaadin.terminal.gwt.client.Paintable", + "com.vaadin.terminal.gwt.client.RenderInformation", + "com.vaadin.terminal.gwt.client.RenderSpace", + "com.vaadin.terminal.gwt.client.StyleConstants", + "com.vaadin.terminal.gwt.client.TooltipInfo", + "com.vaadin.terminal.gwt.client.ui.Action", + "com.vaadin.terminal.gwt.client.ui.ActionOwner", + "com.vaadin.terminal.gwt.client.ui.AlignmentInfo", + "com.vaadin.terminal.gwt.client.ui.CalendarEntry", + "com.vaadin.terminal.gwt.client.ui.ClickEventHandler", + "com.vaadin.terminal.gwt.client.ui.Field", + "com.vaadin.terminal.gwt.client.ui.Icon", + "com.vaadin.terminal.gwt.client.ui.layout.CellBasedLayout", + "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer", + "com.vaadin.terminal.gwt.client.ui.layout.Margins", + "com.vaadin.terminal.gwt.client.ui.LayoutClickEventHandler", + "com.vaadin.terminal.gwt.client.ui.MenuBar", + "com.vaadin.terminal.gwt.client.ui.MenuItem", + "com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextArea", + "com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextToolbar", + "com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler", + "com.vaadin.terminal.gwt.client.ui.SubPartAware", + "com.vaadin.terminal.gwt.client.ui.Table", + "com.vaadin.terminal.gwt.client.ui.TreeAction", + "com.vaadin.terminal.gwt.client.ui.TreeImages", + "com.vaadin.terminal.gwt.client.ui.VAbsoluteLayout", + "com.vaadin.terminal.gwt.client.ui.VAccordion", + "com.vaadin.terminal.gwt.client.ui.VButton", + "com.vaadin.terminal.gwt.client.ui.VCalendarPanel", + "com.vaadin.terminal.gwt.client.ui.VCheckBox", + "com.vaadin.terminal.gwt.client.ui.VContextMenu", + "com.vaadin.terminal.gwt.client.ui.VCssLayout", + "com.vaadin.terminal.gwt.client.ui.VCustomComponent", + "com.vaadin.terminal.gwt.client.ui.VCustomLayout", + "com.vaadin.terminal.gwt.client.ui.VDateField", + "com.vaadin.terminal.gwt.client.ui.VDateFieldCalendar", + "com.vaadin.terminal.gwt.client.ui.VEmbedded", + "com.vaadin.terminal.gwt.client.ui.VFilterSelect", + "com.vaadin.terminal.gwt.client.ui.VForm", + "com.vaadin.terminal.gwt.client.ui.VFormLayout", + "com.vaadin.terminal.gwt.client.ui.VGridLayout", + "com.vaadin.terminal.gwt.client.ui.VHorizontalLayout", + "com.vaadin.terminal.gwt.client.ui.VLabel", + "com.vaadin.terminal.gwt.client.ui.VLink", + "com.vaadin.terminal.gwt.client.ui.VListSelect", + "com.vaadin.terminal.gwt.client.ui.VMarginInfo", + "com.vaadin.terminal.gwt.client.ui.VMenuBar", + "com.vaadin.terminal.gwt.client.ui.VNativeButton", + "com.vaadin.terminal.gwt.client.ui.VNativeSelect", + "com.vaadin.terminal.gwt.client.ui.VNotification", + "com.vaadin.terminal.gwt.client.ui.VOptionGroup", + "com.vaadin.terminal.gwt.client.ui.VOptionGroupBase", + "com.vaadin.terminal.gwt.client.ui.VOrderedLayout", + "com.vaadin.terminal.gwt.client.ui.VOverlay", + "com.vaadin.terminal.gwt.client.ui.VPanel", + "com.vaadin.terminal.gwt.client.ui.VPasswordField", + "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", + "com.vaadin.terminal.gwt.client.ui.VPopupView", + "com.vaadin.terminal.gwt.client.ui.VProgressIndicator", + "com.vaadin.terminal.gwt.client.ui.VScrollTable", + "com.vaadin.terminal.gwt.client.ui.VSlider", + "com.vaadin.terminal.gwt.client.ui.VSplitPanel", + "com.vaadin.terminal.gwt.client.ui.VSplitPanelHorizontal", + "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical", + "com.vaadin.terminal.gwt.client.ui.VTablePaging", + "com.vaadin.terminal.gwt.client.ui.VTabsheet", + "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", + "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel", + "com.vaadin.terminal.gwt.client.ui.VTextArea", + "com.vaadin.terminal.gwt.client.ui.VTextField", + "com.vaadin.terminal.gwt.client.ui.VTextualDate", + "com.vaadin.terminal.gwt.client.ui.VTime", + "com.vaadin.terminal.gwt.client.ui.VTree", + "com.vaadin.terminal.gwt.client.ui.VTwinColSelect", + "com.vaadin.terminal.gwt.client.ui.VUnknownComponent", + "com.vaadin.terminal.gwt.client.ui.VUpload", + "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", + "com.vaadin.terminal.gwt.client.ui.VVerticalLayout", + "com.vaadin.terminal.gwt.client.ui.VView", + "com.vaadin.terminal.gwt.client.ui.VWindow", + "com.vaadin.terminal.gwt.client.UIDL", + "com.vaadin.terminal.gwt.client.Util", + "com.vaadin.terminal.gwt.client.ValueMap", + "com.vaadin.terminal.gwt.client.VCaption", + "com.vaadin.terminal.gwt.client.VCaptionWrapper", + "com.vaadin.terminal.gwt.client.VDebugConsole", + "com.vaadin.terminal.gwt.client.VErrorMessage", + "com.vaadin.terminal.gwt.client.VTooltip", + "com.vaadin.terminal.gwt.client.VUIDLBrowser", + "com.vaadin.terminal.gwt.client.WidgetMap", + "com.vaadin.terminal.gwt.client.WidgetSet", + "com.vaadin.terminal.gwt.server.AbstractApplicationPortlet", + "com.vaadin.terminal.gwt.server.AbstractApplicationServlet", + "com.vaadin.terminal.gwt.server.AbstractCommunicationManager", + "com.vaadin.terminal.gwt.server.AbstractWebApplicationContext", + "com.vaadin.terminal.gwt.server.ApplicationPortlet", + "com.vaadin.terminal.gwt.server.ApplicationPortlet2", + "com.vaadin.terminal.gwt.server.ApplicationRunnerServlet", + "com.vaadin.terminal.gwt.server.ApplicationServlet", + "com.vaadin.terminal.gwt.server.ChangeVariablesErrorEvent", + "com.vaadin.terminal.gwt.server.CommunicationManager", + "com.vaadin.terminal.gwt.server.ComponentSizeValidator", + "com.vaadin.terminal.gwt.server.Constants", + "com.vaadin.terminal.gwt.server.GAEApplicationServlet", + "com.vaadin.terminal.gwt.server.HttpServletRequestListener", + "com.vaadin.terminal.gwt.server.HttpUploadStream", + "com.vaadin.terminal.gwt.server.JsonPaintTarget", + "com.vaadin.terminal.gwt.server.PortletApplicationContext", + "com.vaadin.terminal.gwt.server.PortletApplicationContext2", + "com.vaadin.terminal.gwt.server.PortletCommunicationManager", + "com.vaadin.terminal.gwt.server.PortletRequestListener", + "com.vaadin.terminal.gwt.server.RestrictedRenderResponse", + "com.vaadin.terminal.gwt.server.SessionExpiredException", + "com.vaadin.terminal.gwt.server.SystemMessageException", + "com.vaadin.terminal.gwt.server.WebApplicationContext", + "com.vaadin.terminal.gwt.server.WebBrowser", + "com.vaadin.terminal.gwt.widgetsetutils.ClassPathExplorer", + "com.vaadin.terminal.gwt.widgetsetutils.WidgetMapGenerator", + "com.vaadin.terminal.gwt.widgetsetutils.WidgetSetBuilder", + "com.vaadin.terminal.KeyMapper", "com.vaadin.terminal.Paintable", + "com.vaadin.terminal.PaintException", + "com.vaadin.terminal.PaintTarget", + "com.vaadin.terminal.ParameterHandler", + "com.vaadin.terminal.Resource", "com.vaadin.terminal.Scrollable", + "com.vaadin.terminal.Sizeable", + "com.vaadin.terminal.StreamResource", + "com.vaadin.terminal.SystemError", "com.vaadin.terminal.Terminal", + "com.vaadin.terminal.ThemeResource", + "com.vaadin.terminal.UploadStream", + "com.vaadin.terminal.URIHandler", "com.vaadin.terminal.UserError", + "com.vaadin.terminal.VariableOwner", + "com.vaadin.tools.ReflectTools", + "com.vaadin.tools.WidgetsetCompiler", + "com.vaadin.ui.AbsoluteLayout", "com.vaadin.ui.AbstractComponent", + "com.vaadin.ui.AbstractComponentContainer", + "com.vaadin.ui.AbstractField", "com.vaadin.ui.AbstractLayout", + "com.vaadin.ui.AbstractOrderedLayout", + "com.vaadin.ui.AbstractSelect", "com.vaadin.ui.Accordion", + "com.vaadin.ui.Alignment", "com.vaadin.ui.AlignmentUtils", + "com.vaadin.ui.BaseFieldFactory", "com.vaadin.ui.Button", + "com.vaadin.ui.CheckBox", "com.vaadin.ui.ClientWidget", + "com.vaadin.ui.ComboBox", "com.vaadin.ui.Component", + "com.vaadin.ui.ComponentContainer", "com.vaadin.ui.CssLayout", + "com.vaadin.ui.CustomComponent", "com.vaadin.ui.CustomLayout", + "com.vaadin.ui.DateField", "com.vaadin.ui.DefaultFieldFactory", + "com.vaadin.ui.Embedded", "com.vaadin.ui.ExpandLayout", + "com.vaadin.ui.Field", "com.vaadin.ui.FieldFactory", + "com.vaadin.ui.Form", "com.vaadin.ui.FormFieldFactory", + "com.vaadin.ui.FormLayout", "com.vaadin.ui.GridLayout", + "com.vaadin.ui.HorizontalLayout", "com.vaadin.ui.InlineDateField", + "com.vaadin.ui.Label", "com.vaadin.ui.Layout", + "com.vaadin.ui.Link", "com.vaadin.ui.ListSelect", + "com.vaadin.ui.LoginForm", "com.vaadin.ui.MenuBar", + "com.vaadin.ui.NativeButton", "com.vaadin.ui.NativeSelect", + "com.vaadin.ui.OptionGroup", "com.vaadin.ui.OrderedLayout", + "com.vaadin.ui.Panel", "com.vaadin.ui.PopupDateField", + "com.vaadin.ui.PopupView", "com.vaadin.ui.ProgressIndicator", + "com.vaadin.ui.RichTextArea", "com.vaadin.ui.Select", + "com.vaadin.ui.Slider", "com.vaadin.ui.SplitPanel", + "com.vaadin.ui.Table", "com.vaadin.ui.TableFieldFactory", + "com.vaadin.ui.TabSheet", "com.vaadin.ui.TextField", + "com.vaadin.ui.Tree", "com.vaadin.ui.TwinColSelect", + "com.vaadin.ui.Upload", "com.vaadin.ui.UriFragmentUtility", + "com.vaadin.ui.VerticalLayout", "com.vaadin.ui.Window", + "com.vaadin.util.SerializerHelper", "org.vaadin.test.LastClass" }; + +} diff --git a/tests/server-side/com/vaadin/data/util/AbstractHierarchicalContainerTest.java b/tests/server-side/com/vaadin/data/util/AbstractHierarchicalContainerTest.java index 6ab624b8ff..6bfff90c7b 100644 --- a/tests/server-side/com/vaadin/data/util/AbstractHierarchicalContainerTest.java +++ b/tests/server-side/com/vaadin/data/util/AbstractHierarchicalContainerTest.java @@ -1,256 +1,256 @@ -package com.vaadin.data.util;
-
-import java.util.Collection;
-
-import com.vaadin.data.Container;
-import com.vaadin.data.Container.Hierarchical;
-import com.vaadin.data.Container.Sortable;
-import com.vaadin.data.Item;
-
-public abstract class AbstractHierarchicalContainerTest extends
- AbstractContainerTest {
-
- /**
- * @param container
- * The container to validate
- * @param expectedFirstItemId
- * Expected first item id
- * @param expectedLastItemId
- * Expected last item id
- * @param itemIdInSet
- * An item id that is in the container
- * @param itemIdNotInSet
- * An item id that is not in the container
- * @param checkGetItemNull
- * true if getItem() should return null for itemIdNotInSet, false
- * to skip the check (container.containsId() is checked in any
- * case)
- * @param expectedSize
- * Expected number of items in the container. Not related to
- * hierarchy.
- * @param expectedTraversalSize
- * Expected number of items found when traversing from the roots
- * down to all available nodes.
- * @param expectedRootSize
- * Expected number of root items
- * @param rootsHaveChildren
- * true if all roots have children, false otherwise (skips some
- * asserts)
- */
- protected void validateHierarchicalContainer(Hierarchical container,
- Object expectedFirstItemId, Object expectedLastItemId,
- Object itemIdInSet, Object itemIdNotInSet,
- boolean checkGetItemNull, int expectedSize, int expectedRootSize,
- boolean rootsHaveChildren) {
-
- validateContainer(container, expectedFirstItemId, expectedLastItemId,
- itemIdInSet, itemIdNotInSet, checkGetItemNull, expectedSize);
-
- // rootItemIds
- Collection<?> rootIds = container.rootItemIds();
- assertEquals(expectedRootSize, rootIds.size());
-
- for (Object rootId : rootIds) {
- // All roots must be in container
- assertTrue(container.containsId(rootId));
-
- // All roots must have no parent
- assertNull(container.getParent(rootId));
-
- // all roots must be roots
- assertTrue(container.isRoot(rootId));
-
- if (rootsHaveChildren) {
- // all roots have children allowed in this case
- assertTrue(container.areChildrenAllowed(rootId));
-
- // all roots have children in this case
- Collection<?> children = container.getChildren(rootId);
- assertNotNull(rootId + " should have children", children);
- assertTrue(rootId + " should have children",
- (children.size() > 0));
- // getParent
- for (Object childId : children) {
- assertEquals(container.getParent(childId), rootId);
- }
-
- }
- }
-
- // isRoot should return false for unknown items
- assertFalse(container.isRoot(itemIdNotInSet));
-
- // hasChildren should return false for unknown items
- assertFalse(container.hasChildren(itemIdNotInSet));
-
- // areChildrenAllowed should return false for unknown items
- assertFalse(container.areChildrenAllowed(itemIdNotInSet));
-
- // removeItem of unknown items should return false
- assertFalse(container.removeItem(itemIdNotInSet));
-
- assertEquals(expectedSize, countNodes(container));
-
- validateHierarchy(container);
- }
-
- private int countNodes(Hierarchical container) {
- int totalNodes = 0;
- for (Object rootId : container.rootItemIds()) {
- totalNodes += countNodes(container, rootId);
- }
-
- return totalNodes;
- }
-
- private int countNodes(Hierarchical container, Object itemId) {
- int nodes = 1; // This
- Collection<?> children = container.getChildren(itemId);
- if (children != null) {
- for (Object id : children) {
- nodes += countNodes(container, id);
- }
- }
-
- return nodes;
- }
-
- private void validateHierarchy(Hierarchical container) {
- for (Object rootId : container.rootItemIds()) {
- validateHierarchy(container, rootId, null);
- }
- }
-
- private void validateHierarchy(Hierarchical container, Object itemId,
- Object parentId) {
- Collection<?> children = container.getChildren(itemId);
-
- // getParent
- assertEquals(container.getParent(itemId), parentId);
-
- if (!container.areChildrenAllowed(itemId)) {
- // If no children is allowed the item should have no children
- assertFalse(container.hasChildren(itemId));
- assertTrue(children == null || children.size() == 0);
-
- return;
- }
- if (children != null) {
- for (Object id : children) {
- validateHierarchy(container, id, itemId);
- }
- }
- }
-
- protected void testHierarchicalContainer(Container.Hierarchical container) {
- initializeContainer(container);
-
- int packages = 21 + 3;
- int expectedSize = sampleData.length + packages;
- validateHierarchicalContainer(container, "com",
- "org.vaadin.test.LastClass",
- "com.vaadin.terminal.ApplicationResource", "blah", true,
- expectedSize, 2, true);
-
- }
-
- protected void testHierarchicalSorting(Container.Hierarchical container) {
- Container.Sortable sortable = (Sortable) container;
-
- initializeContainer(container);
-
- // Must be able to sort based on PROP1 and PROP2 for this test
- assertTrue(sortable.getSortableContainerPropertyIds().contains(
- FULLY_QUALIFIED_NAME));
- assertTrue(sortable.getSortableContainerPropertyIds().contains(
- REVERSE_FULLY_QUALIFIED_NAME));
-
- sortable.sort(new Object[] { FULLY_QUALIFIED_NAME },
- new boolean[] { true });
-
- int packages = 21 + 3;
- int expectedSize = sampleData.length + packages;
- validateHierarchicalContainer(container, "com",
- "org.vaadin.test.LastClass",
- "com.vaadin.terminal.ApplicationResource", "blah", true,
- expectedSize, 2, true);
-
- sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME },
- new boolean[] { true });
-
- validateHierarchicalContainer(container,
- "com.vaadin.terminal.gwt.server.ApplicationPortlet2",
- "com.vaadin.data.util.ObjectProperty",
- "com.vaadin.terminal.ApplicationResource", "blah", true,
- expectedSize, 2, true);
-
- }
-
- protected void initializeContainer(Container.Hierarchical container) {
- container.removeAllItems();
- Object[] propertyIds = container.getContainerPropertyIds().toArray();
- for (Object propertyId : propertyIds) {
- container.removeContainerProperty(propertyId);
- }
-
- container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, "");
- container.addContainerProperty(SIMPLE_NAME, String.class, "");
- container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME,
- String.class, null);
- container.addContainerProperty(ID_NUMBER, Integer.class, null);
-
- for (int i = 0; i < sampleData.length; i++) {
- String id = sampleData[i];
-
- // Add path as parent
- String paths[] = id.split("\\.");
- String path = paths[0];
- // Adds "com" and other items multiple times so should return null
- // for all but the first time
- if (container.addItem(path) != null) {
- assertTrue(container.setChildrenAllowed(path, false));
- Item item = container.getItem(path);
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path);
- item.getItemProperty(SIMPLE_NAME).setValue(getSimpleName(path));
- item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue(
- reverse(path));
- item.getItemProperty(ID_NUMBER).setValue(1);
- }
- for (int j = 1; j < paths.length; j++) {
- String parent = path;
- path = path + "." + paths[j];
-
- // Adds "com" and other items multiple times so should return
- // null for all but the first time
- if (container.addItem(path) != null) {
- assertTrue(container.setChildrenAllowed(path, false));
-
- Item item = container.getItem(path);
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path);
- item.getItemProperty(SIMPLE_NAME).setValue(
- getSimpleName(path));
- item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME)
- .setValue(reverse(path));
- item.getItemProperty(ID_NUMBER).setValue(1);
-
- }
- assertTrue(container.setChildrenAllowed(parent, true));
- assertTrue(
- "Failed to set " + parent + " as parent for " + path,
- container.setParent(path, parent));
- }
-
- Item item = container.getItem(id);
- assertNotNull(item);
- String parent = id.substring(0, id.lastIndexOf('.'));
- assertTrue(container.setParent(id, parent));
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]);
- item.getItemProperty(SIMPLE_NAME).setValue(
- getSimpleName(sampleData[i]));
- item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue(
- reverse(sampleData[i]));
- item.getItemProperty(ID_NUMBER).setValue(i % 2);
- }
- }
-
-}
+package com.vaadin.data.util; + +import java.util.Collection; + +import com.vaadin.data.Container; +import com.vaadin.data.Container.Hierarchical; +import com.vaadin.data.Container.Sortable; +import com.vaadin.data.Item; + +public abstract class AbstractHierarchicalContainerTest extends + AbstractContainerTest { + + /** + * @param container + * The container to validate + * @param expectedFirstItemId + * Expected first item id + * @param expectedLastItemId + * Expected last item id + * @param itemIdInSet + * An item id that is in the container + * @param itemIdNotInSet + * An item id that is not in the container + * @param checkGetItemNull + * true if getItem() should return null for itemIdNotInSet, false + * to skip the check (container.containsId() is checked in any + * case) + * @param expectedSize + * Expected number of items in the container. Not related to + * hierarchy. + * @param expectedTraversalSize + * Expected number of items found when traversing from the roots + * down to all available nodes. + * @param expectedRootSize + * Expected number of root items + * @param rootsHaveChildren + * true if all roots have children, false otherwise (skips some + * asserts) + */ + protected void validateHierarchicalContainer(Hierarchical container, + Object expectedFirstItemId, Object expectedLastItemId, + Object itemIdInSet, Object itemIdNotInSet, + boolean checkGetItemNull, int expectedSize, int expectedRootSize, + boolean rootsHaveChildren) { + + validateContainer(container, expectedFirstItemId, expectedLastItemId, + itemIdInSet, itemIdNotInSet, checkGetItemNull, expectedSize); + + // rootItemIds + Collection<?> rootIds = container.rootItemIds(); + assertEquals(expectedRootSize, rootIds.size()); + + for (Object rootId : rootIds) { + // All roots must be in container + assertTrue(container.containsId(rootId)); + + // All roots must have no parent + assertNull(container.getParent(rootId)); + + // all roots must be roots + assertTrue(container.isRoot(rootId)); + + if (rootsHaveChildren) { + // all roots have children allowed in this case + assertTrue(container.areChildrenAllowed(rootId)); + + // all roots have children in this case + Collection<?> children = container.getChildren(rootId); + assertNotNull(rootId + " should have children", children); + assertTrue(rootId + " should have children", + (children.size() > 0)); + // getParent + for (Object childId : children) { + assertEquals(container.getParent(childId), rootId); + } + + } + } + + // isRoot should return false for unknown items + assertFalse(container.isRoot(itemIdNotInSet)); + + // hasChildren should return false for unknown items + assertFalse(container.hasChildren(itemIdNotInSet)); + + // areChildrenAllowed should return false for unknown items + assertFalse(container.areChildrenAllowed(itemIdNotInSet)); + + // removeItem of unknown items should return false + assertFalse(container.removeItem(itemIdNotInSet)); + + assertEquals(expectedSize, countNodes(container)); + + validateHierarchy(container); + } + + private int countNodes(Hierarchical container) { + int totalNodes = 0; + for (Object rootId : container.rootItemIds()) { + totalNodes += countNodes(container, rootId); + } + + return totalNodes; + } + + private int countNodes(Hierarchical container, Object itemId) { + int nodes = 1; // This + Collection<?> children = container.getChildren(itemId); + if (children != null) { + for (Object id : children) { + nodes += countNodes(container, id); + } + } + + return nodes; + } + + private void validateHierarchy(Hierarchical container) { + for (Object rootId : container.rootItemIds()) { + validateHierarchy(container, rootId, null); + } + } + + private void validateHierarchy(Hierarchical container, Object itemId, + Object parentId) { + Collection<?> children = container.getChildren(itemId); + + // getParent + assertEquals(container.getParent(itemId), parentId); + + if (!container.areChildrenAllowed(itemId)) { + // If no children is allowed the item should have no children + assertFalse(container.hasChildren(itemId)); + assertTrue(children == null || children.size() == 0); + + return; + } + if (children != null) { + for (Object id : children) { + validateHierarchy(container, id, itemId); + } + } + } + + protected void testHierarchicalContainer(Container.Hierarchical container) { + initializeContainer(container); + + int packages = 21 + 3; + int expectedSize = sampleData.length + packages; + validateHierarchicalContainer(container, "com", + "org.vaadin.test.LastClass", + "com.vaadin.terminal.ApplicationResource", "blah", true, + expectedSize, 2, true); + + } + + protected void testHierarchicalSorting(Container.Hierarchical container) { + Container.Sortable sortable = (Sortable) container; + + initializeContainer(container); + + // Must be able to sort based on PROP1 and PROP2 for this test + assertTrue(sortable.getSortableContainerPropertyIds().contains( + FULLY_QUALIFIED_NAME)); + assertTrue(sortable.getSortableContainerPropertyIds().contains( + REVERSE_FULLY_QUALIFIED_NAME)); + + sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + int packages = 21 + 3; + int expectedSize = sampleData.length + packages; + validateHierarchicalContainer(container, "com", + "org.vaadin.test.LastClass", + "com.vaadin.terminal.ApplicationResource", "blah", true, + expectedSize, 2, true); + + sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateHierarchicalContainer(container, + "com.vaadin.terminal.gwt.server.ApplicationPortlet2", + "com.vaadin.data.util.ObjectProperty", + "com.vaadin.terminal.ApplicationResource", "blah", true, + expectedSize, 2, true); + + } + + protected void initializeContainer(Container.Hierarchical container) { + container.removeAllItems(); + Object[] propertyIds = container.getContainerPropertyIds().toArray(); + for (Object propertyId : propertyIds) { + container.removeContainerProperty(propertyId); + } + + container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, ""); + container.addContainerProperty(SIMPLE_NAME, String.class, ""); + container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME, + String.class, null); + container.addContainerProperty(ID_NUMBER, Integer.class, null); + + for (int i = 0; i < sampleData.length; i++) { + String id = sampleData[i]; + + // Add path as parent + String paths[] = id.split("\\."); + String path = paths[0]; + // Adds "com" and other items multiple times so should return null + // for all but the first time + if (container.addItem(path) != null) { + assertTrue(container.setChildrenAllowed(path, false)); + Item item = container.getItem(path); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path); + item.getItemProperty(SIMPLE_NAME).setValue(getSimpleName(path)); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( + reverse(path)); + item.getItemProperty(ID_NUMBER).setValue(1); + } + for (int j = 1; j < paths.length; j++) { + String parent = path; + path = path + "." + paths[j]; + + // Adds "com" and other items multiple times so should return + // null for all but the first time + if (container.addItem(path) != null) { + assertTrue(container.setChildrenAllowed(path, false)); + + Item item = container.getItem(path); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path); + item.getItemProperty(SIMPLE_NAME).setValue( + getSimpleName(path)); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME) + .setValue(reverse(path)); + item.getItemProperty(ID_NUMBER).setValue(1); + + } + assertTrue(container.setChildrenAllowed(parent, true)); + assertTrue( + "Failed to set " + parent + " as parent for " + path, + container.setParent(path, parent)); + } + + Item item = container.getItem(id); + assertNotNull(item); + String parent = id.substring(0, id.lastIndexOf('.')); + assertTrue(container.setParent(id, parent)); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]); + item.getItemProperty(SIMPLE_NAME).setValue( + getSimpleName(sampleData[i])); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( + reverse(sampleData[i])); + item.getItemProperty(ID_NUMBER).setValue(i % 2); + } + } + +} diff --git a/tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java b/tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java index a934b40dce..11676099e6 100644 --- a/tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java +++ b/tests/server-side/com/vaadin/data/util/ObjectPropertyTest.java @@ -1,99 +1,99 @@ -package com.vaadin.data.util;
-
-import junit.framework.TestCase;
-
-import org.junit.Assert;
-
-import com.vaadin.data.util.ObjectProperty;
-
-public class ObjectPropertyTest extends TestCase {
-
- public static class TestSuperClass {
- private String name;
-
- public TestSuperClass(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public String toString() {
- return getName();
- }
- }
-
- public static class TestSubClass extends TestSuperClass {
- public TestSubClass(String name) {
- super("Subclass: " + name);
- }
- }
-
- private TestSuperClass super1 = new TestSuperClass("super1");
- private TestSubClass sub1 = new TestSubClass("sub1");
-
- public void testSimple() {
- ObjectProperty<TestSuperClass> prop1 = new ObjectProperty<TestSuperClass>(
- super1, TestSuperClass.class);
- Assert.assertEquals("super1", prop1.getValue().getName());
- prop1 = new ObjectProperty<TestSuperClass>(super1);
- Assert.assertEquals("super1", prop1.getValue().getName());
-
- ObjectProperty<TestSubClass> prop2 = new ObjectProperty<TestSubClass>(
- sub1, TestSubClass.class);
- Assert.assertEquals("Subclass: sub1", prop2.getValue().getName());
- prop2 = new ObjectProperty<TestSubClass>(sub1);
- Assert.assertEquals("Subclass: sub1", prop2.getValue().getName());
- }
-
- public void testSetValueObjectSuper() {
- ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(
- super1, TestSuperClass.class);
- Assert.assertEquals("super1", prop.getValue().getName());
- prop.setValue(new TestSuperClass("super2"));
- Assert.assertEquals("super1", super1.getName());
- Assert.assertEquals("super2", prop.getValue().getName());
- }
-
- public void testSetValueObjectSub() {
- ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>(
- sub1, TestSubClass.class);
- Assert.assertEquals("Subclass: sub1", prop.getValue().getName());
- prop.setValue(new TestSubClass("sub2"));
- Assert.assertEquals("Subclass: sub1", sub1.getName());
- Assert.assertEquals("Subclass: sub2", prop.getValue().getName());
- }
-
- public void testSetValueStringSuper() {
- ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(
- super1, TestSuperClass.class);
- Assert.assertEquals("super1", prop.getValue().getName());
- prop.setValue("super2");
- Assert.assertEquals("super1", super1.getName());
- Assert.assertEquals("super2", prop.getValue().getName());
- }
-
- public void testSetValueStringSub() {
- ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>(
- sub1, TestSubClass.class);
- Assert.assertEquals("Subclass: sub1", prop.getValue().getName());
- prop.setValue("sub2");
- Assert.assertEquals("Subclass: sub1", sub1.getName());
- Assert.assertEquals("Subclass: sub2", prop.getValue().getName());
- }
-
- public void testMixedGenerics() {
- ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>(
- sub1);
- Assert.assertEquals("Subclass: sub1", prop.getValue().getName());
- Assert.assertEquals(prop.getType(), TestSubClass.class);
- // create correct subclass based on the runtime type of the instance
- // given to ObjectProperty constructor, which is a subclass of the type
- // parameter
- prop.setValue("sub2");
- Assert.assertEquals("Subclass: sub2", prop.getValue().getName());
- }
-
-}
+package com.vaadin.data.util; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.data.util.ObjectProperty; + +public class ObjectPropertyTest extends TestCase { + + public static class TestSuperClass { + private String name; + + public TestSuperClass(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return getName(); + } + } + + public static class TestSubClass extends TestSuperClass { + public TestSubClass(String name) { + super("Subclass: " + name); + } + } + + private TestSuperClass super1 = new TestSuperClass("super1"); + private TestSubClass sub1 = new TestSubClass("sub1"); + + public void testSimple() { + ObjectProperty<TestSuperClass> prop1 = new ObjectProperty<TestSuperClass>( + super1, TestSuperClass.class); + Assert.assertEquals("super1", prop1.getValue().getName()); + prop1 = new ObjectProperty<TestSuperClass>(super1); + Assert.assertEquals("super1", prop1.getValue().getName()); + + ObjectProperty<TestSubClass> prop2 = new ObjectProperty<TestSubClass>( + sub1, TestSubClass.class); + Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); + prop2 = new ObjectProperty<TestSubClass>(sub1); + Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); + } + + public void testSetValueObjectSuper() { + ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>( + super1, TestSuperClass.class); + Assert.assertEquals("super1", prop.getValue().getName()); + prop.setValue(new TestSuperClass("super2")); + Assert.assertEquals("super1", super1.getName()); + Assert.assertEquals("super2", prop.getValue().getName()); + } + + public void testSetValueObjectSub() { + ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>( + sub1, TestSubClass.class); + Assert.assertEquals("Subclass: sub1", prop.getValue().getName()); + prop.setValue(new TestSubClass("sub2")); + Assert.assertEquals("Subclass: sub1", sub1.getName()); + Assert.assertEquals("Subclass: sub2", prop.getValue().getName()); + } + + public void testSetValueStringSuper() { + ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>( + super1, TestSuperClass.class); + Assert.assertEquals("super1", prop.getValue().getName()); + prop.setValue("super2"); + Assert.assertEquals("super1", super1.getName()); + Assert.assertEquals("super2", prop.getValue().getName()); + } + + public void testSetValueStringSub() { + ObjectProperty<TestSubClass> prop = new ObjectProperty<TestSubClass>( + sub1, TestSubClass.class); + Assert.assertEquals("Subclass: sub1", prop.getValue().getName()); + prop.setValue("sub2"); + Assert.assertEquals("Subclass: sub1", sub1.getName()); + Assert.assertEquals("Subclass: sub2", prop.getValue().getName()); + } + + public void testMixedGenerics() { + ObjectProperty<TestSuperClass> prop = new ObjectProperty<TestSuperClass>( + sub1); + Assert.assertEquals("Subclass: sub1", prop.getValue().getName()); + Assert.assertEquals(prop.getType(), TestSubClass.class); + // create correct subclass based on the runtime type of the instance + // given to ObjectProperty constructor, which is a subclass of the type + // parameter + prop.setValue("sub2"); + Assert.assertEquals("Subclass: sub2", prop.getValue().getName()); + } + +} diff --git a/tests/server-side/com/vaadin/data/util/TestContainerHierarchicalWrapper.java b/tests/server-side/com/vaadin/data/util/TestContainerHierarchicalWrapper.java index ec0fe1de37..ebe604ff3a 100644 --- a/tests/server-side/com/vaadin/data/util/TestContainerHierarchicalWrapper.java +++ b/tests/server-side/com/vaadin/data/util/TestContainerHierarchicalWrapper.java @@ -1,45 +1,45 @@ -package com.vaadin.data.util;
-
-import java.util.Collection;
-
-import com.vaadin.data.util.ContainerHierarchicalWrapper;
-import com.vaadin.data.util.IndexedContainer;
-
-public class TestContainerHierarchicalWrapper extends
- AbstractHierarchicalContainerTest {
-
- public void testBasicOperations() {
- testBasicContainerOperations(new ContainerHierarchicalWrapper(
- new IndexedContainer()));
- }
-
- public void testHierarchicalContainer() {
- testHierarchicalContainer(new ContainerHierarchicalWrapper(
- new IndexedContainer()));
- }
-
- public void testRemoveSubtree() {
- testRemoveHierarchicalWrapperSubtree(new ContainerHierarchicalWrapper(
- new IndexedContainer()));
- }
-
- protected void testRemoveHierarchicalWrapperSubtree(
- ContainerHierarchicalWrapper container) {
- initializeContainer(container);
-
- // remove root item
- container.removeItemRecursively("org");
-
- int packages = 21 + 3 - 3;
- int expectedSize = sampleData.length + packages - 1;
-
- validateContainer(container, "com", "com.vaadin.util.SerializerHelper",
- "com.vaadin.terminal.ApplicationResource", "blah", true,
- expectedSize);
-
- // rootItemIds
- Collection<?> rootIds = container.rootItemIds();
- assertEquals(1, rootIds.size());
- }
-
-}
+package com.vaadin.data.util; + +import java.util.Collection; + +import com.vaadin.data.util.ContainerHierarchicalWrapper; +import com.vaadin.data.util.IndexedContainer; + +public class TestContainerHierarchicalWrapper extends + AbstractHierarchicalContainerTest { + + public void testBasicOperations() { + testBasicContainerOperations(new ContainerHierarchicalWrapper( + new IndexedContainer())); + } + + public void testHierarchicalContainer() { + testHierarchicalContainer(new ContainerHierarchicalWrapper( + new IndexedContainer())); + } + + public void testRemoveSubtree() { + testRemoveHierarchicalWrapperSubtree(new ContainerHierarchicalWrapper( + new IndexedContainer())); + } + + protected void testRemoveHierarchicalWrapperSubtree( + ContainerHierarchicalWrapper container) { + initializeContainer(container); + + // remove root item + container.removeItemRecursively("org"); + + int packages = 21 + 3 - 3; + int expectedSize = sampleData.length + packages - 1; + + validateContainer(container, "com", "com.vaadin.util.SerializerHelper", + "com.vaadin.terminal.ApplicationResource", "blah", true, + expectedSize); + + // rootItemIds + Collection<?> rootIds = container.rootItemIds(); + assertEquals(1, rootIds.size()); + } + +} diff --git a/tests/server-side/com/vaadin/data/util/TestContainerSorting.java b/tests/server-side/com/vaadin/data/util/TestContainerSorting.java index dbfea7d75d..d9a8e6e51c 100644 --- a/tests/server-side/com/vaadin/data/util/TestContainerSorting.java +++ b/tests/server-side/com/vaadin/data/util/TestContainerSorting.java @@ -1,238 +1,238 @@ -package com.vaadin.data.util;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import com.vaadin.data.Container;
-import com.vaadin.data.Item;
-import com.vaadin.data.util.HierarchicalContainer;
-import com.vaadin.data.util.IndexedContainer;
-
-public class TestContainerSorting extends TestCase {
-
- private static final String ITEM_DATA_MINUS2_NULL = "Data -2 null";
- private static final String ITEM_DATA_MINUS2 = "Data -2";
- private static final String ITEM_DATA_MINUS1 = "Data -1";
- private static final String ITEM_DATA_MINUS1_NULL = "Data -1 null";
- private static final String ITEM_ANOTHER_NULL = "Another null";
- private static final String ITEM_STRING_2 = "String 2";
- private static final String ITEM_STRING_NULL2 = "String null";
- private static final String ITEM_STRING_1 = "String 1";
-
- private static final String PROPERTY_INTEGER_NULL2 = "integer-null";
- private static final String PROPERTY_INTEGER_NOT_NULL = "integer-not-null";
- private static final String PROPERTY_STRING_NULL = "string-null";
- private static final String PROPERTY_STRING_ID = "string-not-null";
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- public void testEmptyFilteredIndexedContainer() {
- IndexedContainer ic = new IndexedContainer();
-
- addProperties(ic);
- populate(ic);
-
- ic.addContainerFilter(PROPERTY_STRING_ID, "aasdfasdfasdf", true, false);
- ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });
-
- }
-
- public void testFilteredIndexedContainer() {
- IndexedContainer ic = new IndexedContainer();
-
- addProperties(ic);
- populate(ic);
-
- ic.addContainerFilter(PROPERTY_STRING_ID, "a", true, false);
- ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });
- verifyOrder(ic,
- new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1,
- ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2,
- ITEM_DATA_MINUS2_NULL, });
- }
-
- public void testIndexedContainer() {
- IndexedContainer ic = new IndexedContainer();
-
- addProperties(ic);
- populate(ic);
-
- ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true });
- verifyOrder(ic, new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1,
- ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL,
- ITEM_STRING_1, ITEM_STRING_2, ITEM_STRING_NULL2 });
-
- ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL,
- PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] {
- true, false, true });
- verifyOrder(ic, new String[] { ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL,
- ITEM_DATA_MINUS1, ITEM_DATA_MINUS1_NULL, ITEM_ANOTHER_NULL,
- ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 });
-
- ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL,
- PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] {
- true, true, true });
- verifyOrder(ic, new String[] { ITEM_DATA_MINUS2_NULL, ITEM_DATA_MINUS2,
- ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS1, ITEM_ANOTHER_NULL,
- ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 });
-
- }
-
- public void testHierarchicalContainer() {
- HierarchicalContainer hc = new HierarchicalContainer();
- populateContainer(hc);
- hc.sort(new Object[] { "name" }, new boolean[] { true });
- verifyOrder(hc, new String[] { "Audi", "C++", "Call of Duty", "Cars",
- "English", "Fallout", "Finnish", "Ford", "Games", "Java",
- "Might and Magic", "Natural languages", "PHP",
- "Programming languages", "Python", "Red Alert", "Swedish",
- "Toyota", "Volvo" });
- assertArrays(
- hc.rootItemIds().toArray(),
- new Integer[] { nameToId.get("Cars"), nameToId.get("Games"),
- nameToId.get("Natural languages"),
- nameToId.get("Programming languages") });
- assertArrays(
- hc.getChildren(nameToId.get("Games")).toArray(),
- new Integer[] { nameToId.get("Call of Duty"),
- nameToId.get("Fallout"),
- nameToId.get("Might and Magic"),
- nameToId.get("Red Alert") });
- }
-
- private static void populateContainer(HierarchicalContainer container) {
- container.addContainerProperty("name", String.class, null);
-
- addItem(container, "Games", null);
- addItem(container, "Call of Duty", "Games");
- addItem(container, "Might and Magic", "Games");
- addItem(container, "Fallout", "Games");
- addItem(container, "Red Alert", "Games");
-
- addItem(container, "Cars", null);
- addItem(container, "Toyota", "Cars");
- addItem(container, "Volvo", "Cars");
- addItem(container, "Audi", "Cars");
- addItem(container, "Ford", "Cars");
-
- addItem(container, "Natural languages", null);
- addItem(container, "Swedish", "Natural languages");
- addItem(container, "English", "Natural languages");
- addItem(container, "Finnish", "Natural languages");
-
- addItem(container, "Programming languages", null);
- addItem(container, "C++", "Programming languages");
- addItem(container, "PHP", "Programming languages");
- addItem(container, "Java", "Programming languages");
- addItem(container, "Python", "Programming languages");
-
- }
-
- private static int index = 0;
- private static Map<String, Integer> nameToId = new HashMap<String, Integer>();
- private static Map<Integer, String> idToName = new HashMap<Integer, String>();
-
- public static void addItem(IndexedContainer container, String string,
- String parent) {
- nameToId.put(string, index);
- idToName.put(index, string);
-
- Item item = container.addItem(index);
- item.getItemProperty("name").setValue(string);
-
- if (parent != null && container instanceof HierarchicalContainer) {
- ((HierarchicalContainer) container).setParent(index,
- nameToId.get(parent));
- }
-
- index++;
- }
-
- private void verifyOrder(Container.Sortable ic, Object[] idOrder) {
- int size = ic.size();
- Object[] actual = new Object[size];
- Iterator<?> i = ic.getItemIds().iterator();
- int index = 0;
- while (i.hasNext()) {
- Object o = i.next();
- if (o.getClass() == Integer.class
- && idOrder[index].getClass() == String.class) {
- o = idToName.get(o);
- }
- actual[index++] = o;
- }
-
- assertArrays(actual, idOrder);
-
- }
-
- private void assertArrays(Object[] actualObjects, Object[] expectedObjects) {
- assertEquals(
- "Actual contains a different number of values than was expected",
- expectedObjects.length, actualObjects.length);
-
- for (int i = 0; i < actualObjects.length; i++) {
- Object actual = actualObjects[i];
- Object expected = expectedObjects[i];
-
- assertEquals("Item[" + i + "] does not match", expected, actual);
- }
-
- }
-
- private void populate(IndexedContainer ic) {
- addItem(ic, ITEM_STRING_1, ITEM_STRING_1, 1, 1);
- addItem(ic, ITEM_STRING_NULL2, null, 0, null);
- addItem(ic, ITEM_STRING_2, ITEM_STRING_2, 2, 2);
- addItem(ic, ITEM_ANOTHER_NULL, null, 0, null);
- addItem(ic, ITEM_DATA_MINUS1, ITEM_DATA_MINUS1, -1, -1);
- addItem(ic, ITEM_DATA_MINUS1_NULL, null, -1, null);
- addItem(ic, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2, -2, -2);
- addItem(ic, ITEM_DATA_MINUS2_NULL, null, -2, null);
- }
-
- private Item addItem(Container ic, String id, String string_null,
- int integer, Integer integer_null) {
- Item i = ic.addItem(id);
- i.getItemProperty(PROPERTY_STRING_ID).setValue(id);
- i.getItemProperty(PROPERTY_STRING_NULL).setValue(string_null);
- i.getItemProperty(PROPERTY_INTEGER_NOT_NULL).setValue(integer);
- i.getItemProperty(PROPERTY_INTEGER_NULL2).setValue(integer_null);
-
- return i;
- }
-
- private void addProperties(IndexedContainer ic) {
- ic.addContainerProperty("id", String.class, null);
- ic.addContainerProperty(PROPERTY_STRING_ID, String.class, "");
- ic.addContainerProperty(PROPERTY_STRING_NULL, String.class, null);
- ic.addContainerProperty(PROPERTY_INTEGER_NULL2, Integer.class, null);
- ic.addContainerProperty(PROPERTY_INTEGER_NOT_NULL, Integer.class, 0);
- ic.addContainerProperty("comparable-null", Integer.class, 0);
- }
-
- public class MyObject implements Comparable<MyObject> {
- private String data;
-
- public int compareTo(MyObject o) {
- if (o == null) {
- return 1;
- }
-
- if (o.data == null) {
- return data == null ? 0 : 1;
- } else if (data == null) {
- return -1;
- } else {
- return data.compareTo(o.data);
- }
- }
- }
-
-}
+package com.vaadin.data.util; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import junit.framework.TestCase; + +import com.vaadin.data.Container; +import com.vaadin.data.Item; +import com.vaadin.data.util.HierarchicalContainer; +import com.vaadin.data.util.IndexedContainer; + +public class TestContainerSorting extends TestCase { + + private static final String ITEM_DATA_MINUS2_NULL = "Data -2 null"; + private static final String ITEM_DATA_MINUS2 = "Data -2"; + private static final String ITEM_DATA_MINUS1 = "Data -1"; + private static final String ITEM_DATA_MINUS1_NULL = "Data -1 null"; + private static final String ITEM_ANOTHER_NULL = "Another null"; + private static final String ITEM_STRING_2 = "String 2"; + private static final String ITEM_STRING_NULL2 = "String null"; + private static final String ITEM_STRING_1 = "String 1"; + + private static final String PROPERTY_INTEGER_NULL2 = "integer-null"; + private static final String PROPERTY_INTEGER_NOT_NULL = "integer-not-null"; + private static final String PROPERTY_STRING_NULL = "string-null"; + private static final String PROPERTY_STRING_ID = "string-not-null"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testEmptyFilteredIndexedContainer() { + IndexedContainer ic = new IndexedContainer(); + + addProperties(ic); + populate(ic); + + ic.addContainerFilter(PROPERTY_STRING_ID, "aasdfasdfasdf", true, false); + ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); + + } + + public void testFilteredIndexedContainer() { + IndexedContainer ic = new IndexedContainer(); + + addProperties(ic); + populate(ic); + + ic.addContainerFilter(PROPERTY_STRING_ID, "a", true, false); + ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); + verifyOrder(ic, + new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1, + ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, + ITEM_DATA_MINUS2_NULL, }); + } + + public void testIndexedContainer() { + IndexedContainer ic = new IndexedContainer(); + + addProperties(ic); + populate(ic); + + ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); + verifyOrder(ic, new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1, + ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL, + ITEM_STRING_1, ITEM_STRING_2, ITEM_STRING_NULL2 }); + + ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL, + PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] { + true, false, true }); + verifyOrder(ic, new String[] { ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL, + ITEM_DATA_MINUS1, ITEM_DATA_MINUS1_NULL, ITEM_ANOTHER_NULL, + ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 }); + + ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL, + PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] { + true, true, true }); + verifyOrder(ic, new String[] { ITEM_DATA_MINUS2_NULL, ITEM_DATA_MINUS2, + ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS1, ITEM_ANOTHER_NULL, + ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 }); + + } + + public void testHierarchicalContainer() { + HierarchicalContainer hc = new HierarchicalContainer(); + populateContainer(hc); + hc.sort(new Object[] { "name" }, new boolean[] { true }); + verifyOrder(hc, new String[] { "Audi", "C++", "Call of Duty", "Cars", + "English", "Fallout", "Finnish", "Ford", "Games", "Java", + "Might and Magic", "Natural languages", "PHP", + "Programming languages", "Python", "Red Alert", "Swedish", + "Toyota", "Volvo" }); + assertArrays( + hc.rootItemIds().toArray(), + new Integer[] { nameToId.get("Cars"), nameToId.get("Games"), + nameToId.get("Natural languages"), + nameToId.get("Programming languages") }); + assertArrays( + hc.getChildren(nameToId.get("Games")).toArray(), + new Integer[] { nameToId.get("Call of Duty"), + nameToId.get("Fallout"), + nameToId.get("Might and Magic"), + nameToId.get("Red Alert") }); + } + + private static void populateContainer(HierarchicalContainer container) { + container.addContainerProperty("name", String.class, null); + + addItem(container, "Games", null); + addItem(container, "Call of Duty", "Games"); + addItem(container, "Might and Magic", "Games"); + addItem(container, "Fallout", "Games"); + addItem(container, "Red Alert", "Games"); + + addItem(container, "Cars", null); + addItem(container, "Toyota", "Cars"); + addItem(container, "Volvo", "Cars"); + addItem(container, "Audi", "Cars"); + addItem(container, "Ford", "Cars"); + + addItem(container, "Natural languages", null); + addItem(container, "Swedish", "Natural languages"); + addItem(container, "English", "Natural languages"); + addItem(container, "Finnish", "Natural languages"); + + addItem(container, "Programming languages", null); + addItem(container, "C++", "Programming languages"); + addItem(container, "PHP", "Programming languages"); + addItem(container, "Java", "Programming languages"); + addItem(container, "Python", "Programming languages"); + + } + + private static int index = 0; + private static Map<String, Integer> nameToId = new HashMap<String, Integer>(); + private static Map<Integer, String> idToName = new HashMap<Integer, String>(); + + public static void addItem(IndexedContainer container, String string, + String parent) { + nameToId.put(string, index); + idToName.put(index, string); + + Item item = container.addItem(index); + item.getItemProperty("name").setValue(string); + + if (parent != null && container instanceof HierarchicalContainer) { + ((HierarchicalContainer) container).setParent(index, + nameToId.get(parent)); + } + + index++; + } + + private void verifyOrder(Container.Sortable ic, Object[] idOrder) { + int size = ic.size(); + Object[] actual = new Object[size]; + Iterator<?> i = ic.getItemIds().iterator(); + int index = 0; + while (i.hasNext()) { + Object o = i.next(); + if (o.getClass() == Integer.class + && idOrder[index].getClass() == String.class) { + o = idToName.get(o); + } + actual[index++] = o; + } + + assertArrays(actual, idOrder); + + } + + private void assertArrays(Object[] actualObjects, Object[] expectedObjects) { + assertEquals( + "Actual contains a different number of values than was expected", + expectedObjects.length, actualObjects.length); + + for (int i = 0; i < actualObjects.length; i++) { + Object actual = actualObjects[i]; + Object expected = expectedObjects[i]; + + assertEquals("Item[" + i + "] does not match", expected, actual); + } + + } + + private void populate(IndexedContainer ic) { + addItem(ic, ITEM_STRING_1, ITEM_STRING_1, 1, 1); + addItem(ic, ITEM_STRING_NULL2, null, 0, null); + addItem(ic, ITEM_STRING_2, ITEM_STRING_2, 2, 2); + addItem(ic, ITEM_ANOTHER_NULL, null, 0, null); + addItem(ic, ITEM_DATA_MINUS1, ITEM_DATA_MINUS1, -1, -1); + addItem(ic, ITEM_DATA_MINUS1_NULL, null, -1, null); + addItem(ic, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2, -2, -2); + addItem(ic, ITEM_DATA_MINUS2_NULL, null, -2, null); + } + + private Item addItem(Container ic, String id, String string_null, + int integer, Integer integer_null) { + Item i = ic.addItem(id); + i.getItemProperty(PROPERTY_STRING_ID).setValue(id); + i.getItemProperty(PROPERTY_STRING_NULL).setValue(string_null); + i.getItemProperty(PROPERTY_INTEGER_NOT_NULL).setValue(integer); + i.getItemProperty(PROPERTY_INTEGER_NULL2).setValue(integer_null); + + return i; + } + + private void addProperties(IndexedContainer ic) { + ic.addContainerProperty("id", String.class, null); + ic.addContainerProperty(PROPERTY_STRING_ID, String.class, ""); + ic.addContainerProperty(PROPERTY_STRING_NULL, String.class, null); + ic.addContainerProperty(PROPERTY_INTEGER_NULL2, Integer.class, null); + ic.addContainerProperty(PROPERTY_INTEGER_NOT_NULL, Integer.class, 0); + ic.addContainerProperty("comparable-null", Integer.class, 0); + } + + public class MyObject implements Comparable<MyObject> { + private String data; + + public int compareTo(MyObject o) { + if (o == null) { + return 1; + } + + if (o.data == null) { + return data == null ? 0 : 1; + } else if (data == null) { + return -1; + } else { + return data.compareTo(o.data); + } + } + } + +} diff --git a/tests/server-side/com/vaadin/data/util/TestHierarchicalContainer.java b/tests/server-side/com/vaadin/data/util/TestHierarchicalContainer.java index 5bbb72fe36..60894dbe6f 100644 --- a/tests/server-side/com/vaadin/data/util/TestHierarchicalContainer.java +++ b/tests/server-side/com/vaadin/data/util/TestHierarchicalContainer.java @@ -1,269 +1,269 @@ -package com.vaadin.data.util;
-
-import com.vaadin.data.Container.Filter;
-import com.vaadin.data.Item;
-import com.vaadin.data.util.HierarchicalContainer;
-
-public class TestHierarchicalContainer extends
- AbstractHierarchicalContainerTest {
-
- public void testBasicOperations() {
- testBasicContainerOperations(new HierarchicalContainer());
- }
-
- public void testFiltering() {
- testContainerFiltering(new HierarchicalContainer());
- }
-
- public void testSorting() {
- testContainerSorting(new HierarchicalContainer());
- }
-
- public void testOrdered() {
- testContainerOrdered(new HierarchicalContainer());
- }
-
- public void testHierarchicalSorting() {
- testHierarchicalSorting(new HierarchicalContainer());
- }
-
- public void testSortingAndFiltering() {
- testContainerSortingAndFiltering(new HierarchicalContainer());
- }
-
- public void testRemovingItemsFromFilteredContainer() {
- HierarchicalContainer container = new HierarchicalContainer();
- initializeContainer(container);
- container.setIncludeParentsWhenFiltering(true);
- container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false);
- Object p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertEquals("com.vaadin.ui", p1);
-
- container.removeItem("com.vaadin.ui.TabSheet");
- // Parent for the removed item must be null because the item is no
- // longer in the container
- p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertNull("Parent should be null, is " + p1, p1);
-
- container.removeAllItems();
- p1 = container.getParent("com.vaadin.terminal.gwt.client.Focusable");
- assertNull("Parent should be null, is " + p1, p1);
-
- }
-
- public void testParentWhenRemovingFilterFromContainer() {
- HierarchicalContainer container = new HierarchicalContainer();
- initializeContainer(container);
- container.setIncludeParentsWhenFiltering(true);
- container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false);
- Object p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertEquals("com.vaadin.ui", p1);
- p1 = container
- .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar");
- assertNull(p1);
- container.removeAllContainerFilters();
- p1 = container
- .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar");
- assertEquals("com.vaadin.terminal.gwt.client.ui", p1);
-
- }
-
- public void testChangeParentInFilteredContainer() {
- HierarchicalContainer container = new HierarchicalContainer();
- initializeContainer(container);
- container.setIncludeParentsWhenFiltering(true);
- container.addContainerFilter(FULLY_QUALIFIED_NAME, "Tab", false, false);
-
- // Change parent of filtered item
- Object p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertEquals("com.vaadin.ui", p1);
- container.setParent("com.vaadin.ui.TabSheet", "com.vaadin");
- p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertEquals("com.vaadin", p1);
- container.setParent("com.vaadin.ui.TabSheet", "com");
- p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertEquals("com", p1);
- container.setParent("com.vaadin.ui.TabSheet", null);
- p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertNull(p1);
-
- // root -> non-root
- container.setParent("com.vaadin.ui.TabSheet", "com");
- p1 = container.getParent("com.vaadin.ui.TabSheet");
- assertEquals("com", p1);
-
- }
-
- public void testHierarchicalFilteringWithParents() {
- HierarchicalContainer container = new HierarchicalContainer();
- initializeContainer(container);
- container.setIncludeParentsWhenFiltering(true);
-
- // Filter by "contains ab"
- container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false);
-
- // 20 items match the filters and the have 8 parents that should also be
- // included
- // only one root "com" should exist
- // filtered
- int expectedSize = 29;
- int expectedRoots = 1;
-
- validateHierarchicalContainer(container, "com",
- "com.vaadin.ui.TabSheet",
- "com.vaadin.terminal.gwt.client.Focusable", "blah", true,
- expectedSize, expectedRoots, true);
-
- // only include .gwt.client classes
- container.removeAllContainerFilters();
- container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.",
- false, false);
-
- int packages = 6;
- int classes = 112;
-
- expectedSize = packages + classes;
- expectedRoots = 1;
-
- validateHierarchicalContainer(container, "com",
- "com.vaadin.terminal.gwt.client.WidgetSet",
- "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical",
- "blah", true, expectedSize, expectedRoots, true);
-
- // Additionally remove all without 'm' in the simple name.
- container.addContainerFilter(SIMPLE_NAME, "m", false, false);
-
- expectedSize = 7 + 18;
- expectedRoots = 1;
-
- validateHierarchicalContainer(
- container,
- "com",
- "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility",
- "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer",
- "blah", true, expectedSize, expectedRoots, true);
-
- }
-
- public void testRemoveLastChild() {
- HierarchicalContainer c = new HierarchicalContainer();
-
- c.addItem("root");
- assertEquals(false, c.hasChildren("root"));
-
- c.addItem("child");
- c.setParent("child", "root");
- assertEquals(true, c.hasChildren("root"));
-
- c.removeItem("child");
- assertFalse(c.containsId("child"));
- assertNull(c.getChildren("root"));
- assertNull(c.getChildren("child"));
- assertFalse(c.hasChildren("child"));
- assertFalse(c.hasChildren("root"));
- }
-
- public void testRemoveLastChildFromFiltered() {
- HierarchicalContainer c = new HierarchicalContainer();
-
- c.addItem("root");
- assertEquals(false, c.hasChildren("root"));
-
- c.addItem("child");
- c.setParent("child", "root");
- assertEquals(true, c.hasChildren("root"));
-
- // Dummy filter that does not remove any items
- c.addContainerFilter(new Filter() {
-
- public boolean passesFilter(Object itemId, Item item)
- throws UnsupportedOperationException {
- return true;
- }
-
- public boolean appliesToProperty(Object propertyId) {
- return true;
- }
- });
- c.removeItem("child");
-
- assertFalse(c.containsId("child"));
- assertNull(c.getChildren("root"));
- assertNull(c.getChildren("child"));
- assertFalse(c.hasChildren("child"));
- assertFalse(c.hasChildren("root"));
- }
-
- public void testHierarchicalFilteringWithoutParents() {
- HierarchicalContainer container = new HierarchicalContainer();
-
- initializeContainer(container);
- container.setIncludeParentsWhenFiltering(false);
-
- // Filter by "contains ab"
- container.addContainerFilter(SIMPLE_NAME, "ab", false, false);
-
- // 20 items match the filter.
- // com.vaadin.data.BufferedValidatable
- // com.vaadin.data.Validatable
- // com.vaadin.terminal.gwt.client.Focusable
- // com.vaadin.terminal.gwt.client.Paintable
- // com.vaadin.terminal.gwt.client.ui.Table
- // com.vaadin.terminal.gwt.client.ui.VLabel
- // com.vaadin.terminal.gwt.client.ui.VScrollTable
- // com.vaadin.terminal.gwt.client.ui.VTablePaging
- // com.vaadin.terminal.gwt.client.ui.VTabsheet
- // com.vaadin.terminal.gwt.client.ui.VTabsheetBase
- // com.vaadin.terminal.gwt.client.ui.VTabsheetPanel
- // com.vaadin.terminal.gwt.server.ChangeVariablesErrorEvent
- // com.vaadin.terminal.Paintable
- // com.vaadin.terminal.Scrollable
- // com.vaadin.terminal.Sizeable
- // com.vaadin.terminal.VariableOwner
- // com.vaadin.ui.Label
- // com.vaadin.ui.Table
- // com.vaadin.ui.TableFieldFactory
- // com.vaadin.ui.TabSheet
- // all become roots.
- int expectedSize = 20;
- int expectedRoots = 20;
-
- validateHierarchicalContainer(container,
- "com.vaadin.data.BufferedValidatable",
- "com.vaadin.ui.TabSheet",
- "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", "blah",
- true, expectedSize, expectedRoots, false);
-
- // only include .gwt.client classes
- container.removeAllContainerFilters();
- container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.",
- false, false);
-
- int packages = 3;
- int classes = 110;
-
- expectedSize = packages + classes;
- expectedRoots = 35 + 1; // com.vaadin.terminal.gwt.client.ui +
- // com.vaadin.terminal.gwt.client.*
-
- // Sorting is case insensitive
- validateHierarchicalContainer(container,
- "com.vaadin.terminal.gwt.client.ApplicationConfiguration",
- "com.vaadin.terminal.gwt.client.WidgetSet",
- "com.vaadin.terminal.gwt.client.ui.VOptionGroup", "blah", true,
- expectedSize, expectedRoots, false);
-
- // Additionally remove all without 'P' in the simple name.
- container.addContainerFilter(SIMPLE_NAME, "P", false, false);
-
- expectedSize = 13;
- expectedRoots = expectedSize;
-
- validateHierarchicalContainer(container,
- "com.vaadin.terminal.gwt.client.Paintable",
- "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel",
- "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", "blah",
- true, expectedSize, expectedRoots, false);
-
- }
-}
+package com.vaadin.data.util; + +import com.vaadin.data.Container.Filter; +import com.vaadin.data.Item; +import com.vaadin.data.util.HierarchicalContainer; + +public class TestHierarchicalContainer extends + AbstractHierarchicalContainerTest { + + public void testBasicOperations() { + testBasicContainerOperations(new HierarchicalContainer()); + } + + public void testFiltering() { + testContainerFiltering(new HierarchicalContainer()); + } + + public void testSorting() { + testContainerSorting(new HierarchicalContainer()); + } + + public void testOrdered() { + testContainerOrdered(new HierarchicalContainer()); + } + + public void testHierarchicalSorting() { + testHierarchicalSorting(new HierarchicalContainer()); + } + + public void testSortingAndFiltering() { + testContainerSortingAndFiltering(new HierarchicalContainer()); + } + + public void testRemovingItemsFromFilteredContainer() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); + Object p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin.ui", p1); + + container.removeItem("com.vaadin.ui.TabSheet"); + // Parent for the removed item must be null because the item is no + // longer in the container + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertNull("Parent should be null, is " + p1, p1); + + container.removeAllItems(); + p1 = container.getParent("com.vaadin.terminal.gwt.client.Focusable"); + assertNull("Parent should be null, is " + p1, p1); + + } + + public void testParentWhenRemovingFilterFromContainer() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); + Object p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin.ui", p1); + p1 = container + .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar"); + assertNull(p1); + container.removeAllContainerFilters(); + p1 = container + .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar"); + assertEquals("com.vaadin.terminal.gwt.client.ui", p1); + + } + + public void testChangeParentInFilteredContainer() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "Tab", false, false); + + // Change parent of filtered item + Object p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin.ui", p1); + container.setParent("com.vaadin.ui.TabSheet", "com.vaadin"); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin", p1); + container.setParent("com.vaadin.ui.TabSheet", "com"); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com", p1); + container.setParent("com.vaadin.ui.TabSheet", null); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertNull(p1); + + // root -> non-root + container.setParent("com.vaadin.ui.TabSheet", "com"); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com", p1); + + } + + public void testHierarchicalFilteringWithParents() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + + // Filter by "contains ab" + container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); + + // 20 items match the filters and the have 8 parents that should also be + // included + // only one root "com" should exist + // filtered + int expectedSize = 29; + int expectedRoots = 1; + + validateHierarchicalContainer(container, "com", + "com.vaadin.ui.TabSheet", + "com.vaadin.terminal.gwt.client.Focusable", "blah", true, + expectedSize, expectedRoots, true); + + // only include .gwt.client classes + container.removeAllContainerFilters(); + container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.", + false, false); + + int packages = 6; + int classes = 112; + + expectedSize = packages + classes; + expectedRoots = 1; + + validateHierarchicalContainer(container, "com", + "com.vaadin.terminal.gwt.client.WidgetSet", + "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical", + "blah", true, expectedSize, expectedRoots, true); + + // Additionally remove all without 'm' in the simple name. + container.addContainerFilter(SIMPLE_NAME, "m", false, false); + + expectedSize = 7 + 18; + expectedRoots = 1; + + validateHierarchicalContainer( + container, + "com", + "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", + "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer", + "blah", true, expectedSize, expectedRoots, true); + + } + + public void testRemoveLastChild() { + HierarchicalContainer c = new HierarchicalContainer(); + + c.addItem("root"); + assertEquals(false, c.hasChildren("root")); + + c.addItem("child"); + c.setParent("child", "root"); + assertEquals(true, c.hasChildren("root")); + + c.removeItem("child"); + assertFalse(c.containsId("child")); + assertNull(c.getChildren("root")); + assertNull(c.getChildren("child")); + assertFalse(c.hasChildren("child")); + assertFalse(c.hasChildren("root")); + } + + public void testRemoveLastChildFromFiltered() { + HierarchicalContainer c = new HierarchicalContainer(); + + c.addItem("root"); + assertEquals(false, c.hasChildren("root")); + + c.addItem("child"); + c.setParent("child", "root"); + assertEquals(true, c.hasChildren("root")); + + // Dummy filter that does not remove any items + c.addContainerFilter(new Filter() { + + public boolean passesFilter(Object itemId, Item item) + throws UnsupportedOperationException { + return true; + } + + public boolean appliesToProperty(Object propertyId) { + return true; + } + }); + c.removeItem("child"); + + assertFalse(c.containsId("child")); + assertNull(c.getChildren("root")); + assertNull(c.getChildren("child")); + assertFalse(c.hasChildren("child")); + assertFalse(c.hasChildren("root")); + } + + public void testHierarchicalFilteringWithoutParents() { + HierarchicalContainer container = new HierarchicalContainer(); + + initializeContainer(container); + container.setIncludeParentsWhenFiltering(false); + + // Filter by "contains ab" + container.addContainerFilter(SIMPLE_NAME, "ab", false, false); + + // 20 items match the filter. + // com.vaadin.data.BufferedValidatable + // com.vaadin.data.Validatable + // com.vaadin.terminal.gwt.client.Focusable + // com.vaadin.terminal.gwt.client.Paintable + // com.vaadin.terminal.gwt.client.ui.Table + // com.vaadin.terminal.gwt.client.ui.VLabel + // com.vaadin.terminal.gwt.client.ui.VScrollTable + // com.vaadin.terminal.gwt.client.ui.VTablePaging + // com.vaadin.terminal.gwt.client.ui.VTabsheet + // com.vaadin.terminal.gwt.client.ui.VTabsheetBase + // com.vaadin.terminal.gwt.client.ui.VTabsheetPanel + // com.vaadin.terminal.gwt.server.ChangeVariablesErrorEvent + // com.vaadin.terminal.Paintable + // com.vaadin.terminal.Scrollable + // com.vaadin.terminal.Sizeable + // com.vaadin.terminal.VariableOwner + // com.vaadin.ui.Label + // com.vaadin.ui.Table + // com.vaadin.ui.TableFieldFactory + // com.vaadin.ui.TabSheet + // all become roots. + int expectedSize = 20; + int expectedRoots = 20; + + validateHierarchicalContainer(container, + "com.vaadin.data.BufferedValidatable", + "com.vaadin.ui.TabSheet", + "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", "blah", + true, expectedSize, expectedRoots, false); + + // only include .gwt.client classes + container.removeAllContainerFilters(); + container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.", + false, false); + + int packages = 3; + int classes = 110; + + expectedSize = packages + classes; + expectedRoots = 35 + 1; // com.vaadin.terminal.gwt.client.ui + + // com.vaadin.terminal.gwt.client.* + + // Sorting is case insensitive + validateHierarchicalContainer(container, + "com.vaadin.terminal.gwt.client.ApplicationConfiguration", + "com.vaadin.terminal.gwt.client.WidgetSet", + "com.vaadin.terminal.gwt.client.ui.VOptionGroup", "blah", true, + expectedSize, expectedRoots, false); + + // Additionally remove all without 'P' in the simple name. + container.addContainerFilter(SIMPLE_NAME, "P", false, false); + + expectedSize = 13; + expectedRoots = expectedSize; + + validateHierarchicalContainer(container, + "com.vaadin.terminal.gwt.client.Paintable", + "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel", + "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", "blah", + true, expectedSize, expectedRoots, false); + + } +} diff --git a/tests/server-side/com/vaadin/data/util/TestIndexedContainer.java b/tests/server-side/com/vaadin/data/util/TestIndexedContainer.java index 99bd4838cf..156ff83883 100644 --- a/tests/server-side/com/vaadin/data/util/TestIndexedContainer.java +++ b/tests/server-side/com/vaadin/data/util/TestIndexedContainer.java @@ -1,271 +1,271 @@ -package com.vaadin.data.util;
-
-import com.vaadin.data.Item;
-import com.vaadin.data.util.IndexedContainer;
-
-public class TestIndexedContainer extends AbstractInMemoryContainerTest {
-
- public void testBasicOperations() {
- testBasicContainerOperations(new IndexedContainer());
- }
-
- public void testFiltering() {
- testContainerFiltering(new IndexedContainer());
- }
-
- public void testSorting() {
- testContainerSorting(new IndexedContainer());
- }
-
- public void testSortingAndFiltering() {
- testContainerSortingAndFiltering(new IndexedContainer());
- }
-
- public void testContainerOrdered() {
- testContainerOrdered(new IndexedContainer());
- }
-
- public void testContainerIndexed() {
- testContainerIndexed(new IndexedContainer(), sampleData[2], 2, true,
- "newItemId", true);
- }
-
- public void testItemSetChangeListeners() {
- IndexedContainer container = new IndexedContainer();
- ItemSetChangeCounter counter = new ItemSetChangeCounter();
- container.addListener(counter);
-
- String id1 = "id1";
- String id2 = "id2";
- String id3 = "id3";
-
- initializeContainer(container);
- counter.reset();
- container.addItem();
- counter.assertOnce();
- container.addItem(id1);
- counter.assertOnce();
-
- initializeContainer(container);
- counter.reset();
- container.addItemAt(0);
- counter.assertOnce();
- container.addItemAt(0, id1);
- counter.assertOnce();
- container.addItemAt(0, id2);
- counter.assertOnce();
- container.addItemAt(container.size(), id3);
- counter.assertOnce();
- // no notification if already in container
- container.addItemAt(0, id1);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- container.addItemAfter(null);
- counter.assertOnce();
- container.addItemAfter(null, id1);
- counter.assertOnce();
- container.addItemAfter(id1);
- counter.assertOnce();
- container.addItemAfter(id1, id2);
- counter.assertOnce();
- container.addItemAfter(container.firstItemId());
- counter.assertOnce();
- container.addItemAfter(container.lastItemId());
- counter.assertOnce();
- container.addItemAfter(container.lastItemId(), id3);
- counter.assertOnce();
- // no notification if already in container
- container.addItemAfter(0, id1);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- container.removeItem(sampleData[0]);
- counter.assertOnce();
-
- initializeContainer(container);
- counter.reset();
- // no notification for removing a non-existing item
- container.removeItem(id1);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- container.removeAllItems();
- counter.assertOnce();
- // already empty
- container.removeAllItems();
- counter.assertNone();
-
- }
-
- public void testAddRemoveContainerFilter() {
- IndexedContainer container = new IndexedContainer();
- ItemSetChangeCounter counter = new ItemSetChangeCounter();
- container.addListener(counter);
-
- // simply adding or removing container filters should cause events
- // (content changes)
-
- initializeContainer(container);
- counter.reset();
- container.addContainerFilter(SIMPLE_NAME, "a", true, false);
- counter.assertOnce();
- container.removeContainerFilters(SIMPLE_NAME);
- counter.assertOnce();
- container.addContainerFilter(SIMPLE_NAME, "a", true, false);
- counter.assertOnce();
- container.removeAllContainerFilters();
- counter.assertOnce();
- }
-
- // TODO other tests should check positions after removing filter etc,
- // here concentrating on listeners
- public void testItemSetChangeListenersFiltering() {
- IndexedContainer container = new IndexedContainer();
- ItemSetChangeCounter counter = new ItemSetChangeCounter();
- container.addListener(counter);
-
- counter.reset();
- container.addContainerFilter(FULLY_QUALIFIED_NAME, "Test", true, false);
- // no real change, so no notification required
- counter.assertNone();
-
- String id1 = "com.example.Test1";
- String id2 = "com.example.Test2";
- String id3 = "com.example.Other";
-
- // perform operations while filtering container
-
- Item item;
-
- initializeContainer(container);
- counter.reset();
- // passes filter
- item = container.addItem(id1);
- // no event if filtered out
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1);
- counter.assertOnce();
- // passes filter but already in the container
- item = container.addItem(id1);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- // passes filter after change
- item = container.addItemAt(0, id1);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1);
- counter.assertOnce();
- item = container.addItemAt(container.size(), id2);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2);
- counter.assertOnce();
- // passes filter but already in the container
- item = container.addItemAt(0, id1);
- counter.assertNone();
- item = container.addItemAt(container.size(), id2);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- // passes filter
- item = container.addItemAfter(null, id1);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1);
- counter.assertOnce();
- item = container.addItemAfter(container.lastItemId(), id2);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2);
- counter.assertOnce();
- // passes filter but already in the container
- item = container.addItemAfter(null, id1);
- counter.assertNone();
- item = container.addItemAfter(container.lastItemId(), id2);
- counter.assertNone();
-
- // does not pass filter
-
- // TODO implement rest
-
- initializeContainer(container);
- counter.reset();
- item = container.addItemAfter(null, id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- item = container.addItemAfter(container.firstItemId(), id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- item = container.addItemAfter(container.lastItemId(), id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- item = container.addItemAt(0, id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- item = container.addItemAt(1, id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
-
- initializeContainer(container);
- counter.reset();
- item = container.addItemAt(container.size(), id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
-
- // passes filter
-
- initializeContainer(container);
- counter.reset();
- item = container.addItem(id1);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1);
- counter.assertOnce();
- container.removeItem(id1);
- counter.assertOnce();
- // already removed
- container.removeItem(id1);
- counter.assertNone();
-
- item = container.addItem(id3);
- counter.assertNone();
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3);
- counter.assertNone();
- // not visible
- container.removeItem(id3);
- counter.assertNone();
-
- // remove all
-
- initializeContainer(container);
- item = container.addItem(id1);
- item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1);
- counter.reset();
- container.removeAllItems();
- counter.assertOnce();
- // no visible items
- container.removeAllItems();
- counter.assertNone();
- }
-
-}
+package com.vaadin.data.util; + +import com.vaadin.data.Item; +import com.vaadin.data.util.IndexedContainer; + +public class TestIndexedContainer extends AbstractInMemoryContainerTest { + + public void testBasicOperations() { + testBasicContainerOperations(new IndexedContainer()); + } + + public void testFiltering() { + testContainerFiltering(new IndexedContainer()); + } + + public void testSorting() { + testContainerSorting(new IndexedContainer()); + } + + public void testSortingAndFiltering() { + testContainerSortingAndFiltering(new IndexedContainer()); + } + + public void testContainerOrdered() { + testContainerOrdered(new IndexedContainer()); + } + + public void testContainerIndexed() { + testContainerIndexed(new IndexedContainer(), sampleData[2], 2, true, + "newItemId", true); + } + + public void testItemSetChangeListeners() { + IndexedContainer container = new IndexedContainer(); + ItemSetChangeCounter counter = new ItemSetChangeCounter(); + container.addListener(counter); + + String id1 = "id1"; + String id2 = "id2"; + String id3 = "id3"; + + initializeContainer(container); + counter.reset(); + container.addItem(); + counter.assertOnce(); + container.addItem(id1); + counter.assertOnce(); + + initializeContainer(container); + counter.reset(); + container.addItemAt(0); + counter.assertOnce(); + container.addItemAt(0, id1); + counter.assertOnce(); + container.addItemAt(0, id2); + counter.assertOnce(); + container.addItemAt(container.size(), id3); + counter.assertOnce(); + // no notification if already in container + container.addItemAt(0, id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + container.addItemAfter(null); + counter.assertOnce(); + container.addItemAfter(null, id1); + counter.assertOnce(); + container.addItemAfter(id1); + counter.assertOnce(); + container.addItemAfter(id1, id2); + counter.assertOnce(); + container.addItemAfter(container.firstItemId()); + counter.assertOnce(); + container.addItemAfter(container.lastItemId()); + counter.assertOnce(); + container.addItemAfter(container.lastItemId(), id3); + counter.assertOnce(); + // no notification if already in container + container.addItemAfter(0, id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + container.removeItem(sampleData[0]); + counter.assertOnce(); + + initializeContainer(container); + counter.reset(); + // no notification for removing a non-existing item + container.removeItem(id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + container.removeAllItems(); + counter.assertOnce(); + // already empty + container.removeAllItems(); + counter.assertNone(); + + } + + public void testAddRemoveContainerFilter() { + IndexedContainer container = new IndexedContainer(); + ItemSetChangeCounter counter = new ItemSetChangeCounter(); + container.addListener(counter); + + // simply adding or removing container filters should cause events + // (content changes) + + initializeContainer(container); + counter.reset(); + container.addContainerFilter(SIMPLE_NAME, "a", true, false); + counter.assertOnce(); + container.removeContainerFilters(SIMPLE_NAME); + counter.assertOnce(); + container.addContainerFilter(SIMPLE_NAME, "a", true, false); + counter.assertOnce(); + container.removeAllContainerFilters(); + counter.assertOnce(); + } + + // TODO other tests should check positions after removing filter etc, + // here concentrating on listeners + public void testItemSetChangeListenersFiltering() { + IndexedContainer container = new IndexedContainer(); + ItemSetChangeCounter counter = new ItemSetChangeCounter(); + container.addListener(counter); + + counter.reset(); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "Test", true, false); + // no real change, so no notification required + counter.assertNone(); + + String id1 = "com.example.Test1"; + String id2 = "com.example.Test2"; + String id3 = "com.example.Other"; + + // perform operations while filtering container + + Item item; + + initializeContainer(container); + counter.reset(); + // passes filter + item = container.addItem(id1); + // no event if filtered out + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + // passes filter but already in the container + item = container.addItem(id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + // passes filter after change + item = container.addItemAt(0, id1); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + item = container.addItemAt(container.size(), id2); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2); + counter.assertOnce(); + // passes filter but already in the container + item = container.addItemAt(0, id1); + counter.assertNone(); + item = container.addItemAt(container.size(), id2); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + // passes filter + item = container.addItemAfter(null, id1); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + item = container.addItemAfter(container.lastItemId(), id2); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2); + counter.assertOnce(); + // passes filter but already in the container + item = container.addItemAfter(null, id1); + counter.assertNone(); + item = container.addItemAfter(container.lastItemId(), id2); + counter.assertNone(); + + // does not pass filter + + // TODO implement rest + + initializeContainer(container); + counter.reset(); + item = container.addItemAfter(null, id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAfter(container.firstItemId(), id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAfter(container.lastItemId(), id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAt(0, id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAt(1, id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAt(container.size(), id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + // passes filter + + initializeContainer(container); + counter.reset(); + item = container.addItem(id1); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + container.removeItem(id1); + counter.assertOnce(); + // already removed + container.removeItem(id1); + counter.assertNone(); + + item = container.addItem(id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + // not visible + container.removeItem(id3); + counter.assertNone(); + + // remove all + + initializeContainer(container); + item = container.addItem(id1); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.reset(); + container.removeAllItems(); + counter.assertOnce(); + // no visible items + container.removeAllItems(); + counter.assertNone(); + } + +} diff --git a/tests/server-side/com/vaadin/data/util/sqlcontainer/SQLContainerTableQueryTest.java b/tests/server-side/com/vaadin/data/util/sqlcontainer/SQLContainerTableQueryTest.java index 58ac123c14..438c40823d 100644 --- a/tests/server-side/com/vaadin/data/util/sqlcontainer/SQLContainerTableQueryTest.java +++ b/tests/server-side/com/vaadin/data/util/sqlcontainer/SQLContainerTableQueryTest.java @@ -1,1519 +1,1519 @@ -package com.vaadin.data.util.sqlcontainer;
-
-import java.math.BigDecimal;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.easymock.EasyMock;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.vaadin.data.Container.ItemSetChangeEvent;
-import com.vaadin.data.Container.ItemSetChangeListener;
-import com.vaadin.data.Item;
-import com.vaadin.data.util.filter.Like;
-import com.vaadin.data.util.sqlcontainer.AllTests.DB;
-import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;
-import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool;
-import com.vaadin.data.util.sqlcontainer.query.OrderBy;
-import com.vaadin.data.util.sqlcontainer.query.TableQuery;
-
-public class SQLContainerTableQueryTest {
-
- private static final int offset = AllTests.offset;
- private static final String createGarbage = AllTests.createGarbage;
- private JDBCConnectionPool connectionPool;
-
- @Before
- public void setUp() throws SQLException {
-
- try {
- connectionPool = new SimpleJDBCConnectionPool(AllTests.dbDriver,
- AllTests.dbURL, AllTests.dbUser, AllTests.dbPwd, 2, 2);
- } catch (SQLException e) {
- e.printStackTrace();
- Assert.fail(e.getMessage());
- }
-
- DataGenerator.addPeopleToDatabase(connectionPool);
- }
-
- @After
- public void tearDown() {
- if (connectionPool != null) {
- connectionPool.destroy();
- }
- }
-
- @Test
- public void constructor_withTableQuery_shouldSucceed() throws SQLException {
- new SQLContainer(new TableQuery("people", connectionPool,
- AllTests.sqlGen));
- }
-
- @Test
- public void containsId_withTableQueryAndExistingId_returnsTrue()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertTrue(container.containsId(new RowId(
- new Object[] { 1 + offset })));
- }
-
- @Test
- public void containsId_withTableQueryAndNonexistingId_returnsFalse()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertFalse(container.containsId(new RowId(
- new Object[] { 1337 + offset })));
- }
-
- @Test
- public void getContainerProperty_tableExistingItemIdAndPropertyId_returnsProperty()
- throws SQLException {
- TableQuery t = new TableQuery("people", connectionPool, AllTests.sqlGen);
- SQLContainer container = new SQLContainer(t);
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- "Ville",
- container
- .getContainerProperty(
- new RowId(new Object[] { new BigDecimal(
- 0 + offset) }), "NAME").getValue());
- } else {
- Assert.assertEquals(
- "Ville",
- container.getContainerProperty(
- new RowId(new Object[] { 0 + offset }), "NAME")
- .getValue());
- }
- }
-
- @Test
- public void getContainerProperty_tableExistingItemIdAndNonexistingPropertyId_returnsNull()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertNull(container.getContainerProperty(new RowId(
- new Object[] { 1 + offset }), "asdf"));
- }
-
- @Test
- public void getContainerProperty_tableNonexistingItemId_returnsNull()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertNull(container.getContainerProperty(new RowId(
- new Object[] { 1337 + offset }), "NAME"));
- }
-
- @Test
- public void getContainerPropertyIds_table_returnsIDAndNAME()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Collection<?> propertyIds = container.getContainerPropertyIds();
- Assert.assertEquals(3, propertyIds.size());
- Assert.assertArrayEquals(new String[] { "ID", "NAME", "AGE" },
- propertyIds.toArray());
- }
-
- @Test
- public void getItem_tableExistingItemId_returnsItem() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Item item;
- if (AllTests.db == DB.ORACLE) {
- item = container.getItem(new RowId(new Object[] { new BigDecimal(
- 0 + offset) }));
- } else {
- item = container.getItem(new RowId(new Object[] { 0 + offset }));
- }
- Assert.assertNotNull(item);
- Assert.assertEquals("Ville", item.getItemProperty("NAME").getValue());
- }
-
- @Test
- public void getItem_commitedModifiedAndRefreshed() throws SQLException {
- String OLD_VALUE = "SomeValue"; //$NON-NLS-1$
- String NEW_VALUE = "OtherValue"; //$NON-NLS-1$
-
- SQLContainer container = new SQLContainer(new TableQuery("people", //$NON-NLS-1$
- connectionPool, AllTests.sqlGen));
- Object itemID = container.addItem();
- Item item = container.getItem(itemID);
- item.getItemProperty("NAME").setValue(OLD_VALUE); //$NON-NLS-1$
- container.commit();
-
- itemID = container.getIdByIndex(container.size() - 1);
- item = container.getItem(itemID);
- Assert.assertEquals(OLD_VALUE, item.getItemProperty("NAME") //$NON-NLS-1$
- .getValue());
- item.getItemProperty("NAME").setValue(NEW_VALUE); //$NON-NLS-1$
-
- // refresh the container which free's the caches
- // and the modified cache keeps untouched which is a really powerful
- // feature
- container.refresh();
-
- // access the item again will use the item from the modified cache.
- item = container.getItem(itemID);
- Assert.assertEquals(NEW_VALUE, item.getItemProperty("NAME") //$NON-NLS-1$
- .getValue());
- }
-
- @Test
- public void getItem_table5000RowsWithParameter1337_returnsItemWithId1337()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
-
- Item item;
- if (AllTests.db == DB.ORACLE) {
- item = container.getItem(new RowId(new Object[] { new BigDecimal(
- 1337 + offset) }));
- Assert.assertNotNull(item);
- Assert.assertEquals(new BigDecimal(1337 + offset), item
- .getItemProperty("ID").getValue());
- } else {
- item = container.getItem(new RowId(new Object[] { 1337 + offset }));
- Assert.assertNotNull(item);
- Assert.assertEquals(1337 + offset, item.getItemProperty("ID")
- .getValue());
- }
- Assert.assertEquals("Person 1337", item.getItemProperty("NAME")
- .getValue());
- }
-
- @Test
- public void getItemIds_table_returnsItemIdsWithKeys0through3()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Collection<?> itemIds = container.getItemIds();
- Assert.assertEquals(4, itemIds.size());
- RowId zero = new RowId(new Object[] { 0 + offset });
- RowId one = new RowId(new Object[] { 1 + offset });
- RowId two = new RowId(new Object[] { 2 + offset });
- RowId three = new RowId(new Object[] { 3 + offset });
- if (AllTests.db == DB.ORACLE) {
- String[] correct = new String[] { "1", "2", "3", "4" };
- List<String> oracle = new ArrayList<String>();
- for (Object o : itemIds) {
- oracle.add(o.toString());
- }
- Assert.assertArrayEquals(correct, oracle.toArray());
- } else {
- Assert.assertArrayEquals(new Object[] { zero, one, two, three },
- itemIds.toArray());
- }
- }
-
- @Test
- public void getType_tableNAMEPropertyId_returnsString() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertEquals(String.class, container.getType("NAME"));
- }
-
- @Test
- public void getType_tableIDPropertyId_returnsInteger() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(BigDecimal.class, container.getType("ID"));
- } else {
- Assert.assertEquals(Integer.class, container.getType("ID"));
- }
- }
-
- @Test
- public void getType_tableNonexistingPropertyId_returnsNull()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertNull(container.getType("asdf"));
- }
-
- @Test
- public void size_table_returnsFour() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertEquals(4, container.size());
- }
-
- @Test
- public void size_tableOneAddedItem_returnsFive() throws SQLException {
- Connection conn = connectionPool.reserveConnection();
- Statement statement = conn.createStatement();
- if (AllTests.db == DB.MSSQL) {
- statement.executeUpdate("insert into people values('Bengt', 30)");
- } else {
- statement
- .executeUpdate("insert into people values(default, 'Bengt', 30)");
- }
- statement.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
-
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertEquals(5, container.size());
- }
-
- @Test
- public void indexOfId_tableWithParameterThree_returnsThree()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(3, container.indexOfId(new RowId(
- new Object[] { new BigDecimal(3 + offset) })));
- } else {
- Assert.assertEquals(3,
- container.indexOfId(new RowId(new Object[] { 3 + offset })));
- }
- }
-
- @Test
- public void indexOfId_table5000RowsWithParameter1337_returns1337()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- TableQuery q = new TableQuery("people", connectionPool, AllTests.sqlGen);
- SQLContainer container = new SQLContainer(q);
- if (AllTests.db == DB.ORACLE) {
- container.getItem(new RowId(new Object[] { new BigDecimal(
- 1337 + offset) }));
- Assert.assertEquals(1337, container.indexOfId(new RowId(
- new Object[] { new BigDecimal(1337 + offset) })));
- } else {
- container.getItem(new RowId(new Object[] { 1337 + offset }));
- Assert.assertEquals(1337, container.indexOfId(new RowId(
- new Object[] { 1337 + offset })));
- }
- }
-
- @Test
- public void getIdByIndex_table5000rowsIndex1337_returnsRowId1337()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object itemId = container.getIdByIndex(1337);
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- new RowId(new Object[] { 1337 + offset }).toString(),
- itemId.toString());
- } else {
- Assert.assertEquals(new RowId(new Object[] { 1337 + offset }),
- itemId);
- }
- }
-
- @Test
- public void getIdByIndex_tableWithPaging5000rowsIndex1337_returnsRowId1337()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- Object itemId = container.getIdByIndex(1337);
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- new RowId(new Object[] { 1337 + offset }).toString(),
- itemId.toString());
- } else {
- Assert.assertEquals(new RowId(new Object[] { 1337 + offset }),
- itemId);
- }
- }
-
- @Test
- public void nextItemId_tableCurrentItem1337_returnsItem1338()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object itemId = container.getIdByIndex(1337);
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- new RowId(new Object[] { 1338 + offset }).toString(),
- container.nextItemId(itemId).toString());
- } else {
- Assert.assertEquals(new RowId(new Object[] { 1338 + offset }),
- container.nextItemId(itemId));
- }
- }
-
- @Test
- public void prevItemId_tableCurrentItem1337_returns1336()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object itemId = container.getIdByIndex(1337);
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- new RowId(new Object[] { 1336 + offset }).toString(),
- container.prevItemId(itemId).toString());
- } else {
- Assert.assertEquals(new RowId(new Object[] { 1336 + offset }),
- container.prevItemId(itemId));
- }
- }
-
- @Test
- public void firstItemId_table_returnsItemId0() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- new RowId(new Object[] { 0 + offset }).toString(),
- container.firstItemId().toString());
- } else {
- Assert.assertEquals(new RowId(new Object[] { 0 + offset }),
- container.firstItemId());
- }
- }
-
- @Test
- public void lastItemId_table5000Rows_returnsItemId4999()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
-
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertEquals(
- new RowId(new Object[] { 4999 + offset }).toString(),
- container.lastItemId().toString());
- } else {
- Assert.assertEquals(new RowId(new Object[] { 4999 + offset }),
- container.lastItemId());
- }
- }
-
- @Test
- public void isFirstId_tableActualFirstId_returnsTrue() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertTrue(container.isFirstId(new RowId(
- new Object[] { new BigDecimal(0 + offset) })));
- } else {
- Assert.assertTrue(container.isFirstId(new RowId(
- new Object[] { 0 + offset })));
- }
- }
-
- @Test
- public void isFirstId_tableSecondId_returnsFalse() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertFalse(container.isFirstId(new RowId(
- new Object[] { new BigDecimal(1 + offset) })));
- } else {
- Assert.assertFalse(container.isFirstId(new RowId(
- new Object[] { 1 + offset })));
- }
- }
-
- @Test
- public void isLastId_tableSecondId_returnsFalse() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertFalse(container.isLastId(new RowId(
- new Object[] { new BigDecimal(1 + offset) })));
- } else {
- Assert.assertFalse(container.isLastId(new RowId(
- new Object[] { 1 + offset })));
- }
- }
-
- @Test
- public void isLastId_tableLastId_returnsTrue() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertTrue(container.isLastId(new RowId(
- new Object[] { new BigDecimal(3 + offset) })));
- } else {
- Assert.assertTrue(container.isLastId(new RowId(
- new Object[] { 3 + offset })));
- }
- }
-
- @Test
- public void isLastId_table5000RowsLastId_returnsTrue() throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- if (AllTests.db == DB.ORACLE) {
- Assert.assertTrue(container.isLastId(new RowId(
- new Object[] { new BigDecimal(4999 + offset) })));
- } else {
- Assert.assertTrue(container.isLastId(new RowId(
- new Object[] { 4999 + offset })));
- }
- }
-
- @Test
- public void allIdsFound_table5000RowsLastId_shouldSucceed()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- for (int i = 0; i < 5000; i++) {
- Assert.assertTrue(container.containsId(container.getIdByIndex(i)));
- }
- }
-
- @Test
- public void allIdsFound_table5000RowsLastId_autoCommit_shouldSucceed()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.setAutoCommit(true);
- for (int i = 0; i < 5000; i++) {
- Assert.assertTrue(container.containsId(container.getIdByIndex(i)));
- }
- }
-
- @Test
- public void refresh_table_sizeShouldUpdate() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertEquals(4, container.size());
- DataGenerator.addFiveThousandPeople(connectionPool);
- container.refresh();
- Assert.assertEquals(5000, container.size());
- }
-
- @Test
- public void refresh_tableWithoutCallingRefresh_sizeShouldNotUpdate()
- throws SQLException {
- // Yeah, this is a weird one. We're testing that the size doesn't update
- // after adding lots of items unless we call refresh inbetween. This to
- // make sure that the refresh method actually refreshes stuff and isn't
- // a NOP.
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertEquals(4, container.size());
- DataGenerator.addFiveThousandPeople(connectionPool);
- Assert.assertEquals(4, container.size());
- }
-
- @Test
- public void setAutoCommit_table_shouldSucceed() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.setAutoCommit(true);
- Assert.assertTrue(container.isAutoCommit());
- container.setAutoCommit(false);
- Assert.assertFalse(container.isAutoCommit());
- }
-
- @Test
- public void getPageLength_table_returnsDefault100() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertEquals(100, container.getPageLength());
- }
-
- @Test
- public void setPageLength_table_shouldSucceed() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.setPageLength(20);
- Assert.assertEquals(20, container.getPageLength());
- container.setPageLength(200);
- Assert.assertEquals(200, container.getPageLength());
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void addContainerProperty_normal_isUnsupported() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addContainerProperty("asdf", String.class, "");
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void removeContainerProperty_normal_isUnsupported()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.removeContainerProperty("asdf");
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void addItemObject_normal_isUnsupported() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItem("asdf");
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void addItemAfterObjectObject_normal_isUnsupported()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItemAfter("asdf", "foo");
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void addItemAtIntObject_normal_isUnsupported() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItemAt(2, "asdf");
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void addItemAtInt_normal_isUnsupported() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItemAt(2);
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void addItemAfterObject_normal_isUnsupported() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItemAfter("asdf");
- }
-
- @Test
- public void addItem_tableAddOneNewItem_returnsItemId() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object itemId = container.addItem();
- Assert.assertNotNull(itemId);
- }
-
- @Test
- public void addItem_tableAddOneNewItem_autoCommit_returnsFinalItemId()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- container.setAutoCommit(true);
- Object itemId = container.addItem();
- Assert.assertNotNull(itemId);
- Assert.assertTrue(itemId instanceof RowId);
- Assert.assertFalse(itemId instanceof TemporaryRowId);
- }
-
- @Test
- public void addItem_tableAddOneNewItem_autoCommit_sizeIsIncreased()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- container.setAutoCommit(true);
- int originalSize = container.size();
- container.addItem();
- Assert.assertEquals(originalSize + 1, container.size());
- }
-
- @Test
- public void addItem_tableAddOneNewItem_shouldChangeSize()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- int size = container.size();
- container.addItem();
- Assert.assertEquals(size + 1, container.size());
- }
-
- @Test
- public void addItem_tableAddTwoNewItems_shouldChangeSize()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- int size = container.size();
- Object id1 = container.addItem();
- Object id2 = container.addItem();
- Assert.assertEquals(size + 2, container.size());
- Assert.assertNotSame(id1, id2);
- Assert.assertFalse(id1.equals(id2));
- }
-
- @Test
- public void nextItemId_tableNewlyAddedItem_returnsNewlyAdded()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object lastId = container.lastItemId();
- Object id = container.addItem();
- Assert.assertEquals(id, container.nextItemId(lastId));
- }
-
- @Test
- public void lastItemId_tableNewlyAddedItem_returnsNewlyAdded()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object lastId = container.lastItemId();
- Object id = container.addItem();
- Assert.assertEquals(id, container.lastItemId());
- Assert.assertNotSame(lastId, container.lastItemId());
- }
-
- @Test
- public void indexOfId_tableNewlyAddedItem_returnsFour() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertEquals(4, container.indexOfId(id));
- }
-
- @Test
- public void getItem_tableNewlyAddedItem_returnsNewlyAdded()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertNotNull(container.getItem(id));
- }
-
- @Test
- public void getItemIds_tableNewlyAddedItem_containsNewlyAdded()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertTrue(container.getItemIds().contains(id));
- }
-
- @Test
- public void getContainerProperty_tableNewlyAddedItem_returnsPropertyOfNewlyAddedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Item item = container.getItem(id);
- item.getItemProperty("NAME").setValue("asdf");
- Assert.assertEquals("asdf", container.getContainerProperty(id, "NAME")
- .getValue());
- }
-
- @Test
- public void containsId_tableNewlyAddedItem_returnsTrue()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertTrue(container.containsId(id));
- }
-
- @Test
- public void prevItemId_tableTwoNewlyAddedItems_returnsFirstAddedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id1 = container.addItem();
- Object id2 = container.addItem();
- Assert.assertEquals(id1, container.prevItemId(id2));
- }
-
- @Test
- public void firstItemId_tableEmptyResultSet_returnsFirstAddedItem()
- throws SQLException {
- DataGenerator.createGarbage(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("garbage",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertSame(id, container.firstItemId());
- }
-
- @Test
- public void isFirstId_tableEmptyResultSet_returnsFirstAddedItem()
- throws SQLException {
- DataGenerator.createGarbage(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("garbage",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertTrue(container.isFirstId(id));
- }
-
- @Test
- public void isLastId_tableOneItemAdded_returnsTrueForAddedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertTrue(container.isLastId(id));
- }
-
- @Test
- public void isLastId_tableTwoItemsAdded_returnsTrueForLastAddedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItem();
- Object id2 = container.addItem();
- Assert.assertTrue(container.isLastId(id2));
- }
-
- @Test
- public void getIdByIndex_tableOneItemAddedLastIndexInContainer_returnsAddedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertEquals(id, container.getIdByIndex(container.size() - 1));
- }
-
- @Test
- public void removeItem_tableNoAddedItems_removesItemFromContainer()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- int size = container.size();
- Object id = container.firstItemId();
- Assert.assertTrue(container.removeItem(id));
- Assert.assertNotSame(id, container.firstItemId());
- Assert.assertEquals(size - 1, container.size());
- }
-
- @Test
- public void containsId_tableRemovedItem_returnsFalse() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.firstItemId();
- Assert.assertTrue(container.removeItem(id));
- Assert.assertFalse(container.containsId(id));
- }
-
- @Test
- public void removeItem_tableOneAddedItem_removesTheAddedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- int size = container.size();
- Assert.assertTrue(container.removeItem(id));
- Assert.assertFalse(container.containsId(id));
- Assert.assertEquals(size - 1, container.size());
- }
-
- @Test
- public void getItem_tableItemRemoved_returnsNull() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.firstItemId();
- Assert.assertTrue(container.removeItem(id));
- Assert.assertNull(container.getItem(id));
- }
-
- @Test
- public void getItem_tableAddedItemRemoved_returnsNull() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertNotNull(container.getItem(id));
- Assert.assertTrue(container.removeItem(id));
- Assert.assertNull(container.getItem(id));
- }
-
- @Test
- public void getItemIds_tableItemRemoved_shouldNotContainRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.firstItemId();
- Assert.assertTrue(container.getItemIds().contains(id));
- Assert.assertTrue(container.removeItem(id));
- Assert.assertFalse(container.getItemIds().contains(id));
- }
-
- @Test
- public void getItemIds_tableAddedItemRemoved_shouldNotContainRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertTrue(container.getItemIds().contains(id));
- Assert.assertTrue(container.removeItem(id));
- Assert.assertFalse(container.getItemIds().contains(id));
- }
-
- @Test
- public void containsId_tableItemRemoved_returnsFalse() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.firstItemId();
- Assert.assertTrue(container.containsId(id));
- Assert.assertTrue(container.removeItem(id));
- Assert.assertFalse(container.containsId(id));
- }
-
- @Test
- public void containsId_tableAddedItemRemoved_returnsFalse()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- Object id = container.addItem();
- Assert.assertTrue(container.containsId(id));
- Assert.assertTrue(container.removeItem(id));
- Assert.assertFalse(container.containsId(id));
- }
-
- @Test
- public void nextItemId_tableItemRemoved_skipsRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object first = container.getIdByIndex(0);
- Object second = container.getIdByIndex(1);
- Object third = container.getIdByIndex(2);
- Assert.assertTrue(container.removeItem(second));
- Assert.assertEquals(third, container.nextItemId(first));
- }
-
- @Test
- public void nextItemId_tableAddedItemRemoved_skipsRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object first = container.lastItemId();
- Object second = container.addItem();
- Object third = container.addItem();
- Assert.assertTrue(container.removeItem(second));
- Assert.assertEquals(third, container.nextItemId(first));
- }
-
- @Test
- public void prevItemId_tableItemRemoved_skipsRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object first = container.getIdByIndex(0);
- Object second = container.getIdByIndex(1);
- Object third = container.getIdByIndex(2);
- Assert.assertTrue(container.removeItem(second));
- Assert.assertEquals(first, container.prevItemId(third));
- }
-
- @Test
- public void prevItemId_tableAddedItemRemoved_skipsRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object first = container.lastItemId();
- Object second = container.addItem();
- Object third = container.addItem();
- Assert.assertTrue(container.removeItem(second));
- Assert.assertEquals(first, container.prevItemId(third));
- }
-
- @Test
- public void firstItemId_tableFirstItemRemoved_resultChanges()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object first = container.firstItemId();
- Assert.assertTrue(container.removeItem(first));
- Assert.assertNotSame(first, container.firstItemId());
- }
-
- @Test
- public void firstItemId_tableNewlyAddedFirstItemRemoved_resultChanges()
- throws SQLException {
- DataGenerator.createGarbage(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("garbage",
- connectionPool, AllTests.sqlGen));
- Object first = container.addItem();
- Object second = container.addItem();
- Assert.assertSame(first, container.firstItemId());
- Assert.assertTrue(container.removeItem(first));
- Assert.assertSame(second, container.firstItemId());
- }
-
- @Test
- public void lastItemId_tableLastItemRemoved_resultChanges()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object last = container.lastItemId();
- Assert.assertTrue(container.removeItem(last));
- Assert.assertNotSame(last, container.lastItemId());
- }
-
- @Test
- public void lastItemId_tableAddedLastItemRemoved_resultChanges()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object last = container.addItem();
- Assert.assertSame(last, container.lastItemId());
- Assert.assertTrue(container.removeItem(last));
- Assert.assertNotSame(last, container.lastItemId());
- }
-
- @Test
- public void isFirstId_tableFirstItemRemoved_returnsFalse()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object first = container.firstItemId();
- Assert.assertTrue(container.removeItem(first));
- Assert.assertFalse(container.isFirstId(first));
- }
-
- @Test
- public void isFirstId_tableAddedFirstItemRemoved_returnsFalse()
- throws SQLException {
- DataGenerator.createGarbage(connectionPool);
- SQLContainer container = new SQLContainer(new TableQuery("garbage",
- connectionPool, AllTests.sqlGen));
- Object first = container.addItem();
- container.addItem();
- Assert.assertSame(first, container.firstItemId());
- Assert.assertTrue(container.removeItem(first));
- Assert.assertFalse(container.isFirstId(first));
- }
-
- @Test
- public void isLastId_tableLastItemRemoved_returnsFalse()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object last = container.lastItemId();
- Assert.assertTrue(container.removeItem(last));
- Assert.assertFalse(container.isLastId(last));
- }
-
- @Test
- public void isLastId_tableAddedLastItemRemoved_returnsFalse()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object last = container.addItem();
- Assert.assertSame(last, container.lastItemId());
- Assert.assertTrue(container.removeItem(last));
- Assert.assertFalse(container.isLastId(last));
- }
-
- @Test
- public void indexOfId_tableItemRemoved_returnsNegOne() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.getIdByIndex(2);
- Assert.assertTrue(container.removeItem(id));
- Assert.assertEquals(-1, container.indexOfId(id));
- }
-
- @Test
- public void indexOfId_tableAddedItemRemoved_returnsNegOne()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- Assert.assertTrue(container.indexOfId(id) != -1);
- Assert.assertTrue(container.removeItem(id));
- Assert.assertEquals(-1, container.indexOfId(id));
- }
-
- @Test
- public void getIdByIndex_tableItemRemoved_resultChanges()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.getIdByIndex(2);
- Assert.assertTrue(container.removeItem(id));
- Assert.assertNotSame(id, container.getIdByIndex(2));
- }
-
- @Test
- public void getIdByIndex_tableAddedItemRemoved_resultChanges()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object id = container.addItem();
- container.addItem();
- int index = container.indexOfId(id);
- Assert.assertTrue(container.removeItem(id));
- Assert.assertNotSame(id, container.getIdByIndex(index));
- }
-
- @Test
- public void removeAllItems_table_shouldSucceed() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertTrue(container.removeAllItems());
- Assert.assertEquals(0, container.size());
- }
-
- @Test
- public void removeAllItems_tableAddedItems_shouldSucceed()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addItem();
- container.addItem();
- Assert.assertTrue(container.removeAllItems());
- Assert.assertEquals(0, container.size());
- }
-
- @Test
- public void commit_tableAddedItem_shouldBeWrittenToDB() throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- Object id = container.addItem();
- container.getContainerProperty(id, "NAME").setValue("New Name");
- Assert.assertTrue(id instanceof TemporaryRowId);
- Assert.assertSame(id, container.lastItemId());
- container.commit();
- Assert.assertFalse(container.lastItemId() instanceof TemporaryRowId);
- Assert.assertEquals("New Name",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void commit_tableTwoAddedItems_shouldBeWrittenToDB()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- Object id = container.addItem();
- Object id2 = container.addItem();
- container.getContainerProperty(id, "NAME").setValue("Herbert");
- container.getContainerProperty(id2, "NAME").setValue("Larry");
- Assert.assertTrue(id2 instanceof TemporaryRowId);
- Assert.assertSame(id2, container.lastItemId());
- container.commit();
- Object nextToLast = container.getIdByIndex(container.size() - 2);
- Assert.assertFalse(nextToLast instanceof TemporaryRowId);
- Assert.assertEquals("Herbert",
- container.getContainerProperty(nextToLast, "NAME").getValue());
- Assert.assertFalse(container.lastItemId() instanceof TemporaryRowId);
- Assert.assertEquals("Larry",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void commit_tableRemovedItem_shouldBeRemovedFromDB()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- Object last = container.lastItemId();
- container.removeItem(last);
- container.commit();
- Assert.assertFalse(last.equals(container.lastItemId()));
- }
-
- @Test
- public void commit_tableLastItemUpdated_shouldUpdateRowInDB()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- Object last = container.lastItemId();
- container.getContainerProperty(last, "NAME").setValue("Donald");
- container.commit();
- Assert.assertEquals("Donald",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void rollback_tableItemAdded_discardsAddedItem() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- int size = container.size();
- Object id = container.addItem();
- container.getContainerProperty(id, "NAME").setValue("foo");
- Assert.assertEquals(size + 1, container.size());
- container.rollback();
- Assert.assertEquals(size, container.size());
- Assert.assertFalse("foo".equals(container.getContainerProperty(
- container.lastItemId(), "NAME").getValue()));
- }
-
- @Test
- public void rollback_tableItemRemoved_restoresRemovedItem()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- int size = container.size();
- Object last = container.lastItemId();
- container.removeItem(last);
- Assert.assertEquals(size - 1, container.size());
- container.rollback();
- Assert.assertEquals(size, container.size());
- Assert.assertEquals(last, container.lastItemId());
- }
-
- @Test
- public void rollback_tableItemChanged_discardsChanges() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Object last = container.lastItemId();
- container.getContainerProperty(last, "NAME").setValue("foo");
- container.rollback();
- Assert.assertFalse("foo".equals(container.getContainerProperty(
- container.lastItemId(), "NAME").getValue()));
- }
-
- @Test
- public void itemChangeNotification_table_isModifiedReturnsTrue()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertFalse(container.isModified());
- RowItem last = (RowItem) container.getItem(container.lastItemId());
- container.itemChangeNotification(last);
- Assert.assertTrue(container.isModified());
- }
-
- @Test
- public void itemSetChangeListeners_table_shouldFire() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- ItemSetChangeListener listener = EasyMock
- .createMock(ItemSetChangeListener.class);
- listener.containerItemSetChange(EasyMock.isA(ItemSetChangeEvent.class));
- EasyMock.replay(listener);
-
- container.addListener(listener);
- container.addItem();
-
- EasyMock.verify(listener);
- }
-
- @Test
- public void itemSetChangeListeners_tableItemRemoved_shouldFire()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- ItemSetChangeListener listener = EasyMock
- .createMock(ItemSetChangeListener.class);
- listener.containerItemSetChange(EasyMock.isA(ItemSetChangeEvent.class));
- EasyMock.expectLastCall().anyTimes();
- EasyMock.replay(listener);
-
- container.addListener(listener);
- container.removeItem(container.lastItemId());
-
- EasyMock.verify(listener);
- }
-
- @Test
- public void removeListener_table_shouldNotFire() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- ItemSetChangeListener listener = EasyMock
- .createMock(ItemSetChangeListener.class);
- EasyMock.replay(listener);
-
- container.addListener(listener);
- container.removeListener(listener);
- container.addItem();
-
- EasyMock.verify(listener);
- }
-
- @Test
- public void isModified_tableRemovedItem_returnsTrue() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertFalse(container.isModified());
- container.removeItem(container.lastItemId());
- Assert.assertTrue(container.isModified());
- }
-
- @Test
- public void isModified_tableAddedItem_returnsTrue() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertFalse(container.isModified());
- container.addItem();
- Assert.assertTrue(container.isModified());
- }
-
- @Test
- public void isModified_tableChangedItem_returnsTrue() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Assert.assertFalse(container.isModified());
- container.getContainerProperty(container.lastItemId(), "NAME")
- .setValue("foo");
- Assert.assertTrue(container.isModified());
- }
-
- @Test
- public void getSortableContainerPropertyIds_table_returnsAllPropertyIds()
- throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- Collection<?> sortableIds = container.getSortableContainerPropertyIds();
- Assert.assertTrue(sortableIds.contains("ID"));
- Assert.assertTrue(sortableIds.contains("NAME"));
- Assert.assertTrue(sortableIds.contains("AGE"));
- Assert.assertEquals(3, sortableIds.size());
- if (AllTests.db == DB.MSSQL || AllTests.db == DB.ORACLE) {
- Assert.assertFalse(sortableIds.contains("rownum"));
- }
- }
-
- @Test
- public void addOrderBy_table_shouldReorderResults() throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.firstItemId(), "NAME")
- .getValue());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- container.addOrderBy(new OrderBy("NAME", true));
- // Börje, Kalle, Pelle, Ville
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.firstItemId(), "NAME")
- .getValue());
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void addOrderBy_tableIllegalColumn_shouldFail() throws SQLException {
- SQLContainer container = new SQLContainer(new TableQuery("people",
- connectionPool, AllTests.sqlGen));
- container.addOrderBy(new OrderBy("asdf", true));
- }
-
- @Test
- public void sort_table_sortsByName() throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.firstItemId(), "NAME")
- .getValue());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- container.sort(new Object[] { "NAME" }, new boolean[] { true });
-
- // Börje, Kalle, Pelle, Ville
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.firstItemId(), "NAME")
- .getValue());
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void addFilter_table_filtersResults() throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals(4, container.size());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- container.addContainerFilter(new Like("NAME", "%lle"));
- // Ville, Kalle, Pelle
- Assert.assertEquals(3, container.size());
- Assert.assertEquals("Pelle",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void addContainerFilter_filtersResults() throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals(4, container.size());
-
- container.addContainerFilter("NAME", "Vi", false, false);
-
- // Ville
- Assert.assertEquals(1, container.size());
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void addContainerFilter_ignoreCase_filtersResults()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals(4, container.size());
-
- container.addContainerFilter("NAME", "vi", true, false);
-
- // Ville
- Assert.assertEquals(1, container.size());
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void removeAllContainerFilters_table_noFiltering()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals(4, container.size());
-
- container.addContainerFilter("NAME", "Vi", false, false);
-
- // Ville
- Assert.assertEquals(1, container.size());
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- container.removeAllContainerFilters();
-
- Assert.assertEquals(4, container.size());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void removeContainerFilters_table_noFiltering() throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals(4, container.size());
-
- container.addContainerFilter("NAME", "Vi", false, false);
-
- // Ville
- Assert.assertEquals(1, container.size());
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- container.removeContainerFilters("NAME");
-
- Assert.assertEquals(4, container.size());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
- @Test
- public void addFilter_tableBufferedItems_alsoFiltersBufferedItems()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals(4, container.size());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- Object id1 = container.addItem();
- container.getContainerProperty(id1, "NAME").setValue("Palle");
- Object id2 = container.addItem();
- container.getContainerProperty(id2, "NAME").setValue("Bengt");
-
- container.addContainerFilter(new Like("NAME", "%lle"));
-
- // Ville, Kalle, Pelle, Palle
- Assert.assertEquals(4, container.size());
- Assert.assertEquals(
- "Ville",
- container.getContainerProperty(container.getIdByIndex(0),
- "NAME").getValue());
- Assert.assertEquals(
- "Kalle",
- container.getContainerProperty(container.getIdByIndex(1),
- "NAME").getValue());
- Assert.assertEquals(
- "Pelle",
- container.getContainerProperty(container.getIdByIndex(2),
- "NAME").getValue());
- Assert.assertEquals(
- "Palle",
- container.getContainerProperty(container.getIdByIndex(3),
- "NAME").getValue());
-
- Assert.assertNull(container.getIdByIndex(4));
- Assert.assertNull(container.nextItemId(container.getIdByIndex(3)));
-
- Assert.assertFalse(container.containsId(id2));
- Assert.assertFalse(container.getItemIds().contains(id2));
-
- Assert.assertNull(container.getItem(id2));
- Assert.assertEquals(-1, container.indexOfId(id2));
-
- Assert.assertNotSame(id2, container.lastItemId());
- Assert.assertSame(id1, container.lastItemId());
- }
-
- @Test
- public void sort_tableBufferedItems_sortsBufferedItemsLastInOrderAdded()
- throws SQLException {
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
- // Ville, Kalle, Pelle, Börje
- Assert.assertEquals("Ville",
- container.getContainerProperty(container.firstItemId(), "NAME")
- .getValue());
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
-
- Object id1 = container.addItem();
- container.getContainerProperty(id1, "NAME").setValue("Wilbert");
- Object id2 = container.addItem();
- container.getContainerProperty(id2, "NAME").setValue("Albert");
-
- container.sort(new Object[] { "NAME" }, new boolean[] { true });
-
- // Börje, Kalle, Pelle, Ville, Wilbert, Albert
- Assert.assertEquals("Börje",
- container.getContainerProperty(container.firstItemId(), "NAME")
- .getValue());
- Assert.assertEquals(
- "Wilbert",
- container.getContainerProperty(
- container.getIdByIndex(container.size() - 2), "NAME")
- .getValue());
- Assert.assertEquals("Albert",
- container.getContainerProperty(container.lastItemId(), "NAME")
- .getValue());
- }
-
-}
+package com.vaadin.data.util.sqlcontainer; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Item; +import com.vaadin.data.util.filter.Like; +import com.vaadin.data.util.sqlcontainer.AllTests.DB; +import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool; +import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool; +import com.vaadin.data.util.sqlcontainer.query.OrderBy; +import com.vaadin.data.util.sqlcontainer.query.TableQuery; + +public class SQLContainerTableQueryTest { + + private static final int offset = AllTests.offset; + private static final String createGarbage = AllTests.createGarbage; + private JDBCConnectionPool connectionPool; + + @Before + public void setUp() throws SQLException { + + try { + connectionPool = new SimpleJDBCConnectionPool(AllTests.dbDriver, + AllTests.dbURL, AllTests.dbUser, AllTests.dbPwd, 2, 2); + } catch (SQLException e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + + DataGenerator.addPeopleToDatabase(connectionPool); + } + + @After + public void tearDown() { + if (connectionPool != null) { + connectionPool.destroy(); + } + } + + @Test + public void constructor_withTableQuery_shouldSucceed() throws SQLException { + new SQLContainer(new TableQuery("people", connectionPool, + AllTests.sqlGen)); + } + + @Test + public void containsId_withTableQueryAndExistingId_returnsTrue() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertTrue(container.containsId(new RowId( + new Object[] { 1 + offset }))); + } + + @Test + public void containsId_withTableQueryAndNonexistingId_returnsFalse() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertFalse(container.containsId(new RowId( + new Object[] { 1337 + offset }))); + } + + @Test + public void getContainerProperty_tableExistingItemIdAndPropertyId_returnsProperty() + throws SQLException { + TableQuery t = new TableQuery("people", connectionPool, AllTests.sqlGen); + SQLContainer container = new SQLContainer(t); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + "Ville", + container + .getContainerProperty( + new RowId(new Object[] { new BigDecimal( + 0 + offset) }), "NAME").getValue()); + } else { + Assert.assertEquals( + "Ville", + container.getContainerProperty( + new RowId(new Object[] { 0 + offset }), "NAME") + .getValue()); + } + } + + @Test + public void getContainerProperty_tableExistingItemIdAndNonexistingPropertyId_returnsNull() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertNull(container.getContainerProperty(new RowId( + new Object[] { 1 + offset }), "asdf")); + } + + @Test + public void getContainerProperty_tableNonexistingItemId_returnsNull() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertNull(container.getContainerProperty(new RowId( + new Object[] { 1337 + offset }), "NAME")); + } + + @Test + public void getContainerPropertyIds_table_returnsIDAndNAME() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Collection<?> propertyIds = container.getContainerPropertyIds(); + Assert.assertEquals(3, propertyIds.size()); + Assert.assertArrayEquals(new String[] { "ID", "NAME", "AGE" }, + propertyIds.toArray()); + } + + @Test + public void getItem_tableExistingItemId_returnsItem() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Item item; + if (AllTests.db == DB.ORACLE) { + item = container.getItem(new RowId(new Object[] { new BigDecimal( + 0 + offset) })); + } else { + item = container.getItem(new RowId(new Object[] { 0 + offset })); + } + Assert.assertNotNull(item); + Assert.assertEquals("Ville", item.getItemProperty("NAME").getValue()); + } + + @Test + public void getItem_commitedModifiedAndRefreshed() throws SQLException { + String OLD_VALUE = "SomeValue"; //$NON-NLS-1$ + String NEW_VALUE = "OtherValue"; //$NON-NLS-1$ + + SQLContainer container = new SQLContainer(new TableQuery("people", //$NON-NLS-1$ + connectionPool, AllTests.sqlGen)); + Object itemID = container.addItem(); + Item item = container.getItem(itemID); + item.getItemProperty("NAME").setValue(OLD_VALUE); //$NON-NLS-1$ + container.commit(); + + itemID = container.getIdByIndex(container.size() - 1); + item = container.getItem(itemID); + Assert.assertEquals(OLD_VALUE, item.getItemProperty("NAME") //$NON-NLS-1$ + .getValue()); + item.getItemProperty("NAME").setValue(NEW_VALUE); //$NON-NLS-1$ + + // refresh the container which free's the caches + // and the modified cache keeps untouched which is a really powerful + // feature + container.refresh(); + + // access the item again will use the item from the modified cache. + item = container.getItem(itemID); + Assert.assertEquals(NEW_VALUE, item.getItemProperty("NAME") //$NON-NLS-1$ + .getValue()); + } + + @Test + public void getItem_table5000RowsWithParameter1337_returnsItemWithId1337() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + + Item item; + if (AllTests.db == DB.ORACLE) { + item = container.getItem(new RowId(new Object[] { new BigDecimal( + 1337 + offset) })); + Assert.assertNotNull(item); + Assert.assertEquals(new BigDecimal(1337 + offset), item + .getItemProperty("ID").getValue()); + } else { + item = container.getItem(new RowId(new Object[] { 1337 + offset })); + Assert.assertNotNull(item); + Assert.assertEquals(1337 + offset, item.getItemProperty("ID") + .getValue()); + } + Assert.assertEquals("Person 1337", item.getItemProperty("NAME") + .getValue()); + } + + @Test + public void getItemIds_table_returnsItemIdsWithKeys0through3() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Collection<?> itemIds = container.getItemIds(); + Assert.assertEquals(4, itemIds.size()); + RowId zero = new RowId(new Object[] { 0 + offset }); + RowId one = new RowId(new Object[] { 1 + offset }); + RowId two = new RowId(new Object[] { 2 + offset }); + RowId three = new RowId(new Object[] { 3 + offset }); + if (AllTests.db == DB.ORACLE) { + String[] correct = new String[] { "1", "2", "3", "4" }; + List<String> oracle = new ArrayList<String>(); + for (Object o : itemIds) { + oracle.add(o.toString()); + } + Assert.assertArrayEquals(correct, oracle.toArray()); + } else { + Assert.assertArrayEquals(new Object[] { zero, one, two, three }, + itemIds.toArray()); + } + } + + @Test + public void getType_tableNAMEPropertyId_returnsString() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertEquals(String.class, container.getType("NAME")); + } + + @Test + public void getType_tableIDPropertyId_returnsInteger() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals(BigDecimal.class, container.getType("ID")); + } else { + Assert.assertEquals(Integer.class, container.getType("ID")); + } + } + + @Test + public void getType_tableNonexistingPropertyId_returnsNull() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertNull(container.getType("asdf")); + } + + @Test + public void size_table_returnsFour() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertEquals(4, container.size()); + } + + @Test + public void size_tableOneAddedItem_returnsFive() throws SQLException { + Connection conn = connectionPool.reserveConnection(); + Statement statement = conn.createStatement(); + if (AllTests.db == DB.MSSQL) { + statement.executeUpdate("insert into people values('Bengt', 30)"); + } else { + statement + .executeUpdate("insert into people values(default, 'Bengt', 30)"); + } + statement.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertEquals(5, container.size()); + } + + @Test + public void indexOfId_tableWithParameterThree_returnsThree() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals(3, container.indexOfId(new RowId( + new Object[] { new BigDecimal(3 + offset) }))); + } else { + Assert.assertEquals(3, + container.indexOfId(new RowId(new Object[] { 3 + offset }))); + } + } + + @Test + public void indexOfId_table5000RowsWithParameter1337_returns1337() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + TableQuery q = new TableQuery("people", connectionPool, AllTests.sqlGen); + SQLContainer container = new SQLContainer(q); + if (AllTests.db == DB.ORACLE) { + container.getItem(new RowId(new Object[] { new BigDecimal( + 1337 + offset) })); + Assert.assertEquals(1337, container.indexOfId(new RowId( + new Object[] { new BigDecimal(1337 + offset) }))); + } else { + container.getItem(new RowId(new Object[] { 1337 + offset })); + Assert.assertEquals(1337, container.indexOfId(new RowId( + new Object[] { 1337 + offset }))); + } + } + + @Test + public void getIdByIndex_table5000rowsIndex1337_returnsRowId1337() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object itemId = container.getIdByIndex(1337); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + new RowId(new Object[] { 1337 + offset }).toString(), + itemId.toString()); + } else { + Assert.assertEquals(new RowId(new Object[] { 1337 + offset }), + itemId); + } + } + + @Test + public void getIdByIndex_tableWithPaging5000rowsIndex1337_returnsRowId1337() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + Object itemId = container.getIdByIndex(1337); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + new RowId(new Object[] { 1337 + offset }).toString(), + itemId.toString()); + } else { + Assert.assertEquals(new RowId(new Object[] { 1337 + offset }), + itemId); + } + } + + @Test + public void nextItemId_tableCurrentItem1337_returnsItem1338() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object itemId = container.getIdByIndex(1337); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + new RowId(new Object[] { 1338 + offset }).toString(), + container.nextItemId(itemId).toString()); + } else { + Assert.assertEquals(new RowId(new Object[] { 1338 + offset }), + container.nextItemId(itemId)); + } + } + + @Test + public void prevItemId_tableCurrentItem1337_returns1336() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object itemId = container.getIdByIndex(1337); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + new RowId(new Object[] { 1336 + offset }).toString(), + container.prevItemId(itemId).toString()); + } else { + Assert.assertEquals(new RowId(new Object[] { 1336 + offset }), + container.prevItemId(itemId)); + } + } + + @Test + public void firstItemId_table_returnsItemId0() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + new RowId(new Object[] { 0 + offset }).toString(), + container.firstItemId().toString()); + } else { + Assert.assertEquals(new RowId(new Object[] { 0 + offset }), + container.firstItemId()); + } + } + + @Test + public void lastItemId_table5000Rows_returnsItemId4999() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertEquals( + new RowId(new Object[] { 4999 + offset }).toString(), + container.lastItemId().toString()); + } else { + Assert.assertEquals(new RowId(new Object[] { 4999 + offset }), + container.lastItemId()); + } + } + + @Test + public void isFirstId_tableActualFirstId_returnsTrue() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertTrue(container.isFirstId(new RowId( + new Object[] { new BigDecimal(0 + offset) }))); + } else { + Assert.assertTrue(container.isFirstId(new RowId( + new Object[] { 0 + offset }))); + } + } + + @Test + public void isFirstId_tableSecondId_returnsFalse() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertFalse(container.isFirstId(new RowId( + new Object[] { new BigDecimal(1 + offset) }))); + } else { + Assert.assertFalse(container.isFirstId(new RowId( + new Object[] { 1 + offset }))); + } + } + + @Test + public void isLastId_tableSecondId_returnsFalse() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertFalse(container.isLastId(new RowId( + new Object[] { new BigDecimal(1 + offset) }))); + } else { + Assert.assertFalse(container.isLastId(new RowId( + new Object[] { 1 + offset }))); + } + } + + @Test + public void isLastId_tableLastId_returnsTrue() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertTrue(container.isLastId(new RowId( + new Object[] { new BigDecimal(3 + offset) }))); + } else { + Assert.assertTrue(container.isLastId(new RowId( + new Object[] { 3 + offset }))); + } + } + + @Test + public void isLastId_table5000RowsLastId_returnsTrue() throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + if (AllTests.db == DB.ORACLE) { + Assert.assertTrue(container.isLastId(new RowId( + new Object[] { new BigDecimal(4999 + offset) }))); + } else { + Assert.assertTrue(container.isLastId(new RowId( + new Object[] { 4999 + offset }))); + } + } + + @Test + public void allIdsFound_table5000RowsLastId_shouldSucceed() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + for (int i = 0; i < 5000; i++) { + Assert.assertTrue(container.containsId(container.getIdByIndex(i))); + } + } + + @Test + public void allIdsFound_table5000RowsLastId_autoCommit_shouldSucceed() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.setAutoCommit(true); + for (int i = 0; i < 5000; i++) { + Assert.assertTrue(container.containsId(container.getIdByIndex(i))); + } + } + + @Test + public void refresh_table_sizeShouldUpdate() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertEquals(4, container.size()); + DataGenerator.addFiveThousandPeople(connectionPool); + container.refresh(); + Assert.assertEquals(5000, container.size()); + } + + @Test + public void refresh_tableWithoutCallingRefresh_sizeShouldNotUpdate() + throws SQLException { + // Yeah, this is a weird one. We're testing that the size doesn't update + // after adding lots of items unless we call refresh inbetween. This to + // make sure that the refresh method actually refreshes stuff and isn't + // a NOP. + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertEquals(4, container.size()); + DataGenerator.addFiveThousandPeople(connectionPool); + Assert.assertEquals(4, container.size()); + } + + @Test + public void setAutoCommit_table_shouldSucceed() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.setAutoCommit(true); + Assert.assertTrue(container.isAutoCommit()); + container.setAutoCommit(false); + Assert.assertFalse(container.isAutoCommit()); + } + + @Test + public void getPageLength_table_returnsDefault100() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertEquals(100, container.getPageLength()); + } + + @Test + public void setPageLength_table_shouldSucceed() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.setPageLength(20); + Assert.assertEquals(20, container.getPageLength()); + container.setPageLength(200); + Assert.assertEquals(200, container.getPageLength()); + } + + @Test(expected = UnsupportedOperationException.class) + public void addContainerProperty_normal_isUnsupported() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addContainerProperty("asdf", String.class, ""); + } + + @Test(expected = UnsupportedOperationException.class) + public void removeContainerProperty_normal_isUnsupported() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.removeContainerProperty("asdf"); + } + + @Test(expected = UnsupportedOperationException.class) + public void addItemObject_normal_isUnsupported() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItem("asdf"); + } + + @Test(expected = UnsupportedOperationException.class) + public void addItemAfterObjectObject_normal_isUnsupported() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItemAfter("asdf", "foo"); + } + + @Test(expected = UnsupportedOperationException.class) + public void addItemAtIntObject_normal_isUnsupported() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItemAt(2, "asdf"); + } + + @Test(expected = UnsupportedOperationException.class) + public void addItemAtInt_normal_isUnsupported() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItemAt(2); + } + + @Test(expected = UnsupportedOperationException.class) + public void addItemAfterObject_normal_isUnsupported() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItemAfter("asdf"); + } + + @Test + public void addItem_tableAddOneNewItem_returnsItemId() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object itemId = container.addItem(); + Assert.assertNotNull(itemId); + } + + @Test + public void addItem_tableAddOneNewItem_autoCommit_returnsFinalItemId() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + container.setAutoCommit(true); + Object itemId = container.addItem(); + Assert.assertNotNull(itemId); + Assert.assertTrue(itemId instanceof RowId); + Assert.assertFalse(itemId instanceof TemporaryRowId); + } + + @Test + public void addItem_tableAddOneNewItem_autoCommit_sizeIsIncreased() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + container.setAutoCommit(true); + int originalSize = container.size(); + container.addItem(); + Assert.assertEquals(originalSize + 1, container.size()); + } + + @Test + public void addItem_tableAddOneNewItem_shouldChangeSize() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + int size = container.size(); + container.addItem(); + Assert.assertEquals(size + 1, container.size()); + } + + @Test + public void addItem_tableAddTwoNewItems_shouldChangeSize() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + int size = container.size(); + Object id1 = container.addItem(); + Object id2 = container.addItem(); + Assert.assertEquals(size + 2, container.size()); + Assert.assertNotSame(id1, id2); + Assert.assertFalse(id1.equals(id2)); + } + + @Test + public void nextItemId_tableNewlyAddedItem_returnsNewlyAdded() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object lastId = container.lastItemId(); + Object id = container.addItem(); + Assert.assertEquals(id, container.nextItemId(lastId)); + } + + @Test + public void lastItemId_tableNewlyAddedItem_returnsNewlyAdded() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object lastId = container.lastItemId(); + Object id = container.addItem(); + Assert.assertEquals(id, container.lastItemId()); + Assert.assertNotSame(lastId, container.lastItemId()); + } + + @Test + public void indexOfId_tableNewlyAddedItem_returnsFour() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertEquals(4, container.indexOfId(id)); + } + + @Test + public void getItem_tableNewlyAddedItem_returnsNewlyAdded() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertNotNull(container.getItem(id)); + } + + @Test + public void getItemIds_tableNewlyAddedItem_containsNewlyAdded() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertTrue(container.getItemIds().contains(id)); + } + + @Test + public void getContainerProperty_tableNewlyAddedItem_returnsPropertyOfNewlyAddedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Item item = container.getItem(id); + item.getItemProperty("NAME").setValue("asdf"); + Assert.assertEquals("asdf", container.getContainerProperty(id, "NAME") + .getValue()); + } + + @Test + public void containsId_tableNewlyAddedItem_returnsTrue() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertTrue(container.containsId(id)); + } + + @Test + public void prevItemId_tableTwoNewlyAddedItems_returnsFirstAddedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id1 = container.addItem(); + Object id2 = container.addItem(); + Assert.assertEquals(id1, container.prevItemId(id2)); + } + + @Test + public void firstItemId_tableEmptyResultSet_returnsFirstAddedItem() + throws SQLException { + DataGenerator.createGarbage(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("garbage", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertSame(id, container.firstItemId()); + } + + @Test + public void isFirstId_tableEmptyResultSet_returnsFirstAddedItem() + throws SQLException { + DataGenerator.createGarbage(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("garbage", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertTrue(container.isFirstId(id)); + } + + @Test + public void isLastId_tableOneItemAdded_returnsTrueForAddedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertTrue(container.isLastId(id)); + } + + @Test + public void isLastId_tableTwoItemsAdded_returnsTrueForLastAddedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItem(); + Object id2 = container.addItem(); + Assert.assertTrue(container.isLastId(id2)); + } + + @Test + public void getIdByIndex_tableOneItemAddedLastIndexInContainer_returnsAddedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertEquals(id, container.getIdByIndex(container.size() - 1)); + } + + @Test + public void removeItem_tableNoAddedItems_removesItemFromContainer() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + int size = container.size(); + Object id = container.firstItemId(); + Assert.assertTrue(container.removeItem(id)); + Assert.assertNotSame(id, container.firstItemId()); + Assert.assertEquals(size - 1, container.size()); + } + + @Test + public void containsId_tableRemovedItem_returnsFalse() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.firstItemId(); + Assert.assertTrue(container.removeItem(id)); + Assert.assertFalse(container.containsId(id)); + } + + @Test + public void removeItem_tableOneAddedItem_removesTheAddedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + int size = container.size(); + Assert.assertTrue(container.removeItem(id)); + Assert.assertFalse(container.containsId(id)); + Assert.assertEquals(size - 1, container.size()); + } + + @Test + public void getItem_tableItemRemoved_returnsNull() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.firstItemId(); + Assert.assertTrue(container.removeItem(id)); + Assert.assertNull(container.getItem(id)); + } + + @Test + public void getItem_tableAddedItemRemoved_returnsNull() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertNotNull(container.getItem(id)); + Assert.assertTrue(container.removeItem(id)); + Assert.assertNull(container.getItem(id)); + } + + @Test + public void getItemIds_tableItemRemoved_shouldNotContainRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.firstItemId(); + Assert.assertTrue(container.getItemIds().contains(id)); + Assert.assertTrue(container.removeItem(id)); + Assert.assertFalse(container.getItemIds().contains(id)); + } + + @Test + public void getItemIds_tableAddedItemRemoved_shouldNotContainRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertTrue(container.getItemIds().contains(id)); + Assert.assertTrue(container.removeItem(id)); + Assert.assertFalse(container.getItemIds().contains(id)); + } + + @Test + public void containsId_tableItemRemoved_returnsFalse() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.firstItemId(); + Assert.assertTrue(container.containsId(id)); + Assert.assertTrue(container.removeItem(id)); + Assert.assertFalse(container.containsId(id)); + } + + @Test + public void containsId_tableAddedItemRemoved_returnsFalse() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + Object id = container.addItem(); + Assert.assertTrue(container.containsId(id)); + Assert.assertTrue(container.removeItem(id)); + Assert.assertFalse(container.containsId(id)); + } + + @Test + public void nextItemId_tableItemRemoved_skipsRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object first = container.getIdByIndex(0); + Object second = container.getIdByIndex(1); + Object third = container.getIdByIndex(2); + Assert.assertTrue(container.removeItem(second)); + Assert.assertEquals(third, container.nextItemId(first)); + } + + @Test + public void nextItemId_tableAddedItemRemoved_skipsRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object first = container.lastItemId(); + Object second = container.addItem(); + Object third = container.addItem(); + Assert.assertTrue(container.removeItem(second)); + Assert.assertEquals(third, container.nextItemId(first)); + } + + @Test + public void prevItemId_tableItemRemoved_skipsRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object first = container.getIdByIndex(0); + Object second = container.getIdByIndex(1); + Object third = container.getIdByIndex(2); + Assert.assertTrue(container.removeItem(second)); + Assert.assertEquals(first, container.prevItemId(third)); + } + + @Test + public void prevItemId_tableAddedItemRemoved_skipsRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object first = container.lastItemId(); + Object second = container.addItem(); + Object third = container.addItem(); + Assert.assertTrue(container.removeItem(second)); + Assert.assertEquals(first, container.prevItemId(third)); + } + + @Test + public void firstItemId_tableFirstItemRemoved_resultChanges() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object first = container.firstItemId(); + Assert.assertTrue(container.removeItem(first)); + Assert.assertNotSame(first, container.firstItemId()); + } + + @Test + public void firstItemId_tableNewlyAddedFirstItemRemoved_resultChanges() + throws SQLException { + DataGenerator.createGarbage(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("garbage", + connectionPool, AllTests.sqlGen)); + Object first = container.addItem(); + Object second = container.addItem(); + Assert.assertSame(first, container.firstItemId()); + Assert.assertTrue(container.removeItem(first)); + Assert.assertSame(second, container.firstItemId()); + } + + @Test + public void lastItemId_tableLastItemRemoved_resultChanges() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object last = container.lastItemId(); + Assert.assertTrue(container.removeItem(last)); + Assert.assertNotSame(last, container.lastItemId()); + } + + @Test + public void lastItemId_tableAddedLastItemRemoved_resultChanges() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object last = container.addItem(); + Assert.assertSame(last, container.lastItemId()); + Assert.assertTrue(container.removeItem(last)); + Assert.assertNotSame(last, container.lastItemId()); + } + + @Test + public void isFirstId_tableFirstItemRemoved_returnsFalse() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object first = container.firstItemId(); + Assert.assertTrue(container.removeItem(first)); + Assert.assertFalse(container.isFirstId(first)); + } + + @Test + public void isFirstId_tableAddedFirstItemRemoved_returnsFalse() + throws SQLException { + DataGenerator.createGarbage(connectionPool); + SQLContainer container = new SQLContainer(new TableQuery("garbage", + connectionPool, AllTests.sqlGen)); + Object first = container.addItem(); + container.addItem(); + Assert.assertSame(first, container.firstItemId()); + Assert.assertTrue(container.removeItem(first)); + Assert.assertFalse(container.isFirstId(first)); + } + + @Test + public void isLastId_tableLastItemRemoved_returnsFalse() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object last = container.lastItemId(); + Assert.assertTrue(container.removeItem(last)); + Assert.assertFalse(container.isLastId(last)); + } + + @Test + public void isLastId_tableAddedLastItemRemoved_returnsFalse() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object last = container.addItem(); + Assert.assertSame(last, container.lastItemId()); + Assert.assertTrue(container.removeItem(last)); + Assert.assertFalse(container.isLastId(last)); + } + + @Test + public void indexOfId_tableItemRemoved_returnsNegOne() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.getIdByIndex(2); + Assert.assertTrue(container.removeItem(id)); + Assert.assertEquals(-1, container.indexOfId(id)); + } + + @Test + public void indexOfId_tableAddedItemRemoved_returnsNegOne() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + Assert.assertTrue(container.indexOfId(id) != -1); + Assert.assertTrue(container.removeItem(id)); + Assert.assertEquals(-1, container.indexOfId(id)); + } + + @Test + public void getIdByIndex_tableItemRemoved_resultChanges() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.getIdByIndex(2); + Assert.assertTrue(container.removeItem(id)); + Assert.assertNotSame(id, container.getIdByIndex(2)); + } + + @Test + public void getIdByIndex_tableAddedItemRemoved_resultChanges() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object id = container.addItem(); + container.addItem(); + int index = container.indexOfId(id); + Assert.assertTrue(container.removeItem(id)); + Assert.assertNotSame(id, container.getIdByIndex(index)); + } + + @Test + public void removeAllItems_table_shouldSucceed() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertTrue(container.removeAllItems()); + Assert.assertEquals(0, container.size()); + } + + @Test + public void removeAllItems_tableAddedItems_shouldSucceed() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addItem(); + container.addItem(); + Assert.assertTrue(container.removeAllItems()); + Assert.assertEquals(0, container.size()); + } + + @Test + public void commit_tableAddedItem_shouldBeWrittenToDB() throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + Object id = container.addItem(); + container.getContainerProperty(id, "NAME").setValue("New Name"); + Assert.assertTrue(id instanceof TemporaryRowId); + Assert.assertSame(id, container.lastItemId()); + container.commit(); + Assert.assertFalse(container.lastItemId() instanceof TemporaryRowId); + Assert.assertEquals("New Name", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void commit_tableTwoAddedItems_shouldBeWrittenToDB() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + Object id = container.addItem(); + Object id2 = container.addItem(); + container.getContainerProperty(id, "NAME").setValue("Herbert"); + container.getContainerProperty(id2, "NAME").setValue("Larry"); + Assert.assertTrue(id2 instanceof TemporaryRowId); + Assert.assertSame(id2, container.lastItemId()); + container.commit(); + Object nextToLast = container.getIdByIndex(container.size() - 2); + Assert.assertFalse(nextToLast instanceof TemporaryRowId); + Assert.assertEquals("Herbert", + container.getContainerProperty(nextToLast, "NAME").getValue()); + Assert.assertFalse(container.lastItemId() instanceof TemporaryRowId); + Assert.assertEquals("Larry", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void commit_tableRemovedItem_shouldBeRemovedFromDB() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + Object last = container.lastItemId(); + container.removeItem(last); + container.commit(); + Assert.assertFalse(last.equals(container.lastItemId())); + } + + @Test + public void commit_tableLastItemUpdated_shouldUpdateRowInDB() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + Object last = container.lastItemId(); + container.getContainerProperty(last, "NAME").setValue("Donald"); + container.commit(); + Assert.assertEquals("Donald", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void rollback_tableItemAdded_discardsAddedItem() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + int size = container.size(); + Object id = container.addItem(); + container.getContainerProperty(id, "NAME").setValue("foo"); + Assert.assertEquals(size + 1, container.size()); + container.rollback(); + Assert.assertEquals(size, container.size()); + Assert.assertFalse("foo".equals(container.getContainerProperty( + container.lastItemId(), "NAME").getValue())); + } + + @Test + public void rollback_tableItemRemoved_restoresRemovedItem() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + int size = container.size(); + Object last = container.lastItemId(); + container.removeItem(last); + Assert.assertEquals(size - 1, container.size()); + container.rollback(); + Assert.assertEquals(size, container.size()); + Assert.assertEquals(last, container.lastItemId()); + } + + @Test + public void rollback_tableItemChanged_discardsChanges() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Object last = container.lastItemId(); + container.getContainerProperty(last, "NAME").setValue("foo"); + container.rollback(); + Assert.assertFalse("foo".equals(container.getContainerProperty( + container.lastItemId(), "NAME").getValue())); + } + + @Test + public void itemChangeNotification_table_isModifiedReturnsTrue() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertFalse(container.isModified()); + RowItem last = (RowItem) container.getItem(container.lastItemId()); + container.itemChangeNotification(last); + Assert.assertTrue(container.isModified()); + } + + @Test + public void itemSetChangeListeners_table_shouldFire() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + ItemSetChangeListener listener = EasyMock + .createMock(ItemSetChangeListener.class); + listener.containerItemSetChange(EasyMock.isA(ItemSetChangeEvent.class)); + EasyMock.replay(listener); + + container.addListener(listener); + container.addItem(); + + EasyMock.verify(listener); + } + + @Test + public void itemSetChangeListeners_tableItemRemoved_shouldFire() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + ItemSetChangeListener listener = EasyMock + .createMock(ItemSetChangeListener.class); + listener.containerItemSetChange(EasyMock.isA(ItemSetChangeEvent.class)); + EasyMock.expectLastCall().anyTimes(); + EasyMock.replay(listener); + + container.addListener(listener); + container.removeItem(container.lastItemId()); + + EasyMock.verify(listener); + } + + @Test + public void removeListener_table_shouldNotFire() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + ItemSetChangeListener listener = EasyMock + .createMock(ItemSetChangeListener.class); + EasyMock.replay(listener); + + container.addListener(listener); + container.removeListener(listener); + container.addItem(); + + EasyMock.verify(listener); + } + + @Test + public void isModified_tableRemovedItem_returnsTrue() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertFalse(container.isModified()); + container.removeItem(container.lastItemId()); + Assert.assertTrue(container.isModified()); + } + + @Test + public void isModified_tableAddedItem_returnsTrue() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertFalse(container.isModified()); + container.addItem(); + Assert.assertTrue(container.isModified()); + } + + @Test + public void isModified_tableChangedItem_returnsTrue() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Assert.assertFalse(container.isModified()); + container.getContainerProperty(container.lastItemId(), "NAME") + .setValue("foo"); + Assert.assertTrue(container.isModified()); + } + + @Test + public void getSortableContainerPropertyIds_table_returnsAllPropertyIds() + throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + Collection<?> sortableIds = container.getSortableContainerPropertyIds(); + Assert.assertTrue(sortableIds.contains("ID")); + Assert.assertTrue(sortableIds.contains("NAME")); + Assert.assertTrue(sortableIds.contains("AGE")); + Assert.assertEquals(3, sortableIds.size()); + if (AllTests.db == DB.MSSQL || AllTests.db == DB.ORACLE) { + Assert.assertFalse(sortableIds.contains("rownum")); + } + } + + @Test + public void addOrderBy_table_shouldReorderResults() throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals("Ville", + container.getContainerProperty(container.firstItemId(), "NAME") + .getValue()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + container.addOrderBy(new OrderBy("NAME", true)); + // Börje, Kalle, Pelle, Ville + Assert.assertEquals("Börje", + container.getContainerProperty(container.firstItemId(), "NAME") + .getValue()); + Assert.assertEquals("Ville", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test(expected = IllegalArgumentException.class) + public void addOrderBy_tableIllegalColumn_shouldFail() throws SQLException { + SQLContainer container = new SQLContainer(new TableQuery("people", + connectionPool, AllTests.sqlGen)); + container.addOrderBy(new OrderBy("asdf", true)); + } + + @Test + public void sort_table_sortsByName() throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals("Ville", + container.getContainerProperty(container.firstItemId(), "NAME") + .getValue()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + container.sort(new Object[] { "NAME" }, new boolean[] { true }); + + // Börje, Kalle, Pelle, Ville + Assert.assertEquals("Börje", + container.getContainerProperty(container.firstItemId(), "NAME") + .getValue()); + Assert.assertEquals("Ville", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void addFilter_table_filtersResults() throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals(4, container.size()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + container.addContainerFilter(new Like("NAME", "%lle")); + // Ville, Kalle, Pelle + Assert.assertEquals(3, container.size()); + Assert.assertEquals("Pelle", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void addContainerFilter_filtersResults() throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals(4, container.size()); + + container.addContainerFilter("NAME", "Vi", false, false); + + // Ville + Assert.assertEquals(1, container.size()); + Assert.assertEquals("Ville", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void addContainerFilter_ignoreCase_filtersResults() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals(4, container.size()); + + container.addContainerFilter("NAME", "vi", true, false); + + // Ville + Assert.assertEquals(1, container.size()); + Assert.assertEquals("Ville", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void removeAllContainerFilters_table_noFiltering() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals(4, container.size()); + + container.addContainerFilter("NAME", "Vi", false, false); + + // Ville + Assert.assertEquals(1, container.size()); + Assert.assertEquals("Ville", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + container.removeAllContainerFilters(); + + Assert.assertEquals(4, container.size()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void removeContainerFilters_table_noFiltering() throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals(4, container.size()); + + container.addContainerFilter("NAME", "Vi", false, false); + + // Ville + Assert.assertEquals(1, container.size()); + Assert.assertEquals("Ville", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + container.removeContainerFilters("NAME"); + + Assert.assertEquals(4, container.size()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + + @Test + public void addFilter_tableBufferedItems_alsoFiltersBufferedItems() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals(4, container.size()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + Object id1 = container.addItem(); + container.getContainerProperty(id1, "NAME").setValue("Palle"); + Object id2 = container.addItem(); + container.getContainerProperty(id2, "NAME").setValue("Bengt"); + + container.addContainerFilter(new Like("NAME", "%lle")); + + // Ville, Kalle, Pelle, Palle + Assert.assertEquals(4, container.size()); + Assert.assertEquals( + "Ville", + container.getContainerProperty(container.getIdByIndex(0), + "NAME").getValue()); + Assert.assertEquals( + "Kalle", + container.getContainerProperty(container.getIdByIndex(1), + "NAME").getValue()); + Assert.assertEquals( + "Pelle", + container.getContainerProperty(container.getIdByIndex(2), + "NAME").getValue()); + Assert.assertEquals( + "Palle", + container.getContainerProperty(container.getIdByIndex(3), + "NAME").getValue()); + + Assert.assertNull(container.getIdByIndex(4)); + Assert.assertNull(container.nextItemId(container.getIdByIndex(3))); + + Assert.assertFalse(container.containsId(id2)); + Assert.assertFalse(container.getItemIds().contains(id2)); + + Assert.assertNull(container.getItem(id2)); + Assert.assertEquals(-1, container.indexOfId(id2)); + + Assert.assertNotSame(id2, container.lastItemId()); + Assert.assertSame(id1, container.lastItemId()); + } + + @Test + public void sort_tableBufferedItems_sortsBufferedItemsLastInOrderAdded() + throws SQLException { + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + // Ville, Kalle, Pelle, Börje + Assert.assertEquals("Ville", + container.getContainerProperty(container.firstItemId(), "NAME") + .getValue()); + Assert.assertEquals("Börje", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + + Object id1 = container.addItem(); + container.getContainerProperty(id1, "NAME").setValue("Wilbert"); + Object id2 = container.addItem(); + container.getContainerProperty(id2, "NAME").setValue("Albert"); + + container.sort(new Object[] { "NAME" }, new boolean[] { true }); + + // Börje, Kalle, Pelle, Ville, Wilbert, Albert + Assert.assertEquals("Börje", + container.getContainerProperty(container.firstItemId(), "NAME") + .getValue()); + Assert.assertEquals( + "Wilbert", + container.getContainerProperty( + container.getIdByIndex(container.size() - 2), "NAME") + .getValue()); + Assert.assertEquals("Albert", + container.getContainerProperty(container.lastItemId(), "NAME") + .getValue()); + } + +} diff --git a/tests/server-side/com/vaadin/data/util/sqlcontainer/generator/SQLGeneratorsTest.java b/tests/server-side/com/vaadin/data/util/sqlcontainer/generator/SQLGeneratorsTest.java index 58dcdb3227..e62a06e6e1 100644 --- a/tests/server-side/com/vaadin/data/util/sqlcontainer/generator/SQLGeneratorsTest.java +++ b/tests/server-side/com/vaadin/data/util/sqlcontainer/generator/SQLGeneratorsTest.java @@ -1,241 +1,241 @@ -package com.vaadin.data.util.sqlcontainer.generator;
-
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.vaadin.data.Container.Filter;
-import com.vaadin.data.util.filter.Like;
-import com.vaadin.data.util.filter.Or;
-import com.vaadin.data.util.sqlcontainer.AllTests;
-import com.vaadin.data.util.sqlcontainer.DataGenerator;
-import com.vaadin.data.util.sqlcontainer.RowItem;
-import com.vaadin.data.util.sqlcontainer.SQLContainer;
-import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;
-import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool;
-import com.vaadin.data.util.sqlcontainer.query.OrderBy;
-import com.vaadin.data.util.sqlcontainer.query.TableQuery;
-import com.vaadin.data.util.sqlcontainer.query.generator.DefaultSQLGenerator;
-import com.vaadin.data.util.sqlcontainer.query.generator.MSSQLGenerator;
-import com.vaadin.data.util.sqlcontainer.query.generator.OracleGenerator;
-import com.vaadin.data.util.sqlcontainer.query.generator.SQLGenerator;
-import com.vaadin.data.util.sqlcontainer.query.generator.StatementHelper;
-
-public class SQLGeneratorsTest {
- private JDBCConnectionPool connectionPool;
-
- @Before
- public void setUp() throws SQLException {
-
- try {
- connectionPool = new SimpleJDBCConnectionPool(AllTests.dbDriver,
- AllTests.dbURL, AllTests.dbUser, AllTests.dbPwd, 2, 2);
- } catch (SQLException e) {
- e.printStackTrace();
- Assert.fail(e.getMessage());
- }
-
- DataGenerator.addPeopleToDatabase(connectionPool);
- }
-
- @After
- public void tearDown() {
- if (connectionPool != null) {
- connectionPool.destroy();
- }
- }
-
- @Test
- public void generateSelectQuery_basicQuery_shouldSucceed() {
- SQLGenerator sg = new DefaultSQLGenerator();
- StatementHelper sh = sg.generateSelectQuery("TABLE", null, null, 0, 0,
- null);
- Assert.assertEquals(sh.getQueryString(), "SELECT * FROM TABLE");
- }
-
- @Test
- public void generateSelectQuery_pagingAndColumnsSet_shouldSucceed() {
- SQLGenerator sg = new DefaultSQLGenerator();
- StatementHelper sh = sg.generateSelectQuery("TABLE", null, null, 4, 8,
- "COL1, COL2, COL3");
- Assert.assertEquals(sh.getQueryString(),
- "SELECT COL1, COL2, COL3 FROM TABLE LIMIT 8 OFFSET 4");
- }
-
- /**
- * Note: Only tests one kind of filter and ordering.
- */
- @Test
- public void generateSelectQuery_filtersAndOrderingSet_shouldSucceed() {
- SQLGenerator sg = new DefaultSQLGenerator();
- List<com.vaadin.data.Container.Filter> f = new ArrayList<Filter>();
- f.add(new Like("name", "%lle"));
- List<OrderBy> ob = Arrays.asList(new OrderBy("name", true));
- StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 0, 0, null);
- Assert.assertEquals(sh.getQueryString(),
- "SELECT * FROM TABLE WHERE \"name\" LIKE ? ORDER BY \"name\" ASC");
- }
-
- @Test
- public void generateSelectQuery_filtersAndOrderingSet_exclusiveFilteringMode_shouldSucceed() {
- SQLGenerator sg = new DefaultSQLGenerator();
- List<Filter> f = new ArrayList<Filter>();
- f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%")));
- List<OrderBy> ob = Arrays.asList(new OrderBy("name", true));
- StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 0, 0, null);
- // TODO
- Assert.assertEquals(sh.getQueryString(),
- "SELECT * FROM TABLE WHERE (\"name\" LIKE ? "
- + "OR \"name\" LIKE ?) ORDER BY \"name\" ASC");
- }
-
- @Test
- public void generateDeleteQuery_basicQuery_shouldSucceed()
- throws SQLException {
- /*
- * No need to run this for Oracle/MSSQL generators since the
- * DefaultSQLGenerator method would be called anyway.
- */
- if (AllTests.sqlGen instanceof MSSQLGenerator
- || AllTests.sqlGen instanceof OracleGenerator) {
- return;
- }
- SQLGenerator sg = AllTests.sqlGen;
- TableQuery query = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(query);
-
- StatementHelper sh = sg.generateDeleteQuery(
- "people",
- query.getPrimaryKeyColumns(),
- null,
- (RowItem) container.getItem(container.getItemIds().iterator()
- .next()));
- Assert.assertEquals("DELETE FROM people WHERE \"ID\" = ?",
- sh.getQueryString());
- }
-
- @Test
- public void generateUpdateQuery_basicQuery_shouldSucceed()
- throws SQLException {
- /*
- * No need to run this for Oracle/MSSQL generators since the
- * DefaultSQLGenerator method would be called anyway.
- */
- if (AllTests.sqlGen instanceof MSSQLGenerator
- || AllTests.sqlGen instanceof OracleGenerator) {
- return;
- }
- SQLGenerator sg = new DefaultSQLGenerator();
- TableQuery query = new TableQuery("people", connectionPool);
- SQLContainer container = new SQLContainer(query);
-
- RowItem ri = (RowItem) container.getItem(container.getItemIds()
- .iterator().next());
- ri.getItemProperty("NAME").setValue("Viljami");
-
- StatementHelper sh = sg.generateUpdateQuery("people", ri);
- Assert.assertTrue("UPDATE people SET \"NAME\" = ?, \"AGE\" = ? WHERE \"ID\" = ?"
- .equals(sh.getQueryString())
- || "UPDATE people SET \"AGE\" = ?, \"NAME\" = ? WHERE \"ID\" = ?"
- .equals(sh.getQueryString()));
- }
-
- @Test
- public void generateInsertQuery_basicQuery_shouldSucceed()
- throws SQLException {
- /*
- * No need to run this for Oracle/MSSQL generators since the
- * DefaultSQLGenerator method would be called anyway.
- */
- if (AllTests.sqlGen instanceof MSSQLGenerator
- || AllTests.sqlGen instanceof OracleGenerator) {
- return;
- }
- SQLGenerator sg = new DefaultSQLGenerator();
- TableQuery query = new TableQuery("people", connectionPool);
- SQLContainer container = new SQLContainer(query);
-
- RowItem ri = (RowItem) container.getItem(container.addItem());
- ri.getItemProperty("NAME").setValue("Viljami");
-
- StatementHelper sh = sg.generateInsertQuery("people", ri);
-
- Assert.assertTrue("INSERT INTO people (\"NAME\", \"AGE\") VALUES (?, ?)"
- .equals(sh.getQueryString())
- || "INSERT INTO people (\"AGE\", \"NAME\") VALUES (?, ?)"
- .equals(sh.getQueryString()));
- }
-
- @Test
- public void generateComplexSelectQuery_forOracle_shouldSucceed()
- throws SQLException {
- SQLGenerator sg = new OracleGenerator();
- List<Filter> f = new ArrayList<Filter>();
- f.add(new Like("name", "%lle"));
- List<OrderBy> ob = Arrays.asList(new OrderBy("name", true));
- StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8,
- "NAME, ID");
- Assert.assertEquals(
- "SELECT * FROM (SELECT x.*, ROWNUM AS \"rownum\" FROM"
- + " (SELECT NAME, ID FROM TABLE WHERE \"name\" LIKE ?"
- + " ORDER BY \"name\" ASC) x) WHERE \"rownum\" BETWEEN 5 AND 12",
- sh.getQueryString());
- }
-
- @Test
- public void generateComplexSelectQuery_forMSSQL_shouldSucceed()
- throws SQLException {
- SQLGenerator sg = new MSSQLGenerator();
- List<Filter> f = new ArrayList<Filter>();
- f.add(new Like("name", "%lle"));
- List<OrderBy> ob = Arrays.asList(new OrderBy("name", true));
- StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8,
- "NAME, ID");
- Assert.assertEquals(sh.getQueryString(),
- "SELECT * FROM (SELECT row_number() OVER "
- + "( ORDER BY \"name\" ASC) AS rownum, NAME, ID "
- + "FROM TABLE WHERE \"name\" LIKE ?) "
- + "AS a WHERE a.rownum BETWEEN 5 AND 12");
- }
-
- @Test
- public void generateComplexSelectQuery_forOracle_exclusiveFilteringMode_shouldSucceed()
- throws SQLException {
- SQLGenerator sg = new OracleGenerator();
- List<Filter> f = new ArrayList<Filter>();
- f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%")));
- List<OrderBy> ob = Arrays.asList(new OrderBy("name", true));
- StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8,
- "NAME, ID");
- Assert.assertEquals(
- sh.getQueryString(),
- "SELECT * FROM (SELECT x.*, ROWNUM AS \"rownum\" FROM"
- + " (SELECT NAME, ID FROM TABLE WHERE (\"name\" LIKE ?"
- + " OR \"name\" LIKE ?) "
- + "ORDER BY \"name\" ASC) x) WHERE \"rownum\" BETWEEN 5 AND 12");
- }
-
- @Test
- public void generateComplexSelectQuery_forMSSQL_exclusiveFilteringMode_shouldSucceed()
- throws SQLException {
- SQLGenerator sg = new MSSQLGenerator();
- List<Filter> f = new ArrayList<Filter>();
- f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%")));
- List<OrderBy> ob = Arrays.asList(new OrderBy("name", true));
- StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8,
- "NAME, ID");
- Assert.assertEquals(sh.getQueryString(),
- "SELECT * FROM (SELECT row_number() OVER "
- + "( ORDER BY \"name\" ASC) AS rownum, NAME, ID "
- + "FROM TABLE WHERE (\"name\" LIKE ? "
- + "OR \"name\" LIKE ?)) "
- + "AS a WHERE a.rownum BETWEEN 5 AND 12");
- }
-}
+package com.vaadin.data.util.sqlcontainer.generator; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.Container.Filter; +import com.vaadin.data.util.filter.Like; +import com.vaadin.data.util.filter.Or; +import com.vaadin.data.util.sqlcontainer.AllTests; +import com.vaadin.data.util.sqlcontainer.DataGenerator; +import com.vaadin.data.util.sqlcontainer.RowItem; +import com.vaadin.data.util.sqlcontainer.SQLContainer; +import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool; +import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool; +import com.vaadin.data.util.sqlcontainer.query.OrderBy; +import com.vaadin.data.util.sqlcontainer.query.TableQuery; +import com.vaadin.data.util.sqlcontainer.query.generator.DefaultSQLGenerator; +import com.vaadin.data.util.sqlcontainer.query.generator.MSSQLGenerator; +import com.vaadin.data.util.sqlcontainer.query.generator.OracleGenerator; +import com.vaadin.data.util.sqlcontainer.query.generator.SQLGenerator; +import com.vaadin.data.util.sqlcontainer.query.generator.StatementHelper; + +public class SQLGeneratorsTest { + private JDBCConnectionPool connectionPool; + + @Before + public void setUp() throws SQLException { + + try { + connectionPool = new SimpleJDBCConnectionPool(AllTests.dbDriver, + AllTests.dbURL, AllTests.dbUser, AllTests.dbPwd, 2, 2); + } catch (SQLException e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + + DataGenerator.addPeopleToDatabase(connectionPool); + } + + @After + public void tearDown() { + if (connectionPool != null) { + connectionPool.destroy(); + } + } + + @Test + public void generateSelectQuery_basicQuery_shouldSucceed() { + SQLGenerator sg = new DefaultSQLGenerator(); + StatementHelper sh = sg.generateSelectQuery("TABLE", null, null, 0, 0, + null); + Assert.assertEquals(sh.getQueryString(), "SELECT * FROM TABLE"); + } + + @Test + public void generateSelectQuery_pagingAndColumnsSet_shouldSucceed() { + SQLGenerator sg = new DefaultSQLGenerator(); + StatementHelper sh = sg.generateSelectQuery("TABLE", null, null, 4, 8, + "COL1, COL2, COL3"); + Assert.assertEquals(sh.getQueryString(), + "SELECT COL1, COL2, COL3 FROM TABLE LIMIT 8 OFFSET 4"); + } + + /** + * Note: Only tests one kind of filter and ordering. + */ + @Test + public void generateSelectQuery_filtersAndOrderingSet_shouldSucceed() { + SQLGenerator sg = new DefaultSQLGenerator(); + List<com.vaadin.data.Container.Filter> f = new ArrayList<Filter>(); + f.add(new Like("name", "%lle")); + List<OrderBy> ob = Arrays.asList(new OrderBy("name", true)); + StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 0, 0, null); + Assert.assertEquals(sh.getQueryString(), + "SELECT * FROM TABLE WHERE \"name\" LIKE ? ORDER BY \"name\" ASC"); + } + + @Test + public void generateSelectQuery_filtersAndOrderingSet_exclusiveFilteringMode_shouldSucceed() { + SQLGenerator sg = new DefaultSQLGenerator(); + List<Filter> f = new ArrayList<Filter>(); + f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); + List<OrderBy> ob = Arrays.asList(new OrderBy("name", true)); + StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 0, 0, null); + // TODO + Assert.assertEquals(sh.getQueryString(), + "SELECT * FROM TABLE WHERE (\"name\" LIKE ? " + + "OR \"name\" LIKE ?) ORDER BY \"name\" ASC"); + } + + @Test + public void generateDeleteQuery_basicQuery_shouldSucceed() + throws SQLException { + /* + * No need to run this for Oracle/MSSQL generators since the + * DefaultSQLGenerator method would be called anyway. + */ + if (AllTests.sqlGen instanceof MSSQLGenerator + || AllTests.sqlGen instanceof OracleGenerator) { + return; + } + SQLGenerator sg = AllTests.sqlGen; + TableQuery query = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(query); + + StatementHelper sh = sg.generateDeleteQuery( + "people", + query.getPrimaryKeyColumns(), + null, + (RowItem) container.getItem(container.getItemIds().iterator() + .next())); + Assert.assertEquals("DELETE FROM people WHERE \"ID\" = ?", + sh.getQueryString()); + } + + @Test + public void generateUpdateQuery_basicQuery_shouldSucceed() + throws SQLException { + /* + * No need to run this for Oracle/MSSQL generators since the + * DefaultSQLGenerator method would be called anyway. + */ + if (AllTests.sqlGen instanceof MSSQLGenerator + || AllTests.sqlGen instanceof OracleGenerator) { + return; + } + SQLGenerator sg = new DefaultSQLGenerator(); + TableQuery query = new TableQuery("people", connectionPool); + SQLContainer container = new SQLContainer(query); + + RowItem ri = (RowItem) container.getItem(container.getItemIds() + .iterator().next()); + ri.getItemProperty("NAME").setValue("Viljami"); + + StatementHelper sh = sg.generateUpdateQuery("people", ri); + Assert.assertTrue("UPDATE people SET \"NAME\" = ?, \"AGE\" = ? WHERE \"ID\" = ?" + .equals(sh.getQueryString()) + || "UPDATE people SET \"AGE\" = ?, \"NAME\" = ? WHERE \"ID\" = ?" + .equals(sh.getQueryString())); + } + + @Test + public void generateInsertQuery_basicQuery_shouldSucceed() + throws SQLException { + /* + * No need to run this for Oracle/MSSQL generators since the + * DefaultSQLGenerator method would be called anyway. + */ + if (AllTests.sqlGen instanceof MSSQLGenerator + || AllTests.sqlGen instanceof OracleGenerator) { + return; + } + SQLGenerator sg = new DefaultSQLGenerator(); + TableQuery query = new TableQuery("people", connectionPool); + SQLContainer container = new SQLContainer(query); + + RowItem ri = (RowItem) container.getItem(container.addItem()); + ri.getItemProperty("NAME").setValue("Viljami"); + + StatementHelper sh = sg.generateInsertQuery("people", ri); + + Assert.assertTrue("INSERT INTO people (\"NAME\", \"AGE\") VALUES (?, ?)" + .equals(sh.getQueryString()) + || "INSERT INTO people (\"AGE\", \"NAME\") VALUES (?, ?)" + .equals(sh.getQueryString())); + } + + @Test + public void generateComplexSelectQuery_forOracle_shouldSucceed() + throws SQLException { + SQLGenerator sg = new OracleGenerator(); + List<Filter> f = new ArrayList<Filter>(); + f.add(new Like("name", "%lle")); + List<OrderBy> ob = Arrays.asList(new OrderBy("name", true)); + StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8, + "NAME, ID"); + Assert.assertEquals( + "SELECT * FROM (SELECT x.*, ROWNUM AS \"rownum\" FROM" + + " (SELECT NAME, ID FROM TABLE WHERE \"name\" LIKE ?" + + " ORDER BY \"name\" ASC) x) WHERE \"rownum\" BETWEEN 5 AND 12", + sh.getQueryString()); + } + + @Test + public void generateComplexSelectQuery_forMSSQL_shouldSucceed() + throws SQLException { + SQLGenerator sg = new MSSQLGenerator(); + List<Filter> f = new ArrayList<Filter>(); + f.add(new Like("name", "%lle")); + List<OrderBy> ob = Arrays.asList(new OrderBy("name", true)); + StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8, + "NAME, ID"); + Assert.assertEquals(sh.getQueryString(), + "SELECT * FROM (SELECT row_number() OVER " + + "( ORDER BY \"name\" ASC) AS rownum, NAME, ID " + + "FROM TABLE WHERE \"name\" LIKE ?) " + + "AS a WHERE a.rownum BETWEEN 5 AND 12"); + } + + @Test + public void generateComplexSelectQuery_forOracle_exclusiveFilteringMode_shouldSucceed() + throws SQLException { + SQLGenerator sg = new OracleGenerator(); + List<Filter> f = new ArrayList<Filter>(); + f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); + List<OrderBy> ob = Arrays.asList(new OrderBy("name", true)); + StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8, + "NAME, ID"); + Assert.assertEquals( + sh.getQueryString(), + "SELECT * FROM (SELECT x.*, ROWNUM AS \"rownum\" FROM" + + " (SELECT NAME, ID FROM TABLE WHERE (\"name\" LIKE ?" + + " OR \"name\" LIKE ?) " + + "ORDER BY \"name\" ASC) x) WHERE \"rownum\" BETWEEN 5 AND 12"); + } + + @Test + public void generateComplexSelectQuery_forMSSQL_exclusiveFilteringMode_shouldSucceed() + throws SQLException { + SQLGenerator sg = new MSSQLGenerator(); + List<Filter> f = new ArrayList<Filter>(); + f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); + List<OrderBy> ob = Arrays.asList(new OrderBy("name", true)); + StatementHelper sh = sg.generateSelectQuery("TABLE", f, ob, 4, 8, + "NAME, ID"); + Assert.assertEquals(sh.getQueryString(), + "SELECT * FROM (SELECT row_number() OVER " + + "( ORDER BY \"name\" ASC) AS rownum, NAME, ID " + + "FROM TABLE WHERE (\"name\" LIKE ? " + + "OR \"name\" LIKE ?)) " + + "AS a WHERE a.rownum BETWEEN 5 AND 12"); + } +} diff --git a/tests/server-side/com/vaadin/data/util/sqlcontainer/query/TableQueryTest.java b/tests/server-side/com/vaadin/data/util/sqlcontainer/query/TableQueryTest.java index 52f7e273c6..657f06ae5e 100644 --- a/tests/server-side/com/vaadin/data/util/sqlcontainer/query/TableQueryTest.java +++ b/tests/server-side/com/vaadin/data/util/sqlcontainer/query/TableQueryTest.java @@ -1,663 +1,663 @@ -package com.vaadin.data.util.sqlcontainer.query;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.vaadin.data.Container.Filter;
-import com.vaadin.data.util.filter.Compare.Equal;
-import com.vaadin.data.util.filter.Like;
-import com.vaadin.data.util.sqlcontainer.AllTests;
-import com.vaadin.data.util.sqlcontainer.DataGenerator;
-import com.vaadin.data.util.sqlcontainer.OptimisticLockException;
-import com.vaadin.data.util.sqlcontainer.RowItem;
-import com.vaadin.data.util.sqlcontainer.SQLContainer;
-import com.vaadin.data.util.sqlcontainer.AllTests.DB;
-import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;
-import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool;
-import com.vaadin.data.util.sqlcontainer.query.OrderBy;
-import com.vaadin.data.util.sqlcontainer.query.TableQuery;
-import com.vaadin.data.util.sqlcontainer.query.generator.DefaultSQLGenerator;
-
-public class TableQueryTest {
- private static final int offset = AllTests.offset;
- private JDBCConnectionPool connectionPool;
-
- @Before
- public void setUp() throws SQLException {
-
- try {
- connectionPool = new SimpleJDBCConnectionPool(AllTests.dbDriver,
- AllTests.dbURL, AllTests.dbUser, AllTests.dbPwd, 2, 2);
- } catch (SQLException e) {
- e.printStackTrace();
- Assert.fail(e.getMessage());
- }
-
- DataGenerator.addPeopleToDatabase(connectionPool);
- }
-
- @After
- public void tearDown() {
- if (connectionPool != null) {
- connectionPool.destroy();
- }
- }
-
- /**********************************************************************
- * TableQuery construction tests
- **********************************************************************/
- @Test
- public void construction_legalParameters_shouldSucceed() {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- new DefaultSQLGenerator());
- Assert.assertArrayEquals(new Object[] { "ID" }, tQuery
- .getPrimaryKeyColumns().toArray());
- boolean correctTableName = "people".equalsIgnoreCase(tQuery
- .getTableName());
- Assert.assertTrue(correctTableName);
- }
-
- @Test
- public void construction_legalParameters_defaultGenerator_shouldSucceed() {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- Assert.assertArrayEquals(new Object[] { "ID" }, tQuery
- .getPrimaryKeyColumns().toArray());
- boolean correctTableName = "people".equalsIgnoreCase(tQuery
- .getTableName());
- Assert.assertTrue(correctTableName);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void construction_nonExistingTableName_shouldFail() {
- new TableQuery("skgwaguhsd", connectionPool, new DefaultSQLGenerator());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void construction_emptyTableName_shouldFail() {
- new TableQuery("", connectionPool, new DefaultSQLGenerator());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void construction_nullSqlGenerator_shouldFail() {
- new TableQuery("people", connectionPool, null);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void construction_nullConnectionPool_shouldFail() {
- new TableQuery("people", null, new DefaultSQLGenerator());
- }
-
- /**********************************************************************
- * TableQuery row count tests
- **********************************************************************/
- @Test
- public void getCount_simpleQuery_returnsFour() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- Assert.assertEquals(4, tQuery.getCount());
- }
-
- @Test
- public void getCount_simpleQueryTwoMorePeopleAdded_returnsSix()
- throws SQLException {
- // Add some people
- Connection conn = connectionPool.reserveConnection();
- Statement statement = conn.createStatement();
- if (AllTests.db == DB.MSSQL) {
- statement.executeUpdate("insert into people values('Bengt', 30)");
- statement.executeUpdate("insert into people values('Ingvar', 50)");
- } else {
- statement
- .executeUpdate("insert into people values(default, 'Bengt', 30)");
- statement
- .executeUpdate("insert into people values(default, 'Ingvar', 50)");
- }
- statement.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
-
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- Assert.assertEquals(6, tQuery.getCount());
- }
-
- @Test
- public void getCount_normalState_releasesConnection() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.getCount();
- tQuery.getCount();
- Assert.assertNotNull(connectionPool.reserveConnection());
- }
-
- /**********************************************************************
- * TableQuery get results tests
- **********************************************************************/
- @Test
- public void getResults_simpleQuery_returnsFourRecords() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.beginTransaction();
- ResultSet rs = tQuery.getResults(0, 0);
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(0 + offset, rs.getInt(1));
- Assert.assertEquals("Ville", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(1 + offset, rs.getInt(1));
- Assert.assertEquals("Kalle", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(2 + offset, rs.getInt(1));
- Assert.assertEquals("Pelle", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(3 + offset, rs.getInt(1));
- Assert.assertEquals("Börje", rs.getString(2));
-
- Assert.assertFalse(rs.next());
- tQuery.commit();
- }
-
- @Test
- public void getResults_noDelegate5000Rows_returns5000rows()
- throws SQLException {
- DataGenerator.addFiveThousandPeople(connectionPool);
-
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- tQuery.beginTransaction();
- ResultSet rs = tQuery.getResults(0, 0);
- for (int i = 0; i < 5000; i++) {
- Assert.assertTrue(rs.next());
- }
- Assert.assertFalse(rs.next());
- tQuery.commit();
- }
-
- /**********************************************************************
- * TableQuery transaction management tests
- **********************************************************************/
- @Test
- public void beginTransaction_readOnly_shouldSucceed() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.beginTransaction();
- }
-
- @Test(expected = IllegalStateException.class)
- public void beginTransaction_transactionAlreadyActive_shouldFail()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- tQuery.beginTransaction();
- tQuery.beginTransaction();
- }
-
- @Test
- public void commit_readOnly_shouldSucceed() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.beginTransaction();
- tQuery.commit();
- }
-
- @Test
- public void rollback_readOnly_shouldSucceed() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.beginTransaction();
- tQuery.rollback();
- }
-
- @Test(expected = SQLException.class)
- public void commit_noActiveTransaction_shouldFail() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.commit();
- }
-
- @Test(expected = SQLException.class)
- public void rollback_noActiveTransaction_shouldFail() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.rollback();
- }
-
- /**********************************************************************
- * TableQuery row query with given keys tests
- **********************************************************************/
- @Test
- public void containsRowWithKeys_existingKeys_returnsTrue()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- Assert.assertTrue(tQuery.containsRowWithKey(1));
- }
-
- @Test
- public void containsRowWithKeys_nonexistingKeys_returnsTrue()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- Assert.assertFalse(tQuery.containsRowWithKey(1337));
- }
-
- @Test
- public void containsRowWithKeys_invalidKeys_shouldFail()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- boolean b = true;
- try {
- b = tQuery.containsRowWithKey("foo");
- } catch (SQLException se) {
- return;
- }
- Assert.assertFalse(b);
- }
-
- @Test
- public void containsRowWithKeys_nullKeys_shouldFailAndReleaseConnections()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- try {
- tQuery.containsRowWithKey(new Object[] { null });
- } catch (SQLException e) {
- // We should now be able to reserve two connections
- connectionPool.reserveConnection();
- connectionPool.reserveConnection();
- }
- }
-
- /**********************************************************************
- * TableQuery filtering and ordering tests
- **********************************************************************/
- @Test
- public void setFilters_shouldReturnCorrectCount() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- List<Filter> filters = new ArrayList<Filter>();
- filters.add(new Like("NAME", "%lle"));
- tQuery.setFilters(filters);
- Assert.assertEquals(3, tQuery.getCount());
- }
-
- @Test
- public void setOrderByNameAscending_shouldReturnCorrectOrder()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- List<OrderBy> orderBys = Arrays.asList(new OrderBy("NAME", true));
- tQuery.setOrderBy(orderBys);
-
- tQuery.beginTransaction();
- ResultSet rs;
- rs = tQuery.getResults(0, 0);
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(3 + offset, rs.getInt(1));
- Assert.assertEquals("Börje", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(1 + offset, rs.getInt(1));
- Assert.assertEquals("Kalle", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(2 + offset, rs.getInt(1));
- Assert.assertEquals("Pelle", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(0 + offset, rs.getInt(1));
- Assert.assertEquals("Ville", rs.getString(2));
-
- Assert.assertFalse(rs.next());
- tQuery.commit();
- }
-
- @Test
- public void setOrderByNameDescending_shouldReturnCorrectOrder()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- List<OrderBy> orderBys = Arrays.asList(new OrderBy("NAME", false));
- tQuery.setOrderBy(orderBys);
-
- tQuery.beginTransaction();
- ResultSet rs;
- rs = tQuery.getResults(0, 0);
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(0 + offset, rs.getInt(1));
- Assert.assertEquals("Ville", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(2 + offset, rs.getInt(1));
- Assert.assertEquals("Pelle", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(1 + offset, rs.getInt(1));
- Assert.assertEquals("Kalle", rs.getString(2));
-
- Assert.assertTrue(rs.next());
- Assert.assertEquals(3 + offset, rs.getInt(1));
- Assert.assertEquals("Börje", rs.getString(2));
-
- Assert.assertFalse(rs.next());
- tQuery.commit();
- }
-
- @Test
- public void setFilters_nullParameter_shouldSucceed() {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.setFilters(null);
- }
-
- @Test
- public void setOrderBy_nullParameter_shouldSucceed() {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.setOrderBy(null);
- }
-
- /**********************************************************************
- * TableQuery row removal tests
- **********************************************************************/
- @Test
- public void removeRowThroughContainer_legalRowItem_shouldSucceed()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(tQuery);
- container.setAutoCommit(false);
- Assert.assertTrue(container.removeItem(container.getItemIds()
- .iterator().next()));
-
- Assert.assertEquals(4, tQuery.getCount());
- Assert.assertEquals(3, container.size());
- container.commit();
-
- Assert.assertEquals(3, tQuery.getCount());
- Assert.assertEquals(3, container.size());
- }
-
- @Test
- public void removeRowThroughContainer_nonexistingRowId_shouldFail()
- throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- SQLContainer container = new SQLContainer(tQuery);
- container.setAutoCommit(true);
- Assert.assertFalse(container.removeItem("foo"));
- }
-
- /**********************************************************************
- * TableQuery row adding / modification tests
- **********************************************************************/
- @Test
- public void insertRowThroughContainer_shouldSucceed() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- tQuery.setVersionColumn("ID");
-
- SQLContainer container = new SQLContainer(tQuery);
- container.setAutoCommit(false);
-
- Object item = container.addItem();
- Assert.assertNotNull(item);
-
- Assert.assertEquals(4, tQuery.getCount());
- Assert.assertEquals(5, container.size());
- container.commit();
-
- Assert.assertEquals(5, tQuery.getCount());
- Assert.assertEquals(5, container.size());
- }
-
- @Test
- public void modifyRowThroughContainer_shouldSucceed() throws SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
-
- // In this test the primary key is used as a version column
- tQuery.setVersionColumn("ID");
- SQLContainer container = new SQLContainer(tQuery);
- container.setAutoCommit(false);
-
- /* Check that the container size is correct and there is no 'Viljami' */
- Assert.assertEquals(4, container.size());
- List<Filter> filters = new ArrayList<Filter>();
- filters.add(new Equal("NAME", "Viljami"));
- tQuery.setFilters(filters);
- Assert.assertEquals(0, tQuery.getCount());
- tQuery.setFilters(null);
-
- /* Fetch first item, modify and commit */
- Object item = container.getItem(container.getItemIds().iterator()
- .next());
- Assert.assertNotNull(item);
-
- RowItem ri = (RowItem) item;
- Assert.assertNotNull(ri.getItemProperty("NAME"));
- ri.getItemProperty("NAME").setValue("Viljami");
-
- container.commit();
-
- // Check that the size is still correct and only 1 'Viljami' is found
- Assert.assertEquals(4, tQuery.getCount());
- Assert.assertEquals(4, container.size());
- tQuery.setFilters(filters);
- Assert.assertEquals(1, tQuery.getCount());
- }
-
- @Test
- public void storeRow_noVersionColumn_shouldSucceed()
- throws UnsupportedOperationException, SQLException {
- TableQuery tQuery = new TableQuery("people", connectionPool,
- AllTests.sqlGen);
- SQLContainer container = new SQLContainer(tQuery);
- Object id = container.addItem();
- RowItem row = (RowItem) container.getItem(id);
- row.getItemProperty("NAME").setValue("R2D2");
- row.getItemProperty("AGE").setValue(123);
- tQuery.beginTransaction();
- tQuery.storeRow(row);
- tQuery.commit();
-
- Connection conn = connectionPool.reserveConnection();
- PreparedStatement stmt = conn
- .prepareStatement("SELECT * FROM PEOPLE WHERE \"NAME\" = ?");
- stmt.setString(1, "R2D2");
- ResultSet rs = stmt.executeQuery();
- Assert.assertTrue(rs.next());
- rs.close();
- stmt.close();
- connectionPool.releaseConnection(conn);
- }
-
- @Test
- public void storeRow_versionSetAndEqualToDBValue_shouldSucceed()
- throws SQLException {
- DataGenerator.addVersionedData(connectionPool);
-
- TableQuery tQuery = new TableQuery("versioned", connectionPool,
- AllTests.sqlGen);
- tQuery.setVersionColumn("VERSION");
- SQLContainer container = new SQLContainer(tQuery);
- RowItem row = (RowItem) container.getItem(container.firstItemId());
- Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue());
-
- row.getItemProperty("TEXT").setValue("asdf");
- container.commit();
-
- Connection conn = connectionPool.reserveConnection();
- PreparedStatement stmt = conn
- .prepareStatement("SELECT * FROM VERSIONED WHERE \"TEXT\" = ?");
- stmt.setString(1, "asdf");
- ResultSet rs = stmt.executeQuery();
- Assert.assertTrue(rs.next());
- rs.close();
- stmt.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
- }
-
- @Test(expected = OptimisticLockException.class)
- public void storeRow_versionSetAndLessThanDBValue_shouldThrowException()
- throws SQLException {
- if (AllTests.db == DB.HSQLDB) {
- throw new OptimisticLockException(
- "HSQLDB doesn't support row versioning for optimistic locking - don't run this test.",
- null);
- }
- DataGenerator.addVersionedData(connectionPool);
-
- TableQuery tQuery = new TableQuery("versioned", connectionPool,
- AllTests.sqlGen);
- tQuery.setVersionColumn("VERSION");
- SQLContainer container = new SQLContainer(tQuery);
- RowItem row = (RowItem) container.getItem(container.firstItemId());
- Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue());
-
- row.getItemProperty("TEXT").setValue("asdf");
-
- // Update the version using another connection.
- Connection conn = connectionPool.reserveConnection();
- PreparedStatement stmt = conn
- .prepareStatement("UPDATE VERSIONED SET \"TEXT\" = ? WHERE \"ID\" = ?");
- stmt.setString(1, "foo");
- stmt.setObject(2, row.getItemProperty("ID").getValue());
- stmt.executeUpdate();
- stmt.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
-
- container.commit();
- }
-
- @Test
- public void removeRow_versionSetAndEqualToDBValue_shouldSucceed()
- throws SQLException {
- DataGenerator.addVersionedData(connectionPool);
-
- TableQuery tQuery = new TableQuery("versioned", connectionPool,
- AllTests.sqlGen);
- tQuery.setVersionColumn("VERSION");
- SQLContainer container = new SQLContainer(tQuery);
- RowItem row = (RowItem) container.getItem(container.firstItemId());
- Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue());
-
- container.removeItem(container.firstItemId());
- container.commit();
-
- Connection conn = connectionPool.reserveConnection();
- PreparedStatement stmt = conn
- .prepareStatement("SELECT * FROM VERSIONED WHERE \"TEXT\" = ?");
- stmt.setString(1, "Junk");
- ResultSet rs = stmt.executeQuery();
- Assert.assertFalse(rs.next());
- rs.close();
- stmt.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
- }
-
- @Test(expected = OptimisticLockException.class)
- public void removeRow_versionSetAndLessThanDBValue_shouldThrowException()
- throws SQLException {
- if (AllTests.db == AllTests.DB.HSQLDB) {
- // HSQLDB doesn't support versioning, so this is to make the test
- // green.
- throw new OptimisticLockException(null);
- }
- DataGenerator.addVersionedData(connectionPool);
-
- TableQuery tQuery = new TableQuery("versioned", connectionPool,
- AllTests.sqlGen);
- tQuery.setVersionColumn("VERSION");
- SQLContainer container = new SQLContainer(tQuery);
- RowItem row = (RowItem) container.getItem(container.firstItemId());
- Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue());
-
- // Update the version using another connection.
- Connection conn = connectionPool.reserveConnection();
- PreparedStatement stmt = conn
- .prepareStatement("UPDATE VERSIONED SET \"TEXT\" = ? WHERE \"ID\" = ?");
- stmt.setString(1, "asdf");
- stmt.setObject(2, row.getItemProperty("ID").getValue());
- stmt.executeUpdate();
- stmt.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
-
- container.removeItem(container.firstItemId());
- container.commit();
- }
-
- @Test
- public void removeRow_throwsOptimisticLockException_shouldStillWork()
- throws SQLException {
- if (AllTests.db == AllTests.DB.HSQLDB) {
- // HSQLDB doesn't support versioning, so this is to make the test
- // green.
- return;
- }
- DataGenerator.addVersionedData(connectionPool);
-
- TableQuery tQuery = new TableQuery("versioned", connectionPool,
- AllTests.sqlGen);
- tQuery.setVersionColumn("VERSION");
- SQLContainer container = new SQLContainer(tQuery);
- RowItem row = (RowItem) container.getItem(container.firstItemId());
- Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue());
-
- // Update the version using another connection.
- Connection conn = connectionPool.reserveConnection();
- PreparedStatement stmt = conn
- .prepareStatement("UPDATE VERSIONED SET \"TEXT\" = ? WHERE \"ID\" = ?");
- stmt.setString(1, "asdf");
- stmt.setObject(2, row.getItemProperty("ID").getValue());
- stmt.executeUpdate();
- stmt.close();
- conn.commit();
- connectionPool.releaseConnection(conn);
-
- Object itemToRemove = container.firstItemId();
- try {
- container.removeItem(itemToRemove);
- container.commit();
- } catch (OptimisticLockException e) {
- // This is expected, refresh and try again.
- container.rollback();
- container.removeItem(itemToRemove);
- container.commit();
- }
- Object id = container.addItem();
- RowItem item = (RowItem) container.getItem(id);
- item.getItemProperty("TEXT").setValue("foo");
- container.commit();
- }
-
+package com.vaadin.data.util.sqlcontainer.query; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.Container.Filter; +import com.vaadin.data.util.filter.Compare.Equal; +import com.vaadin.data.util.filter.Like; +import com.vaadin.data.util.sqlcontainer.AllTests; +import com.vaadin.data.util.sqlcontainer.DataGenerator; +import com.vaadin.data.util.sqlcontainer.OptimisticLockException; +import com.vaadin.data.util.sqlcontainer.RowItem; +import com.vaadin.data.util.sqlcontainer.SQLContainer; +import com.vaadin.data.util.sqlcontainer.AllTests.DB; +import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool; +import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool; +import com.vaadin.data.util.sqlcontainer.query.OrderBy; +import com.vaadin.data.util.sqlcontainer.query.TableQuery; +import com.vaadin.data.util.sqlcontainer.query.generator.DefaultSQLGenerator; + +public class TableQueryTest { + private static final int offset = AllTests.offset; + private JDBCConnectionPool connectionPool; + + @Before + public void setUp() throws SQLException { + + try { + connectionPool = new SimpleJDBCConnectionPool(AllTests.dbDriver, + AllTests.dbURL, AllTests.dbUser, AllTests.dbPwd, 2, 2); + } catch (SQLException e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + + DataGenerator.addPeopleToDatabase(connectionPool); + } + + @After + public void tearDown() { + if (connectionPool != null) { + connectionPool.destroy(); + } + } + + /********************************************************************** + * TableQuery construction tests + **********************************************************************/ + @Test + public void construction_legalParameters_shouldSucceed() { + TableQuery tQuery = new TableQuery("people", connectionPool, + new DefaultSQLGenerator()); + Assert.assertArrayEquals(new Object[] { "ID" }, tQuery + .getPrimaryKeyColumns().toArray()); + boolean correctTableName = "people".equalsIgnoreCase(tQuery + .getTableName()); + Assert.assertTrue(correctTableName); + } + + @Test + public void construction_legalParameters_defaultGenerator_shouldSucceed() { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + Assert.assertArrayEquals(new Object[] { "ID" }, tQuery + .getPrimaryKeyColumns().toArray()); + boolean correctTableName = "people".equalsIgnoreCase(tQuery + .getTableName()); + Assert.assertTrue(correctTableName); + } + + @Test(expected = IllegalArgumentException.class) + public void construction_nonExistingTableName_shouldFail() { + new TableQuery("skgwaguhsd", connectionPool, new DefaultSQLGenerator()); + } + + @Test(expected = IllegalArgumentException.class) + public void construction_emptyTableName_shouldFail() { + new TableQuery("", connectionPool, new DefaultSQLGenerator()); + } + + @Test(expected = IllegalArgumentException.class) + public void construction_nullSqlGenerator_shouldFail() { + new TableQuery("people", connectionPool, null); + } + + @Test(expected = IllegalArgumentException.class) + public void construction_nullConnectionPool_shouldFail() { + new TableQuery("people", null, new DefaultSQLGenerator()); + } + + /********************************************************************** + * TableQuery row count tests + **********************************************************************/ + @Test + public void getCount_simpleQuery_returnsFour() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + Assert.assertEquals(4, tQuery.getCount()); + } + + @Test + public void getCount_simpleQueryTwoMorePeopleAdded_returnsSix() + throws SQLException { + // Add some people + Connection conn = connectionPool.reserveConnection(); + Statement statement = conn.createStatement(); + if (AllTests.db == DB.MSSQL) { + statement.executeUpdate("insert into people values('Bengt', 30)"); + statement.executeUpdate("insert into people values('Ingvar', 50)"); + } else { + statement + .executeUpdate("insert into people values(default, 'Bengt', 30)"); + statement + .executeUpdate("insert into people values(default, 'Ingvar', 50)"); + } + statement.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + Assert.assertEquals(6, tQuery.getCount()); + } + + @Test + public void getCount_normalState_releasesConnection() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.getCount(); + tQuery.getCount(); + Assert.assertNotNull(connectionPool.reserveConnection()); + } + + /********************************************************************** + * TableQuery get results tests + **********************************************************************/ + @Test + public void getResults_simpleQuery_returnsFourRecords() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.beginTransaction(); + ResultSet rs = tQuery.getResults(0, 0); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(0 + offset, rs.getInt(1)); + Assert.assertEquals("Ville", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(1 + offset, rs.getInt(1)); + Assert.assertEquals("Kalle", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(2 + offset, rs.getInt(1)); + Assert.assertEquals("Pelle", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(3 + offset, rs.getInt(1)); + Assert.assertEquals("Börje", rs.getString(2)); + + Assert.assertFalse(rs.next()); + tQuery.commit(); + } + + @Test + public void getResults_noDelegate5000Rows_returns5000rows() + throws SQLException { + DataGenerator.addFiveThousandPeople(connectionPool); + + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + tQuery.beginTransaction(); + ResultSet rs = tQuery.getResults(0, 0); + for (int i = 0; i < 5000; i++) { + Assert.assertTrue(rs.next()); + } + Assert.assertFalse(rs.next()); + tQuery.commit(); + } + + /********************************************************************** + * TableQuery transaction management tests + **********************************************************************/ + @Test + public void beginTransaction_readOnly_shouldSucceed() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.beginTransaction(); + } + + @Test(expected = IllegalStateException.class) + public void beginTransaction_transactionAlreadyActive_shouldFail() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + tQuery.beginTransaction(); + tQuery.beginTransaction(); + } + + @Test + public void commit_readOnly_shouldSucceed() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.beginTransaction(); + tQuery.commit(); + } + + @Test + public void rollback_readOnly_shouldSucceed() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.beginTransaction(); + tQuery.rollback(); + } + + @Test(expected = SQLException.class) + public void commit_noActiveTransaction_shouldFail() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.commit(); + } + + @Test(expected = SQLException.class) + public void rollback_noActiveTransaction_shouldFail() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.rollback(); + } + + /********************************************************************** + * TableQuery row query with given keys tests + **********************************************************************/ + @Test + public void containsRowWithKeys_existingKeys_returnsTrue() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + Assert.assertTrue(tQuery.containsRowWithKey(1)); + } + + @Test + public void containsRowWithKeys_nonexistingKeys_returnsTrue() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + Assert.assertFalse(tQuery.containsRowWithKey(1337)); + } + + @Test + public void containsRowWithKeys_invalidKeys_shouldFail() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + boolean b = true; + try { + b = tQuery.containsRowWithKey("foo"); + } catch (SQLException se) { + return; + } + Assert.assertFalse(b); + } + + @Test + public void containsRowWithKeys_nullKeys_shouldFailAndReleaseConnections() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + try { + tQuery.containsRowWithKey(new Object[] { null }); + } catch (SQLException e) { + // We should now be able to reserve two connections + connectionPool.reserveConnection(); + connectionPool.reserveConnection(); + } + } + + /********************************************************************** + * TableQuery filtering and ordering tests + **********************************************************************/ + @Test + public void setFilters_shouldReturnCorrectCount() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + List<Filter> filters = new ArrayList<Filter>(); + filters.add(new Like("NAME", "%lle")); + tQuery.setFilters(filters); + Assert.assertEquals(3, tQuery.getCount()); + } + + @Test + public void setOrderByNameAscending_shouldReturnCorrectOrder() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + List<OrderBy> orderBys = Arrays.asList(new OrderBy("NAME", true)); + tQuery.setOrderBy(orderBys); + + tQuery.beginTransaction(); + ResultSet rs; + rs = tQuery.getResults(0, 0); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(3 + offset, rs.getInt(1)); + Assert.assertEquals("Börje", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(1 + offset, rs.getInt(1)); + Assert.assertEquals("Kalle", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(2 + offset, rs.getInt(1)); + Assert.assertEquals("Pelle", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(0 + offset, rs.getInt(1)); + Assert.assertEquals("Ville", rs.getString(2)); + + Assert.assertFalse(rs.next()); + tQuery.commit(); + } + + @Test + public void setOrderByNameDescending_shouldReturnCorrectOrder() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + List<OrderBy> orderBys = Arrays.asList(new OrderBy("NAME", false)); + tQuery.setOrderBy(orderBys); + + tQuery.beginTransaction(); + ResultSet rs; + rs = tQuery.getResults(0, 0); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(0 + offset, rs.getInt(1)); + Assert.assertEquals("Ville", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(2 + offset, rs.getInt(1)); + Assert.assertEquals("Pelle", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(1 + offset, rs.getInt(1)); + Assert.assertEquals("Kalle", rs.getString(2)); + + Assert.assertTrue(rs.next()); + Assert.assertEquals(3 + offset, rs.getInt(1)); + Assert.assertEquals("Börje", rs.getString(2)); + + Assert.assertFalse(rs.next()); + tQuery.commit(); + } + + @Test + public void setFilters_nullParameter_shouldSucceed() { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.setFilters(null); + } + + @Test + public void setOrderBy_nullParameter_shouldSucceed() { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.setOrderBy(null); + } + + /********************************************************************** + * TableQuery row removal tests + **********************************************************************/ + @Test + public void removeRowThroughContainer_legalRowItem_shouldSucceed() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(tQuery); + container.setAutoCommit(false); + Assert.assertTrue(container.removeItem(container.getItemIds() + .iterator().next())); + + Assert.assertEquals(4, tQuery.getCount()); + Assert.assertEquals(3, container.size()); + container.commit(); + + Assert.assertEquals(3, tQuery.getCount()); + Assert.assertEquals(3, container.size()); + } + + @Test + public void removeRowThroughContainer_nonexistingRowId_shouldFail() + throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + SQLContainer container = new SQLContainer(tQuery); + container.setAutoCommit(true); + Assert.assertFalse(container.removeItem("foo")); + } + + /********************************************************************** + * TableQuery row adding / modification tests + **********************************************************************/ + @Test + public void insertRowThroughContainer_shouldSucceed() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + tQuery.setVersionColumn("ID"); + + SQLContainer container = new SQLContainer(tQuery); + container.setAutoCommit(false); + + Object item = container.addItem(); + Assert.assertNotNull(item); + + Assert.assertEquals(4, tQuery.getCount()); + Assert.assertEquals(5, container.size()); + container.commit(); + + Assert.assertEquals(5, tQuery.getCount()); + Assert.assertEquals(5, container.size()); + } + + @Test + public void modifyRowThroughContainer_shouldSucceed() throws SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + + // In this test the primary key is used as a version column + tQuery.setVersionColumn("ID"); + SQLContainer container = new SQLContainer(tQuery); + container.setAutoCommit(false); + + /* Check that the container size is correct and there is no 'Viljami' */ + Assert.assertEquals(4, container.size()); + List<Filter> filters = new ArrayList<Filter>(); + filters.add(new Equal("NAME", "Viljami")); + tQuery.setFilters(filters); + Assert.assertEquals(0, tQuery.getCount()); + tQuery.setFilters(null); + + /* Fetch first item, modify and commit */ + Object item = container.getItem(container.getItemIds().iterator() + .next()); + Assert.assertNotNull(item); + + RowItem ri = (RowItem) item; + Assert.assertNotNull(ri.getItemProperty("NAME")); + ri.getItemProperty("NAME").setValue("Viljami"); + + container.commit(); + + // Check that the size is still correct and only 1 'Viljami' is found + Assert.assertEquals(4, tQuery.getCount()); + Assert.assertEquals(4, container.size()); + tQuery.setFilters(filters); + Assert.assertEquals(1, tQuery.getCount()); + } + + @Test + public void storeRow_noVersionColumn_shouldSucceed() + throws UnsupportedOperationException, SQLException { + TableQuery tQuery = new TableQuery("people", connectionPool, + AllTests.sqlGen); + SQLContainer container = new SQLContainer(tQuery); + Object id = container.addItem(); + RowItem row = (RowItem) container.getItem(id); + row.getItemProperty("NAME").setValue("R2D2"); + row.getItemProperty("AGE").setValue(123); + tQuery.beginTransaction(); + tQuery.storeRow(row); + tQuery.commit(); + + Connection conn = connectionPool.reserveConnection(); + PreparedStatement stmt = conn + .prepareStatement("SELECT * FROM PEOPLE WHERE \"NAME\" = ?"); + stmt.setString(1, "R2D2"); + ResultSet rs = stmt.executeQuery(); + Assert.assertTrue(rs.next()); + rs.close(); + stmt.close(); + connectionPool.releaseConnection(conn); + } + + @Test + public void storeRow_versionSetAndEqualToDBValue_shouldSucceed() + throws SQLException { + DataGenerator.addVersionedData(connectionPool); + + TableQuery tQuery = new TableQuery("versioned", connectionPool, + AllTests.sqlGen); + tQuery.setVersionColumn("VERSION"); + SQLContainer container = new SQLContainer(tQuery); + RowItem row = (RowItem) container.getItem(container.firstItemId()); + Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue()); + + row.getItemProperty("TEXT").setValue("asdf"); + container.commit(); + + Connection conn = connectionPool.reserveConnection(); + PreparedStatement stmt = conn + .prepareStatement("SELECT * FROM VERSIONED WHERE \"TEXT\" = ?"); + stmt.setString(1, "asdf"); + ResultSet rs = stmt.executeQuery(); + Assert.assertTrue(rs.next()); + rs.close(); + stmt.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + } + + @Test(expected = OptimisticLockException.class) + public void storeRow_versionSetAndLessThanDBValue_shouldThrowException() + throws SQLException { + if (AllTests.db == DB.HSQLDB) { + throw new OptimisticLockException( + "HSQLDB doesn't support row versioning for optimistic locking - don't run this test.", + null); + } + DataGenerator.addVersionedData(connectionPool); + + TableQuery tQuery = new TableQuery("versioned", connectionPool, + AllTests.sqlGen); + tQuery.setVersionColumn("VERSION"); + SQLContainer container = new SQLContainer(tQuery); + RowItem row = (RowItem) container.getItem(container.firstItemId()); + Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue()); + + row.getItemProperty("TEXT").setValue("asdf"); + + // Update the version using another connection. + Connection conn = connectionPool.reserveConnection(); + PreparedStatement stmt = conn + .prepareStatement("UPDATE VERSIONED SET \"TEXT\" = ? WHERE \"ID\" = ?"); + stmt.setString(1, "foo"); + stmt.setObject(2, row.getItemProperty("ID").getValue()); + stmt.executeUpdate(); + stmt.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + + container.commit(); + } + + @Test + public void removeRow_versionSetAndEqualToDBValue_shouldSucceed() + throws SQLException { + DataGenerator.addVersionedData(connectionPool); + + TableQuery tQuery = new TableQuery("versioned", connectionPool, + AllTests.sqlGen); + tQuery.setVersionColumn("VERSION"); + SQLContainer container = new SQLContainer(tQuery); + RowItem row = (RowItem) container.getItem(container.firstItemId()); + Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue()); + + container.removeItem(container.firstItemId()); + container.commit(); + + Connection conn = connectionPool.reserveConnection(); + PreparedStatement stmt = conn + .prepareStatement("SELECT * FROM VERSIONED WHERE \"TEXT\" = ?"); + stmt.setString(1, "Junk"); + ResultSet rs = stmt.executeQuery(); + Assert.assertFalse(rs.next()); + rs.close(); + stmt.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + } + + @Test(expected = OptimisticLockException.class) + public void removeRow_versionSetAndLessThanDBValue_shouldThrowException() + throws SQLException { + if (AllTests.db == AllTests.DB.HSQLDB) { + // HSQLDB doesn't support versioning, so this is to make the test + // green. + throw new OptimisticLockException(null); + } + DataGenerator.addVersionedData(connectionPool); + + TableQuery tQuery = new TableQuery("versioned", connectionPool, + AllTests.sqlGen); + tQuery.setVersionColumn("VERSION"); + SQLContainer container = new SQLContainer(tQuery); + RowItem row = (RowItem) container.getItem(container.firstItemId()); + Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue()); + + // Update the version using another connection. + Connection conn = connectionPool.reserveConnection(); + PreparedStatement stmt = conn + .prepareStatement("UPDATE VERSIONED SET \"TEXT\" = ? WHERE \"ID\" = ?"); + stmt.setString(1, "asdf"); + stmt.setObject(2, row.getItemProperty("ID").getValue()); + stmt.executeUpdate(); + stmt.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + + container.removeItem(container.firstItemId()); + container.commit(); + } + + @Test + public void removeRow_throwsOptimisticLockException_shouldStillWork() + throws SQLException { + if (AllTests.db == AllTests.DB.HSQLDB) { + // HSQLDB doesn't support versioning, so this is to make the test + // green. + return; + } + DataGenerator.addVersionedData(connectionPool); + + TableQuery tQuery = new TableQuery("versioned", connectionPool, + AllTests.sqlGen); + tQuery.setVersionColumn("VERSION"); + SQLContainer container = new SQLContainer(tQuery); + RowItem row = (RowItem) container.getItem(container.firstItemId()); + Assert.assertEquals("Junk", row.getItemProperty("TEXT").getValue()); + + // Update the version using another connection. + Connection conn = connectionPool.reserveConnection(); + PreparedStatement stmt = conn + .prepareStatement("UPDATE VERSIONED SET \"TEXT\" = ? WHERE \"ID\" = ?"); + stmt.setString(1, "asdf"); + stmt.setObject(2, row.getItemProperty("ID").getValue()); + stmt.executeUpdate(); + stmt.close(); + conn.commit(); + connectionPool.releaseConnection(conn); + + Object itemToRemove = container.firstItemId(); + try { + container.removeItem(itemToRemove); + container.commit(); + } catch (OptimisticLockException e) { + // This is expected, refresh and try again. + container.rollback(); + container.removeItem(itemToRemove); + container.commit(); + } + Object id = container.addItem(); + RowItem item = (RowItem) container.getItem(id); + item.getItemProperty("TEXT").setValue("foo"); + container.commit(); + } + }
\ No newline at end of file |