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 | |
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')
58 files changed, 7088 insertions, 7088 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 diff --git a/tests/server-side/com/vaadin/tests/server/IndexedContainerListeners.java b/tests/server-side/com/vaadin/tests/server/IndexedContainerListeners.java index 2dc0caade3..8334c7f183 100644 --- a/tests/server-side/com/vaadin/tests/server/IndexedContainerListeners.java +++ b/tests/server-side/com/vaadin/tests/server/IndexedContainerListeners.java @@ -1,20 +1,20 @@ -package com.vaadin.tests.server;
-
-import com.vaadin.data.Container.PropertySetChangeEvent;
-import com.vaadin.data.Container.PropertySetChangeListener;
-import com.vaadin.data.Property.ValueChangeEvent;
-import com.vaadin.data.Property.ValueChangeListener;
-import com.vaadin.data.util.IndexedContainer;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-
-public class IndexedContainerListeners extends AbstractListenerMethodsTest {
- public void testValueChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(IndexedContainer.class,
- ValueChangeEvent.class, ValueChangeListener.class);
- }
-
- public void testPropertySetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(IndexedContainer.class,
- PropertySetChangeEvent.class, PropertySetChangeListener.class);
- }
-}
+package com.vaadin.tests.server; + +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; + +public class IndexedContainerListeners extends AbstractListenerMethodsTest { + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + ValueChangeEvent.class, ValueChangeListener.class); + } + + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/PropertysetItemListeners.java b/tests/server-side/com/vaadin/tests/server/PropertysetItemListeners.java index 69cbbbfb7c..d493f22779 100644 --- a/tests/server-side/com/vaadin/tests/server/PropertysetItemListeners.java +++ b/tests/server-side/com/vaadin/tests/server/PropertysetItemListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server;
-
-import com.vaadin.data.Item.PropertySetChangeEvent;
-import com.vaadin.data.Item.PropertySetChangeListener;
-import com.vaadin.data.util.PropertysetItem;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-
-public class PropertysetItemListeners extends AbstractListenerMethodsTest {
- public void testPropertySetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(PropertysetItem.class,
- PropertySetChangeEvent.class, PropertySetChangeListener.class);
- }
-}
+package com.vaadin.tests.server; + +import com.vaadin.data.Item.PropertySetChangeEvent; +import com.vaadin.data.Item.PropertySetChangeListener; +import com.vaadin.data.util.PropertysetItem; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; + +public class PropertysetItemListeners extends AbstractListenerMethodsTest { + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(PropertysetItem.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java b/tests/server-side/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java index ae70757b3e..d6598a3b62 100644 --- a/tests/server-side/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java +++ b/tests/server-side/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java @@ -1,15 +1,15 @@ -package com.vaadin.tests.server;
-
-import com.vaadin.data.Container.PropertySetChangeEvent;
-import com.vaadin.data.Container.PropertySetChangeListener;
-import com.vaadin.data.util.BeanItemContainer;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-
-public class TestAbstractBeanContainerListeners extends AbstractListenerMethodsTest {
- public void testPropertySetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(BeanItemContainer.class,
- PropertySetChangeEvent.class, PropertySetChangeListener.class,
- new BeanItemContainer<PropertySetChangeListener>(
- PropertySetChangeListener.class));
- }
-}
+package com.vaadin.tests.server; + +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.data.util.BeanItemContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; + +public class TestAbstractBeanContainerListeners extends AbstractListenerMethodsTest { + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(BeanItemContainer.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class, + new BeanItemContainer<PropertySetChangeListener>( + PropertySetChangeListener.class)); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/TestAbstractContainerListeners.java b/tests/server-side/com/vaadin/tests/server/TestAbstractContainerListeners.java index d10c5d7791..b63e4f809a 100644 --- a/tests/server-side/com/vaadin/tests/server/TestAbstractContainerListeners.java +++ b/tests/server-side/com/vaadin/tests/server/TestAbstractContainerListeners.java @@ -1,21 +1,21 @@ -package com.vaadin.tests.server;
-
-import com.vaadin.data.Container.ItemSetChangeEvent;
-import com.vaadin.data.Container.ItemSetChangeListener;
-import com.vaadin.data.Container.PropertySetChangeEvent;
-import com.vaadin.data.Container.PropertySetChangeListener;
-import com.vaadin.data.util.IndexedContainer;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-
-public class TestAbstractContainerListeners extends AbstractListenerMethodsTest {
-
- public void testItemSetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(IndexedContainer.class,
- ItemSetChangeEvent.class, ItemSetChangeListener.class);
- }
-
- public void testPropertySetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(IndexedContainer.class,
- PropertySetChangeEvent.class, PropertySetChangeListener.class);
- }
-}
+package com.vaadin.tests.server; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; + +public class TestAbstractContainerListeners extends AbstractListenerMethodsTest { + + public void testItemSetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + ItemSetChangeEvent.class, ItemSetChangeListener.class); + } + + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java b/tests/server-side/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java index 754f152936..4be4e35554 100644 --- a/tests/server-side/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java +++ b/tests/server-side/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server;
-
-import com.vaadin.data.Container.ItemSetChangeEvent;
-import com.vaadin.data.Container.ItemSetChangeListener;
-import com.vaadin.data.util.IndexedContainer;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-
-public class TestAbstractInMemoryContainerListeners extends AbstractListenerMethodsTest {
- public void testItemSetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(IndexedContainer.class,
- ItemSetChangeEvent.class, ItemSetChangeListener.class);
- }
-}
+package com.vaadin.tests.server; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; + +public class TestAbstractInMemoryContainerListeners extends AbstractListenerMethodsTest { + public void testItemSetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + ItemSetChangeEvent.class, ItemSetChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/TestAbstractPropertyListeners.java b/tests/server-side/com/vaadin/tests/server/TestAbstractPropertyListeners.java index 58dee08643..a1d01d1930 100644 --- a/tests/server-side/com/vaadin/tests/server/TestAbstractPropertyListeners.java +++ b/tests/server-side/com/vaadin/tests/server/TestAbstractPropertyListeners.java @@ -1,24 +1,24 @@ -package com.vaadin.tests.server;
-
-import com.vaadin.data.Property.ReadOnlyStatusChangeEvent;
-import com.vaadin.data.Property.ReadOnlyStatusChangeListener;
-import com.vaadin.data.Property.ValueChangeEvent;
-import com.vaadin.data.Property.ValueChangeListener;
-import com.vaadin.data.util.AbstractProperty;
-import com.vaadin.data.util.ObjectProperty;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-
-public class TestAbstractPropertyListeners extends AbstractListenerMethodsTest {
- public void testValueChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(AbstractProperty.class,
- ValueChangeEvent.class, ValueChangeListener.class,
- new ObjectProperty<String>(""));
- }
-
- public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(AbstractProperty.class,
- ReadOnlyStatusChangeEvent.class,
- ReadOnlyStatusChangeListener.class, new ObjectProperty<String>(
- ""));
- }
-}
+package com.vaadin.tests.server; + +import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; +import com.vaadin.data.Property.ReadOnlyStatusChangeListener; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.AbstractProperty; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; + +public class TestAbstractPropertyListeners extends AbstractListenerMethodsTest { + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbstractProperty.class, + ValueChangeEvent.class, ValueChangeListener.class, + new ObjectProperty<String>("")); + } + + public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbstractProperty.class, + ReadOnlyStatusChangeEvent.class, + ReadOnlyStatusChangeListener.class, new ObjectProperty<String>( + "")); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/TestClassesSerializable.java b/tests/server-side/com/vaadin/tests/server/TestClassesSerializable.java index 33c1dfaf5f..c047565fcc 100644 --- a/tests/server-side/com/vaadin/tests/server/TestClassesSerializable.java +++ b/tests/server-side/com/vaadin/tests/server/TestClassesSerializable.java @@ -1,262 +1,262 @@ -package com.vaadin.tests.server;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-
-public class TestClassesSerializable extends TestCase {
-
- /**
- * JARs that will be scanned for classes to test, in addition to classpath
- * directories.
- */
- private static String JAR_PATTERN = ".*vaadin.*\\.jar";
-
- private static String[] BASE_PACKAGES = { "com.vaadin" };
-
- private static String[] EXCLUDED_PATTERNS = {
- "com\\.vaadin\\.demo\\..*", //
- "com\\.vaadin\\.external\\.org\\.apache\\.commons\\.fileupload\\..*", //
- "com\\.vaadin\\.launcher\\..*", //
- "com\\.vaadin\\.terminal\\.gwt\\.client\\..*", //
- "com\\.vaadin\\.terminal\\.gwt\\.widgetsetutils\\..*", //
- "com\\.vaadin\\.tests\\..*", // exclude automated tests
- "com\\.vaadin\\.tools\\..*", //
- "com\\.vaadin\\.ui\\.themes\\..*", //
- // exact class level filtering
- "com\\.vaadin\\.event\\.FieldEvents", //
- "com\\.vaadin\\.event\\.LayoutEvents", //
- "com\\.vaadin\\.event\\.MouseEvents", //
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.AbstractApplicationPortlet", //
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.ApplicationPortlet2", //
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.Constants", //
- "com\\.vaadin\\.util\\.SerializerHelper", // fully static
- // class level filtering, also affecting nested classes and
- // interfaces
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.AbstractCommunicationManager.*", //
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.ApplicationRunnerServlet.*", //
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.CommunicationManager.*", //
- "com\\.vaadin\\.terminal\\.gwt\\.server\\.PortletCommunicationManager.*", //
- };
-
- /**
- * Tests that all the relevant classes and interfaces under
- * {@link #BASE_PACKAGES} implement Serializable.
- *
- * @throws Exception
- */
- public void testClassesSerializable() throws Exception {
- List<String> rawClasspathEntries = getRawClasspathEntries();
-
- List<String> classes = new ArrayList<String>();
- for (String location : rawClasspathEntries) {
- classes.addAll(findServerClasses(location));
- }
-
- ArrayList<Class<?>> nonSerializableClasses = new ArrayList<Class<?>>();
- for (String className : classes) {
- Class<?> cls = Class.forName(className);
- // skip annotations and synthetic classes
- if (cls.isAnnotation() || cls.isSynthetic()) {
- continue;
- }
- // Don't add classes that have a @Test annotation on any methods
- boolean testPresent = false;
- for (Method method : cls.getMethods()) {
- if (method.isAnnotationPresent(Test.class)) {
- testPresent = true;
- break;
- }
- }
- if (testPresent) {
- continue;
- }
-
- // report non-serializable classes and interfaces
- if (!Serializable.class.isAssignableFrom(cls)) {
- nonSerializableClasses.add(cls);
- // TODO easier to read when testing
- // System.err.println(cls);
- }
- }
-
- // useful failure message including all non-serializable classes and
- // interfaces
- if (!nonSerializableClasses.isEmpty()) {
- String nonSerializableString = "";
- Iterator<Class<?>> it = nonSerializableClasses.iterator();
- nonSerializableString = it.next().getName();
- while (it.hasNext()) {
- nonSerializableString += ", " + it.next().getName();
- }
- fail("Serializable not implemented by the following classes and interfaces: "
- + nonSerializableString);
- }
- }
-
- /**
- * Lists all class path entries by splitting the class path string.
- *
- * Adapted from ClassPathExplorer.getRawClasspathEntries(), but without
- * filtering.
- *
- * @return List of class path segment strings
- */
- //
- private final static List<String> getRawClasspathEntries() {
- // try to keep the order of the classpath
- List<String> locations = new ArrayList<String>();
-
- String pathSep = System.getProperty("path.separator");
- String classpath = System.getProperty("java.class.path");
-
- if (classpath.startsWith("\"")) {
- classpath = classpath.substring(1);
- }
- if (classpath.endsWith("\"")) {
- classpath = classpath.substring(0, classpath.length() - 1);
- }
-
- String[] split = classpath.split(pathSep);
- for (int i = 0; i < split.length; i++) {
- String classpathEntry = split[i];
- locations.add(classpathEntry);
- }
-
- return locations;
- }
-
- /**
- * Finds the server side classes/interfaces under a class path entry -
- * either a directory or a JAR that matches {@link #JAR_PATTERN}.
- *
- * Only classes under {@link #BASE_PACKAGES} are considered, and those
- * matching {@link #EXCLUDED_PATTERNS} are filtered out.
- *
- * @param classpathEntry
- * @return
- * @throws IOException
- */
- private List<String> findServerClasses(String classpathEntry)
- throws IOException {
- Collection<String> classes = new ArrayList<String>();
-
- File file = new File(classpathEntry);
- if (file.isDirectory()) {
- classes = findClassesInDirectory(null, file);
- } else if (file.getName().matches(JAR_PATTERN)) {
- classes = findClassesInJar(file);
- } else {
- System.out.println("Ignoring " + classpathEntry);
- return Collections.emptyList();
- }
-
- List<String> filteredClasses = new ArrayList<String>();
- for (String className : classes) {
- boolean ok = false;
- for (String basePackage : BASE_PACKAGES) {
- if (className.startsWith(basePackage + ".")) {
- ok = true;
- break;
- }
- }
- for (String excludedPrefix : EXCLUDED_PATTERNS) {
- if (className.matches(excludedPrefix)) {
- ok = false;
- break;
- }
- }
-
- // Don't add test classes
- if (className.contains("Test")) {
- ok = false;
- }
-
- if (ok) {
- filteredClasses.add(className);
- }
- }
-
- return filteredClasses;
- }
-
- /**
- * Lists class names (based on .class files) in a JAR file.
- *
- * @param file
- * a valid JAR file
- * @return collection of fully qualified class names in the JAR
- * @throws IOException
- */
- private Collection<String> findClassesInJar(File file) throws IOException {
- Collection<String> classes = new ArrayList<String>();
-
- JarFile jar = new JarFile(file);
- Enumeration<JarEntry> e = jar.entries();
- while (e.hasMoreElements()) {
- JarEntry entry = e.nextElement();
- if (entry.getName().endsWith(".class")) {
- String nameWithoutExtension = entry.getName().replaceAll(
- "\\.class", "");
- String className = nameWithoutExtension.replace('/', '.');
- classes.add(className);
- }
- }
- return classes;
- }
-
- /**
- * Lists class names (based on .class files) in a directory (a package path
- * root).
- *
- * @param parentPackage
- * parent package name or null at root of hierarchy, used by
- * recursion
- * @param parent
- * File representing the directory to scan
- * @return collection of fully qualified class names in the directory
- */
- private final static Collection<String> findClassesInDirectory(
- String parentPackage, File parent) {
- if (parent.isHidden()
- || parent.getPath().contains(File.separator + ".")) {
- return Collections.emptyList();
- }
-
- if (parentPackage == null) {
- parentPackage = "";
- } else {
- parentPackage += ".";
- }
-
- Collection<String> classNames = new ArrayList<String>();
-
- // add all directories recursively
- File[] files = parent.listFiles();
- for (File child : files) {
- if (child.isDirectory()) {
- classNames.addAll(findClassesInDirectory(
- parentPackage + child.getName(), child));
- } else if (child.getName().endsWith(".class")) {
- classNames.add(parentPackage.replace(File.separatorChar, '.')
- + child.getName().replaceAll("\\.class", ""));
- }
- }
-
- return classNames;
- }
-
-}
+package com.vaadin.tests.server; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import junit.framework.TestCase; + +import org.junit.Test; + +public class TestClassesSerializable extends TestCase { + + /** + * JARs that will be scanned for classes to test, in addition to classpath + * directories. + */ + private static String JAR_PATTERN = ".*vaadin.*\\.jar"; + + private static String[] BASE_PACKAGES = { "com.vaadin" }; + + private static String[] EXCLUDED_PATTERNS = { + "com\\.vaadin\\.demo\\..*", // + "com\\.vaadin\\.external\\.org\\.apache\\.commons\\.fileupload\\..*", // + "com\\.vaadin\\.launcher\\..*", // + "com\\.vaadin\\.terminal\\.gwt\\.client\\..*", // + "com\\.vaadin\\.terminal\\.gwt\\.widgetsetutils\\..*", // + "com\\.vaadin\\.tests\\..*", // exclude automated tests + "com\\.vaadin\\.tools\\..*", // + "com\\.vaadin\\.ui\\.themes\\..*", // + // exact class level filtering + "com\\.vaadin\\.event\\.FieldEvents", // + "com\\.vaadin\\.event\\.LayoutEvents", // + "com\\.vaadin\\.event\\.MouseEvents", // + "com\\.vaadin\\.terminal\\.gwt\\.server\\.AbstractApplicationPortlet", // + "com\\.vaadin\\.terminal\\.gwt\\.server\\.ApplicationPortlet2", // + "com\\.vaadin\\.terminal\\.gwt\\.server\\.Constants", // + "com\\.vaadin\\.util\\.SerializerHelper", // fully static + // class level filtering, also affecting nested classes and + // interfaces + "com\\.vaadin\\.terminal\\.gwt\\.server\\.AbstractCommunicationManager.*", // + "com\\.vaadin\\.terminal\\.gwt\\.server\\.ApplicationRunnerServlet.*", // + "com\\.vaadin\\.terminal\\.gwt\\.server\\.CommunicationManager.*", // + "com\\.vaadin\\.terminal\\.gwt\\.server\\.PortletCommunicationManager.*", // + }; + + /** + * Tests that all the relevant classes and interfaces under + * {@link #BASE_PACKAGES} implement Serializable. + * + * @throws Exception + */ + public void testClassesSerializable() throws Exception { + List<String> rawClasspathEntries = getRawClasspathEntries(); + + List<String> classes = new ArrayList<String>(); + for (String location : rawClasspathEntries) { + classes.addAll(findServerClasses(location)); + } + + ArrayList<Class<?>> nonSerializableClasses = new ArrayList<Class<?>>(); + for (String className : classes) { + Class<?> cls = Class.forName(className); + // skip annotations and synthetic classes + if (cls.isAnnotation() || cls.isSynthetic()) { + continue; + } + // Don't add classes that have a @Test annotation on any methods + boolean testPresent = false; + for (Method method : cls.getMethods()) { + if (method.isAnnotationPresent(Test.class)) { + testPresent = true; + break; + } + } + if (testPresent) { + continue; + } + + // report non-serializable classes and interfaces + if (!Serializable.class.isAssignableFrom(cls)) { + nonSerializableClasses.add(cls); + // TODO easier to read when testing + // System.err.println(cls); + } + } + + // useful failure message including all non-serializable classes and + // interfaces + if (!nonSerializableClasses.isEmpty()) { + String nonSerializableString = ""; + Iterator<Class<?>> it = nonSerializableClasses.iterator(); + nonSerializableString = it.next().getName(); + while (it.hasNext()) { + nonSerializableString += ", " + it.next().getName(); + } + fail("Serializable not implemented by the following classes and interfaces: " + + nonSerializableString); + } + } + + /** + * Lists all class path entries by splitting the class path string. + * + * Adapted from ClassPathExplorer.getRawClasspathEntries(), but without + * filtering. + * + * @return List of class path segment strings + */ + // + private final static List<String> getRawClasspathEntries() { + // try to keep the order of the classpath + List<String> locations = new ArrayList<String>(); + + String pathSep = System.getProperty("path.separator"); + String classpath = System.getProperty("java.class.path"); + + if (classpath.startsWith("\"")) { + classpath = classpath.substring(1); + } + if (classpath.endsWith("\"")) { + classpath = classpath.substring(0, classpath.length() - 1); + } + + String[] split = classpath.split(pathSep); + for (int i = 0; i < split.length; i++) { + String classpathEntry = split[i]; + locations.add(classpathEntry); + } + + return locations; + } + + /** + * Finds the server side classes/interfaces under a class path entry - + * either a directory or a JAR that matches {@link #JAR_PATTERN}. + * + * Only classes under {@link #BASE_PACKAGES} are considered, and those + * matching {@link #EXCLUDED_PATTERNS} are filtered out. + * + * @param classpathEntry + * @return + * @throws IOException + */ + private List<String> findServerClasses(String classpathEntry) + throws IOException { + Collection<String> classes = new ArrayList<String>(); + + File file = new File(classpathEntry); + if (file.isDirectory()) { + classes = findClassesInDirectory(null, file); + } else if (file.getName().matches(JAR_PATTERN)) { + classes = findClassesInJar(file); + } else { + System.out.println("Ignoring " + classpathEntry); + return Collections.emptyList(); + } + + List<String> filteredClasses = new ArrayList<String>(); + for (String className : classes) { + boolean ok = false; + for (String basePackage : BASE_PACKAGES) { + if (className.startsWith(basePackage + ".")) { + ok = true; + break; + } + } + for (String excludedPrefix : EXCLUDED_PATTERNS) { + if (className.matches(excludedPrefix)) { + ok = false; + break; + } + } + + // Don't add test classes + if (className.contains("Test")) { + ok = false; + } + + if (ok) { + filteredClasses.add(className); + } + } + + return filteredClasses; + } + + /** + * Lists class names (based on .class files) in a JAR file. + * + * @param file + * a valid JAR file + * @return collection of fully qualified class names in the JAR + * @throws IOException + */ + private Collection<String> findClassesInJar(File file) throws IOException { + Collection<String> classes = new ArrayList<String>(); + + JarFile jar = new JarFile(file); + Enumeration<JarEntry> e = jar.entries(); + while (e.hasMoreElements()) { + JarEntry entry = e.nextElement(); + if (entry.getName().endsWith(".class")) { + String nameWithoutExtension = entry.getName().replaceAll( + "\\.class", ""); + String className = nameWithoutExtension.replace('/', '.'); + classes.add(className); + } + } + return classes; + } + + /** + * Lists class names (based on .class files) in a directory (a package path + * root). + * + * @param parentPackage + * parent package name or null at root of hierarchy, used by + * recursion + * @param parent + * File representing the directory to scan + * @return collection of fully qualified class names in the directory + */ + private final static Collection<String> findClassesInDirectory( + String parentPackage, File parent) { + if (parent.isHidden() + || parent.getPath().contains(File.separator + ".")) { + return Collections.emptyList(); + } + + if (parentPackage == null) { + parentPackage = ""; + } else { + parentPackage += "."; + } + + Collection<String> classNames = new ArrayList<String>(); + + // add all directories recursively + File[] files = parent.listFiles(); + for (File child : files) { + if (child.isDirectory()) { + classNames.addAll(findClassesInDirectory( + parentPackage + child.getName(), child)); + } else if (child.getName().endsWith(".class")) { + classNames.add(parentPackage.replace(File.separatorChar, '.') + + child.getName().replaceAll("\\.class", "")); + } + } + + return classNames; + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/TestKeyMapper.java b/tests/server-side/com/vaadin/tests/server/TestKeyMapper.java index 02ea45ce7c..ca33cf3314 100644 --- a/tests/server-side/com/vaadin/tests/server/TestKeyMapper.java +++ b/tests/server-side/com/vaadin/tests/server/TestKeyMapper.java @@ -1,102 +1,102 @@ -package com.vaadin.tests.server;
-
-import java.lang.reflect.Field;
-import java.util.Hashtable;
-
-import junit.framework.TestCase;
-
-import com.vaadin.terminal.KeyMapper;
-
-public class TestKeyMapper extends TestCase {
-
- public void testAdd() {
- KeyMapper mapper = new KeyMapper();
- Object o1 = new Object();
- Object o2 = new Object();
- Object o3 = new Object();
-
- // Create new ids
- String key1 = mapper.key(o1);
- String key2 = mapper.key(o2);
- String key3 = mapper.key(o3);
-
- assertEquals(mapper.get(key1), o1);
- assertEquals(mapper.get(key2), o2);
- assertEquals(mapper.get(key3), o3);
- assertNotSame(key1, key2);
- assertNotSame(key1, key3);
- assertNotSame(key2, key3);
-
- assertSize(mapper, 3);
-
- // Key should not add if there already is a mapping
- assertEquals(mapper.key(o3), key3);
- assertSize(mapper, 3);
-
- // Remove -> add should return a new key
- mapper.remove(o1);
- String newkey1 = mapper.key(o1);
- assertNotSame(key1, newkey1);
-
- }
-
- public void testRemoveAll() {
- KeyMapper mapper = new KeyMapper();
- Object o1 = new Object();
- Object o2 = new Object();
- Object o3 = new Object();
-
- // Create new ids
- mapper.key(o1);
- mapper.key(o2);
- mapper.key(o3);
-
- assertSize(mapper, 3);
- mapper.removeAll();
- assertSize(mapper, 0);
-
- }
-
- public void testRemove() {
- KeyMapper mapper = new KeyMapper();
- Object o1 = new Object();
- Object o2 = new Object();
- Object o3 = new Object();
-
- // Create new ids
- mapper.key(o1);
- mapper.key(o2);
- mapper.key(o3);
-
- assertSize(mapper, 3);
- mapper.remove(o1);
- assertSize(mapper, 2);
- mapper.key(o1);
- assertSize(mapper, 3);
- mapper.remove(o1);
- assertSize(mapper, 2);
-
- mapper.remove(o2);
- mapper.remove(o3);
- assertSize(mapper, 0);
-
- }
-
- private void assertSize(KeyMapper mapper, int i) {
- try {
- Field f1 = KeyMapper.class.getDeclaredField("objectKeyMap");
- Field f2 = KeyMapper.class.getDeclaredField("keyObjectMap");
- f1.setAccessible(true);
- f2.setAccessible(true);
-
- Hashtable<?, ?> h1 = (Hashtable<?, ?>) f1.get(mapper);
- Hashtable<?, ?> h2 = (Hashtable<?, ?>) f2.get(mapper);
-
- assertEquals(i, h1.size());
- assertEquals(i, h2.size());
- } catch (Throwable t) {
- t.printStackTrace();
- fail();
- }
- }
-}
+package com.vaadin.tests.server; + +import java.lang.reflect.Field; +import java.util.Hashtable; + +import junit.framework.TestCase; + +import com.vaadin.terminal.KeyMapper; + +public class TestKeyMapper extends TestCase { + + public void testAdd() { + KeyMapper mapper = new KeyMapper(); + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + // Create new ids + String key1 = mapper.key(o1); + String key2 = mapper.key(o2); + String key3 = mapper.key(o3); + + assertEquals(mapper.get(key1), o1); + assertEquals(mapper.get(key2), o2); + assertEquals(mapper.get(key3), o3); + assertNotSame(key1, key2); + assertNotSame(key1, key3); + assertNotSame(key2, key3); + + assertSize(mapper, 3); + + // Key should not add if there already is a mapping + assertEquals(mapper.key(o3), key3); + assertSize(mapper, 3); + + // Remove -> add should return a new key + mapper.remove(o1); + String newkey1 = mapper.key(o1); + assertNotSame(key1, newkey1); + + } + + public void testRemoveAll() { + KeyMapper mapper = new KeyMapper(); + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + // Create new ids + mapper.key(o1); + mapper.key(o2); + mapper.key(o3); + + assertSize(mapper, 3); + mapper.removeAll(); + assertSize(mapper, 0); + + } + + public void testRemove() { + KeyMapper mapper = new KeyMapper(); + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + // Create new ids + mapper.key(o1); + mapper.key(o2); + mapper.key(o3); + + assertSize(mapper, 3); + mapper.remove(o1); + assertSize(mapper, 2); + mapper.key(o1); + assertSize(mapper, 3); + mapper.remove(o1); + assertSize(mapper, 2); + + mapper.remove(o2); + mapper.remove(o3); + assertSize(mapper, 0); + + } + + private void assertSize(KeyMapper mapper, int i) { + try { + Field f1 = KeyMapper.class.getDeclaredField("objectKeyMap"); + Field f2 = KeyMapper.class.getDeclaredField("keyObjectMap"); + f1.setAccessible(true); + f2.setAccessible(true); + + Hashtable<?, ?> h1 = (Hashtable<?, ?>) f1.get(mapper); + Hashtable<?, ?> h2 = (Hashtable<?, ?>) f2.get(mapper); + + assertEquals(i, h1.size()); + assertEquals(i, h2.size()); + } catch (Throwable t) { + t.printStackTrace(); + fail(); + } + } +} diff --git a/tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java b/tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java index 3f16bb262b..224c9f5964 100644 --- a/tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java +++ b/tests/server-side/com/vaadin/tests/server/TransactionListenersConcurrency.java @@ -1,185 +1,185 @@ -package com.vaadin.tests.server;
-
-import static org.easymock.EasyMock.createMock;
-
-import java.lang.Thread.UncaughtExceptionHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.Random;
-
-import javax.servlet.http.HttpSession;
-
-import junit.framework.TestCase;
-
-import org.easymock.EasyMock;
-
-import com.vaadin.Application;
-import com.vaadin.service.ApplicationContext.TransactionListener;
-import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext;
-import com.vaadin.terminal.gwt.server.WebApplicationContext;
-
-public class TransactionListenersConcurrency extends TestCase {
-
- /**
- * This test starts N threads concurrently. Each thread creates an
- * application which adds a transaction listener to the context. A
- * transaction is then started for each application. Some semi-random delays
- * are included so that calls to addTransactionListener and
- * WebApplicationContext.startTransaction are mixed.
- *
- */
- public void testTransactionListeners() throws Exception {
- final List<Throwable> exceptions = new ArrayList<Throwable>();
-
- HttpSession session = createSession();
- final WebApplicationContext context = WebApplicationContext
- .getApplicationContext(session);
- List<Thread> threads = new ArrayList<Thread>();
-
- for (int i = 0; i < 5; i++) {
- Thread t = new Thread(new Runnable() {
-
- public void run() {
- Application app = new Application() {
-
- @Override
- public void init() {
- // Sleep 0-1000ms so another transaction has time to
- // start before we add the transaction listener.
- try {
- Thread.sleep((long) (1000 * new Random()
- .nextDouble()));
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- getContext().addTransactionListener(
- new DelayTransactionListener(2000));
- }
-
- };
-
- // Start the application so the transaction listener is
- // called later on.
- try {
-
- app.start(new URL("http://localhost/"),
- new Properties(), context);
- } catch (MalformedURLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- try {
- // Call the transaction listener using reflection as
- // startTransaction is protected.
-
- Method m = AbstractWebApplicationContext.class
- .getDeclaredMethod("startTransaction",
- Application.class, Object.class);
- m.setAccessible(true);
- m.invoke(context, app, null);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- });
-
- threads.add(t);
- t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
-
- public void uncaughtException(Thread t, Throwable e) {
- e = e.getCause();
- exceptions.add(e);
- }
- });
- }
-
- // Start the threads and wait for all of them to finish
- for (Thread t : threads) {
- t.start();
- }
- int running = threads.size();
-
- while (running > 0) {
- for (Iterator<Thread> i = threads.iterator(); i.hasNext();) {
- Thread t = i.next();
- if (!t.isAlive()) {
- running--;
- i.remove();
- }
- }
- }
-
- for (Throwable t : exceptions) {
- if (t instanceof InvocationTargetException) {
- t = t.getCause();
- }
- t.printStackTrace(System.err);
- fail(t.getClass().getName());
- }
-
- System.out.println("Done, all ok");
-
- }
-
- /**
- * Creates a HttpSession mock
- *
- */
- private static HttpSession createSession() {
- HttpSession session = createMock(HttpSession.class);
- EasyMock.expect(
- session.getAttribute(WebApplicationContext.class.getName()))
- .andReturn(null).anyTimes();
- session.setAttribute(
- EasyMock.eq(WebApplicationContext.class.getName()),
- EasyMock.anyObject());
-
- EasyMock.replay(session);
- return session;
- }
-
- /**
- * A transaction listener that just sleeps for the given amount of time in
- * transactionStart and transactionEnd.
- *
- */
- public static class DelayTransactionListener implements TransactionListener {
-
- private int delay;
-
- public DelayTransactionListener(int delay) {
- this.delay = delay;
- }
-
- public void transactionStart(Application application,
- Object transactionData) {
- try {
- Thread.sleep(delay);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- }
-
- public void transactionEnd(Application application,
- Object transactionData) {
- try {
- Thread.sleep(delay);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- }
- }
-
-}
+package com.vaadin.tests.server; + +import static org.easymock.EasyMock.createMock; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.Random; + +import javax.servlet.http.HttpSession; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.Application; +import com.vaadin.service.ApplicationContext.TransactionListener; +import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext; +import com.vaadin.terminal.gwt.server.WebApplicationContext; + +public class TransactionListenersConcurrency extends TestCase { + + /** + * This test starts N threads concurrently. Each thread creates an + * application which adds a transaction listener to the context. A + * transaction is then started for each application. Some semi-random delays + * are included so that calls to addTransactionListener and + * WebApplicationContext.startTransaction are mixed. + * + */ + public void testTransactionListeners() throws Exception { + final List<Throwable> exceptions = new ArrayList<Throwable>(); + + HttpSession session = createSession(); + final WebApplicationContext context = WebApplicationContext + .getApplicationContext(session); + List<Thread> threads = new ArrayList<Thread>(); + + for (int i = 0; i < 5; i++) { + Thread t = new Thread(new Runnable() { + + public void run() { + Application app = new Application() { + + @Override + public void init() { + // Sleep 0-1000ms so another transaction has time to + // start before we add the transaction listener. + try { + Thread.sleep((long) (1000 * new Random() + .nextDouble())); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + getContext().addTransactionListener( + new DelayTransactionListener(2000)); + } + + }; + + // Start the application so the transaction listener is + // called later on. + try { + + app.start(new URL("http://localhost/"), + new Properties(), context); + } catch (MalformedURLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + // Call the transaction listener using reflection as + // startTransaction is protected. + + Method m = AbstractWebApplicationContext.class + .getDeclaredMethod("startTransaction", + Application.class, Object.class); + m.setAccessible(true); + m.invoke(context, app, null); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + }); + + threads.add(t); + t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { + + public void uncaughtException(Thread t, Throwable e) { + e = e.getCause(); + exceptions.add(e); + } + }); + } + + // Start the threads and wait for all of them to finish + for (Thread t : threads) { + t.start(); + } + int running = threads.size(); + + while (running > 0) { + for (Iterator<Thread> i = threads.iterator(); i.hasNext();) { + Thread t = i.next(); + if (!t.isAlive()) { + running--; + i.remove(); + } + } + } + + for (Throwable t : exceptions) { + if (t instanceof InvocationTargetException) { + t = t.getCause(); + } + t.printStackTrace(System.err); + fail(t.getClass().getName()); + } + + System.out.println("Done, all ok"); + + } + + /** + * Creates a HttpSession mock + * + */ + private static HttpSession createSession() { + HttpSession session = createMock(HttpSession.class); + EasyMock.expect( + session.getAttribute(WebApplicationContext.class.getName())) + .andReturn(null).anyTimes(); + session.setAttribute( + EasyMock.eq(WebApplicationContext.class.getName()), + EasyMock.anyObject()); + + EasyMock.replay(session); + return session; + } + + /** + * A transaction listener that just sleeps for the given amount of time in + * transactionStart and transactionEnd. + * + */ + public static class DelayTransactionListener implements TransactionListener { + + private int delay; + + public DelayTransactionListener(int delay) { + this.delay = delay; + } + + public void transactionStart(Application application, + Object transactionData) { + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + public void transactionEnd(Application application, + Object transactionData) { + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java b/tests/server-side/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java index a569ea03e9..7d6db42d1a 100644 --- a/tests/server-side/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.absolutelayout;
-
-import com.vaadin.event.LayoutEvents.LayoutClickEvent;
-import com.vaadin.event.LayoutEvents.LayoutClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.AbsoluteLayout;
-
-public class AbsoluteLayoutListeners extends AbstractListenerMethodsTest {
- public void testLayoutClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(AbsoluteLayout.class, LayoutClickEvent.class,
- LayoutClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.absolutelayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.AbsoluteLayout; + +public class AbsoluteLayoutListeners extends AbstractListenerMethodsTest { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbsoluteLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java b/tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java index 6fc7fbba0d..ee8ef6bfbc 100644 --- a/tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java +++ b/tests/server-side/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java @@ -1,205 +1,205 @@ -package com.vaadin.tests.server.component.absolutelayout;
-
-import junit.framework.TestCase;
-
-import com.vaadin.terminal.Sizeable;
-import com.vaadin.ui.AbsoluteLayout;
-import com.vaadin.ui.Button;
-
-public class ComponentPosition extends TestCase {
-
- private static final String CSS = "top:7.0px;right:7.0%;bottom:7.0pc;left:7.0em;z-index:7;";
- private static final String PARTIAL_CSS = "top:7.0px;left:7.0em;";
- private static final Float CSS_VALUE = Float.valueOf(7);
-
- private static final int UNIT_UNSET = Sizeable.UNITS_PIXELS;
-
- /**
- * Add component w/o giving positions, assert that everything is unset
- */
- public void testNoPosition() {
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b);
-
- assertNull(layout.getPosition(b).getTopValue());
- assertNull(layout.getPosition(b).getBottomValue());
- assertNull(layout.getPosition(b).getLeftValue());
- assertNull(layout.getPosition(b).getRightValue());
-
- assertEquals(UNIT_UNSET, layout.getPosition(b).getTopUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getLeftUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());
-
- assertEquals(-1, layout.getPosition(b).getZIndex());
-
- assertEquals("", layout.getPosition(b).getCSSString());
-
- }
-
- /**
- * Add component, setting all attributes using CSS, assert getter agree
- */
- public void testFullCss() {
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b, CSS);
-
- assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());
- assertEquals(CSS_VALUE, layout.getPosition(b).getBottomValue());
- assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());
- assertEquals(CSS_VALUE, layout.getPosition(b).getRightValue());
-
- assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits());
- assertEquals(Sizeable.UNITS_PICAS, layout.getPosition(b)
- .getBottomUnits());
- assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits());
- assertEquals(Sizeable.UNITS_PERCENTAGE, layout.getPosition(b)
- .getRightUnits());
-
- assertEquals(7, layout.getPosition(b).getZIndex());
-
- assertEquals(CSS, layout.getPosition(b).getCSSString());
-
- }
-
- /**
- * Add component, setting some attributes using CSS, assert getters agree
- */
- public void testPartialCss() {
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b, PARTIAL_CSS);
-
- assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());
- assertNull(layout.getPosition(b).getBottomValue());
- assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());
- assertNull(layout.getPosition(b).getRightValue());
-
- assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());
- assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());
-
- assertEquals(-1, layout.getPosition(b).getZIndex());
-
- assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString());
-
- }
-
- /**
- * Add component setting all attributes using CSS, then reset using partial
- * CSS; assert getters agree and the appropriate attributes are unset.
- */
- public void testPartialCssReset() {
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b, CSS);
-
- layout.getPosition(b).setCSSString(PARTIAL_CSS);
-
- assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue());
- assertNull(layout.getPosition(b).getBottomValue());
- assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue());
- assertNull(layout.getPosition(b).getRightValue());
-
- assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits());
- assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits());
- assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits());
-
- assertEquals(-1, layout.getPosition(b).getZIndex());
-
- assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString());
-
- }
-
- /**
- * Add component, then set all position attributes with individual setters
- * for value and units; assert getters agree.
- */
- public void testSetPosition() {
- final Float SIZE = Float.valueOf(12);
-
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b);
-
- layout.getPosition(b).setTopValue(SIZE);
- layout.getPosition(b).setRightValue(SIZE);
- layout.getPosition(b).setBottomValue(SIZE);
- layout.getPosition(b).setLeftValue(SIZE);
-
- layout.getPosition(b).setTopUnits(Sizeable.UNITS_CM);
- layout.getPosition(b).setRightUnits(Sizeable.UNITS_EX);
- layout.getPosition(b).setBottomUnits(Sizeable.UNITS_INCH);
- layout.getPosition(b).setLeftUnits(Sizeable.UNITS_MM);
-
- assertEquals(SIZE, layout.getPosition(b).getTopValue());
- assertEquals(SIZE, layout.getPosition(b).getRightValue());
- assertEquals(SIZE, layout.getPosition(b).getBottomValue());
- assertEquals(SIZE, layout.getPosition(b).getLeftValue());
-
- assertEquals(Sizeable.UNITS_CM, layout.getPosition(b).getTopUnits());
- assertEquals(Sizeable.UNITS_EX, layout.getPosition(b).getRightUnits());
- assertEquals(Sizeable.UNITS_INCH, layout.getPosition(b)
- .getBottomUnits());
- assertEquals(Sizeable.UNITS_MM, layout.getPosition(b).getLeftUnits());
-
- }
-
- /**
- * Add component, then set all position attributes with combined setters for
- * value and units; assert getters agree.
- */
- public void testSetPosition2() {
- final Float SIZE = Float.valueOf(12);
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b);
-
- layout.getPosition(b).setTop(SIZE, Sizeable.UNITS_CM);
- layout.getPosition(b).setRight(SIZE, Sizeable.UNITS_EX);
- layout.getPosition(b).setBottom(SIZE, Sizeable.UNITS_INCH);
- layout.getPosition(b).setLeft(SIZE, Sizeable.UNITS_MM);
-
- assertEquals(SIZE, layout.getPosition(b).getTopValue());
- assertEquals(SIZE, layout.getPosition(b).getRightValue());
- assertEquals(SIZE, layout.getPosition(b).getBottomValue());
- assertEquals(SIZE, layout.getPosition(b).getLeftValue());
-
- assertEquals(Sizeable.UNITS_CM, layout.getPosition(b).getTopUnits());
- assertEquals(Sizeable.UNITS_EX, layout.getPosition(b).getRightUnits());
- assertEquals(Sizeable.UNITS_INCH, layout.getPosition(b)
- .getBottomUnits());
- assertEquals(Sizeable.UNITS_MM, layout.getPosition(b).getLeftUnits());
-
- }
-
- /**
- * Add component, set all attributes using CSS, unset some using method
- * calls, assert getters agree.
- */
- public void testUnsetPosition() {
- AbsoluteLayout layout = new AbsoluteLayout();
- Button b = new Button();
- layout.addComponent(b, CSS);
-
- layout.getPosition(b).setTopValue(null);
- layout.getPosition(b).setRightValue(null);
- layout.getPosition(b).setBottomValue(null);
- layout.getPosition(b).setLeftValue(null);
-
- layout.getPosition(b).setZIndex(-1);
-
- assertNull(layout.getPosition(b).getTopValue());
- assertNull(layout.getPosition(b).getBottomValue());
- assertNull(layout.getPosition(b).getLeftValue());
- assertNull(layout.getPosition(b).getRightValue());
-
- assertEquals("", layout.getPosition(b).getCSSString());
-
- }
-
-}
+package com.vaadin.tests.server.component.absolutelayout; + +import junit.framework.TestCase; + +import com.vaadin.terminal.Sizeable; +import com.vaadin.ui.AbsoluteLayout; +import com.vaadin.ui.Button; + +public class ComponentPosition extends TestCase { + + private static final String CSS = "top:7.0px;right:7.0%;bottom:7.0pc;left:7.0em;z-index:7;"; + private static final String PARTIAL_CSS = "top:7.0px;left:7.0em;"; + private static final Float CSS_VALUE = Float.valueOf(7); + + private static final int UNIT_UNSET = Sizeable.UNITS_PIXELS; + + /** + * Add component w/o giving positions, assert that everything is unset + */ + public void testNoPosition() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b); + + assertNull(layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertNull(layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals(UNIT_UNSET, layout.getPosition(b).getTopUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getLeftUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); + + assertEquals(-1, layout.getPosition(b).getZIndex()); + + assertEquals("", layout.getPosition(b).getCSSString()); + + } + + /** + * Add component, setting all attributes using CSS, assert getter agree + */ + public void testFullCss() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, CSS); + + assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getBottomValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getRightValue()); + + assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits()); + assertEquals(Sizeable.UNITS_PICAS, layout.getPosition(b) + .getBottomUnits()); + assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits()); + assertEquals(Sizeable.UNITS_PERCENTAGE, layout.getPosition(b) + .getRightUnits()); + + assertEquals(7, layout.getPosition(b).getZIndex()); + + assertEquals(CSS, layout.getPosition(b).getCSSString()); + + } + + /** + * Add component, setting some attributes using CSS, assert getters agree + */ + public void testPartialCss() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, PARTIAL_CSS); + + assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); + assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); + + assertEquals(-1, layout.getPosition(b).getZIndex()); + + assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString()); + + } + + /** + * Add component setting all attributes using CSS, then reset using partial + * CSS; assert getters agree and the appropriate attributes are unset. + */ + public void testPartialCssReset() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, CSS); + + layout.getPosition(b).setCSSString(PARTIAL_CSS); + + assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals(Sizeable.UNITS_PIXELS, layout.getPosition(b).getTopUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); + assertEquals(Sizeable.UNITS_EM, layout.getPosition(b).getLeftUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); + + assertEquals(-1, layout.getPosition(b).getZIndex()); + + assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString()); + + } + + /** + * Add component, then set all position attributes with individual setters + * for value and units; assert getters agree. + */ + public void testSetPosition() { + final Float SIZE = Float.valueOf(12); + + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b); + + layout.getPosition(b).setTopValue(SIZE); + layout.getPosition(b).setRightValue(SIZE); + layout.getPosition(b).setBottomValue(SIZE); + layout.getPosition(b).setLeftValue(SIZE); + + layout.getPosition(b).setTopUnits(Sizeable.UNITS_CM); + layout.getPosition(b).setRightUnits(Sizeable.UNITS_EX); + layout.getPosition(b).setBottomUnits(Sizeable.UNITS_INCH); + layout.getPosition(b).setLeftUnits(Sizeable.UNITS_MM); + + assertEquals(SIZE, layout.getPosition(b).getTopValue()); + assertEquals(SIZE, layout.getPosition(b).getRightValue()); + assertEquals(SIZE, layout.getPosition(b).getBottomValue()); + assertEquals(SIZE, layout.getPosition(b).getLeftValue()); + + assertEquals(Sizeable.UNITS_CM, layout.getPosition(b).getTopUnits()); + assertEquals(Sizeable.UNITS_EX, layout.getPosition(b).getRightUnits()); + assertEquals(Sizeable.UNITS_INCH, layout.getPosition(b) + .getBottomUnits()); + assertEquals(Sizeable.UNITS_MM, layout.getPosition(b).getLeftUnits()); + + } + + /** + * Add component, then set all position attributes with combined setters for + * value and units; assert getters agree. + */ + public void testSetPosition2() { + final Float SIZE = Float.valueOf(12); + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b); + + layout.getPosition(b).setTop(SIZE, Sizeable.UNITS_CM); + layout.getPosition(b).setRight(SIZE, Sizeable.UNITS_EX); + layout.getPosition(b).setBottom(SIZE, Sizeable.UNITS_INCH); + layout.getPosition(b).setLeft(SIZE, Sizeable.UNITS_MM); + + assertEquals(SIZE, layout.getPosition(b).getTopValue()); + assertEquals(SIZE, layout.getPosition(b).getRightValue()); + assertEquals(SIZE, layout.getPosition(b).getBottomValue()); + assertEquals(SIZE, layout.getPosition(b).getLeftValue()); + + assertEquals(Sizeable.UNITS_CM, layout.getPosition(b).getTopUnits()); + assertEquals(Sizeable.UNITS_EX, layout.getPosition(b).getRightUnits()); + assertEquals(Sizeable.UNITS_INCH, layout.getPosition(b) + .getBottomUnits()); + assertEquals(Sizeable.UNITS_MM, layout.getPosition(b).getLeftUnits()); + + } + + /** + * Add component, set all attributes using CSS, unset some using method + * calls, assert getters agree. + */ + public void testUnsetPosition() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, CSS); + + layout.getPosition(b).setTopValue(null); + layout.getPosition(b).setRightValue(null); + layout.getPosition(b).setBottomValue(null); + layout.getPosition(b).setLeftValue(null); + + layout.getPosition(b).setZIndex(-1); + + assertNull(layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertNull(layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals("", layout.getPosition(b).getCSSString()); + + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java b/tests/server-side/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java index adf9c8d72e..6a8267f296 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java @@ -1,21 +1,21 @@ -package com.vaadin.tests.server.component.abstractcomponentcontainer;
-
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.ComponentContainer.ComponentAttachEvent;
-import com.vaadin.ui.ComponentContainer.ComponentAttachListener;
-import com.vaadin.ui.ComponentContainer.ComponentDetachEvent;
-import com.vaadin.ui.ComponentContainer.ComponentDetachListener;
-import com.vaadin.ui.HorizontalLayout;
-import com.vaadin.ui.VerticalLayout;
-
-public class TestAbstractComponentContainerListeners extends AbstractListenerMethodsTest {
- public void testComponentDetachListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(HorizontalLayout.class,
- ComponentDetachEvent.class, ComponentDetachListener.class);
- }
-
- public void testComponentAttachListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(VerticalLayout.class,
- ComponentAttachEvent.class, ComponentAttachListener.class);
- }
-}
+package com.vaadin.tests.server.component.abstractcomponentcontainer; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.ComponentContainer.ComponentAttachEvent; +import com.vaadin.ui.ComponentContainer.ComponentAttachListener; +import com.vaadin.ui.ComponentContainer.ComponentDetachEvent; +import com.vaadin.ui.ComponentContainer.ComponentDetachListener; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.VerticalLayout; + +public class TestAbstractComponentContainerListeners extends AbstractListenerMethodsTest { + public void testComponentDetachListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(HorizontalLayout.class, + ComponentDetachEvent.class, ComponentDetachListener.class); + } + + public void testComponentAttachListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(VerticalLayout.class, + ComponentAttachEvent.class, ComponentAttachListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java b/tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java index 63536baf68..7ee70bde13 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java @@ -1,20 +1,20 @@ -package com.vaadin.tests.server.component.abstractfield;
-
-import com.vaadin.data.Property.ReadOnlyStatusChangeEvent;
-import com.vaadin.data.Property.ReadOnlyStatusChangeListener;
-import com.vaadin.data.Property.ValueChangeEvent;
-import com.vaadin.data.Property.ValueChangeListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Button;
-
-public class TestAbstractFieldListeners extends AbstractListenerMethodsTest {
- public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, ReadOnlyStatusChangeEvent.class,
- ReadOnlyStatusChangeListener.class);
- }
-
- public void testValueChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, ValueChangeEvent.class,
- ValueChangeListener.class);
- }
-}
+package com.vaadin.tests.server.component.abstractfield; + +import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; +import com.vaadin.data.Property.ReadOnlyStatusChangeListener; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Button; + +public class TestAbstractFieldListeners extends AbstractListenerMethodsTest { + public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, ReadOnlyStatusChangeEvent.class, + ReadOnlyStatusChangeListener.class); + } + + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, ValueChangeEvent.class, + ValueChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/AddComponentsTest.java b/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/AddComponentsTest.java index ba5ea62181..bd67841f33 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/AddComponentsTest.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/AddComponentsTest.java @@ -1,115 +1,115 @@ -package com.vaadin.tests.server.component.abstractorderedlayout;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-import org.junit.Test;
-
-import com.vaadin.ui.AbstractOrderedLayout;
-import com.vaadin.ui.Component;
-import com.vaadin.ui.HorizontalLayout;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.Layout;
-import com.vaadin.ui.VerticalLayout;
-
-public class AddComponentsTest {
-
- Component[] children = new Component[] { new Label("A"), new Label("B"),
- new Label("C"), new Label("D") };
-
- @Test
- public void moveComponentsBetweenLayouts() {
- AbstractOrderedLayout layout1 = new HorizontalLayout();
- AbstractOrderedLayout layout2 = new VerticalLayout();
-
- layout1.addComponent(children[0]);
- layout1.addComponent(children[1]);
-
- layout2.addComponent(children[2]);
- layout2.addComponent(children[3]);
-
- layout2.addComponent(children[1], 1);
- assertOrder(layout1, new int[] { 0 });
- assertOrder(layout2, new int[] { 2, 1, 3 });
-
- layout1.addComponent(children[3], 0);
- assertOrder(layout1, new int[] { 3, 0 });
- assertOrder(layout2, new int[] { 2, 1 });
-
- layout2.addComponent(children[0]);
- assertOrder(layout1, new int[] { 3 });
- assertOrder(layout2, new int[] { 2, 1, 0 });
-
- layout1.addComponentAsFirst(children[1]);
- assertOrder(layout1, new int[] { 1, 3 });
- assertOrder(layout2, new int[] { 2, 0 });
- }
-
- @Test
- public void shuffleChildComponents() {
- shuffleChildComponents(new HorizontalLayout());
- shuffleChildComponents(new VerticalLayout());
- }
-
- private void shuffleChildComponents(AbstractOrderedLayout layout) {
-
- for (int i = 0; i < children.length; ++i) {
- layout.addComponent(children[i], i);
- }
-
- assertOrder(layout, new int[] { 0, 1, 2, 3 });
-
- // Move C from #2 to #1
- // Exhibits defect #7668
- layout.addComponent(children[2], 1);
- assertOrder(layout, new int[] { 0, 2, 1, 3 });
-
- // Move C from #1 to #4 (which becomes #3 when #1 is erased)
- layout.addComponent(children[2], 4);
- assertOrder(layout, new int[] { 0, 1, 3, 2 });
-
- // Keep everything in place
- layout.addComponent(children[1], 1);
- assertOrder(layout, new int[] { 0, 1, 3, 2 });
-
- // Move D from #2 to #0
- layout.addComponent(children[3], 0);
- assertOrder(layout, new int[] { 3, 0, 1, 2 });
-
- // Move A from #1 to end (#4 which becomes #3)
- layout.addComponent(children[0]);
- assertOrder(layout, new int[] { 3, 1, 2, 0 });
-
- // Keep everything in place
- layout.addComponent(children[0]);
- assertOrder(layout, new int[] { 3, 1, 2, 0 });
-
- // Move C from #2 to #0
- layout.addComponentAsFirst(children[2]);
- assertOrder(layout, new int[] { 2, 3, 1, 0 });
-
- // Keep everything in place
- layout.addComponentAsFirst(children[2]);
- assertOrder(layout, new int[] { 2, 3, 1, 0 });
- }
-
- /**
- * Asserts that layout has the components in children in the order specified
- * by indices.
- */
- private void assertOrder(Layout layout, int[] indices) {
- Iterator<?> i = layout.getComponentIterator();
- try {
- for (int index : indices) {
- assertSame(children[index], i.next());
- }
- assertFalse("Too many components in layout", i.hasNext());
- } catch (NoSuchElementException e) {
- fail("Too few components in layout");
- }
- }
-}
+package com.vaadin.tests.server.component.abstractorderedlayout; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +import org.junit.Test; + +import com.vaadin.ui.AbstractOrderedLayout; +import com.vaadin.ui.Component; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Layout; +import com.vaadin.ui.VerticalLayout; + +public class AddComponentsTest { + + Component[] children = new Component[] { new Label("A"), new Label("B"), + new Label("C"), new Label("D") }; + + @Test + public void moveComponentsBetweenLayouts() { + AbstractOrderedLayout layout1 = new HorizontalLayout(); + AbstractOrderedLayout layout2 = new VerticalLayout(); + + layout1.addComponent(children[0]); + layout1.addComponent(children[1]); + + layout2.addComponent(children[2]); + layout2.addComponent(children[3]); + + layout2.addComponent(children[1], 1); + assertOrder(layout1, new int[] { 0 }); + assertOrder(layout2, new int[] { 2, 1, 3 }); + + layout1.addComponent(children[3], 0); + assertOrder(layout1, new int[] { 3, 0 }); + assertOrder(layout2, new int[] { 2, 1 }); + + layout2.addComponent(children[0]); + assertOrder(layout1, new int[] { 3 }); + assertOrder(layout2, new int[] { 2, 1, 0 }); + + layout1.addComponentAsFirst(children[1]); + assertOrder(layout1, new int[] { 1, 3 }); + assertOrder(layout2, new int[] { 2, 0 }); + } + + @Test + public void shuffleChildComponents() { + shuffleChildComponents(new HorizontalLayout()); + shuffleChildComponents(new VerticalLayout()); + } + + private void shuffleChildComponents(AbstractOrderedLayout layout) { + + for (int i = 0; i < children.length; ++i) { + layout.addComponent(children[i], i); + } + + assertOrder(layout, new int[] { 0, 1, 2, 3 }); + + // Move C from #2 to #1 + // Exhibits defect #7668 + layout.addComponent(children[2], 1); + assertOrder(layout, new int[] { 0, 2, 1, 3 }); + + // Move C from #1 to #4 (which becomes #3 when #1 is erased) + layout.addComponent(children[2], 4); + assertOrder(layout, new int[] { 0, 1, 3, 2 }); + + // Keep everything in place + layout.addComponent(children[1], 1); + assertOrder(layout, new int[] { 0, 1, 3, 2 }); + + // Move D from #2 to #0 + layout.addComponent(children[3], 0); + assertOrder(layout, new int[] { 3, 0, 1, 2 }); + + // Move A from #1 to end (#4 which becomes #3) + layout.addComponent(children[0]); + assertOrder(layout, new int[] { 3, 1, 2, 0 }); + + // Keep everything in place + layout.addComponent(children[0]); + assertOrder(layout, new int[] { 3, 1, 2, 0 }); + + // Move C from #2 to #0 + layout.addComponentAsFirst(children[2]); + assertOrder(layout, new int[] { 2, 3, 1, 0 }); + + // Keep everything in place + layout.addComponentAsFirst(children[2]); + assertOrder(layout, new int[] { 2, 3, 1, 0 }); + } + + /** + * Asserts that layout has the components in children in the order specified + * by indices. + */ + private void assertOrder(Layout layout, int[] indices) { + Iterator<?> i = layout.getComponentIterator(); + try { + for (int index : indices) { + assertSame(children[index], i.next()); + } + assertFalse("Too many components in layout", i.hasNext()); + } catch (NoSuchElementException e) { + fail("Too few components in layout"); + } + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java b/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java index 05dfc47126..02143a2796 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.abstractorderedlayout;
-
-import com.vaadin.event.LayoutEvents.LayoutClickEvent;
-import com.vaadin.event.LayoutEvents.LayoutClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.VerticalLayout;
-
-public class TestAbstractOrderedLayoutListeners extends AbstractListenerMethodsTest {
- public void testLayoutClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(VerticalLayout.class, LayoutClickEvent.class,
- LayoutClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.abstractorderedlayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.VerticalLayout; + +public class TestAbstractOrderedLayoutListeners extends AbstractListenerMethodsTest { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(VerticalLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java b/tests/server-side/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java index c1886943fd..75c19b0517 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java @@ -1,20 +1,20 @@ -package com.vaadin.tests.server.component.abstractselect;
-
-import com.vaadin.data.Container.ItemSetChangeEvent;
-import com.vaadin.data.Container.ItemSetChangeListener;
-import com.vaadin.data.Container.PropertySetChangeEvent;
-import com.vaadin.data.Container.PropertySetChangeListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.ComboBox;
-
-public class TestAbstractSelectListeners extends AbstractListenerMethodsTest {
- public void testItemSetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(ComboBox.class, ItemSetChangeEvent.class,
- ItemSetChangeListener.class);
- }
-
- public void testPropertySetChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(ComboBox.class, PropertySetChangeEvent.class,
- PropertySetChangeListener.class);
- }
-}
+package com.vaadin.tests.server.component.abstractselect; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.ComboBox; + +public class TestAbstractSelectListeners extends AbstractListenerMethodsTest { + public void testItemSetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(ComboBox.class, ItemSetChangeEvent.class, + ItemSetChangeListener.class); + } + + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(ComboBox.class, PropertySetChangeEvent.class, + PropertySetChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java b/tests/server-side/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java index 4f66d1446b..5e9556c182 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.abstractsplitpanel;
-
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.AbstractSplitPanel.SplitterClickEvent;
-import com.vaadin.ui.AbstractSplitPanel.SplitterClickListener;
-import com.vaadin.ui.HorizontalSplitPanel;
-
-public class TestAbstractSplitPanelListeners extends AbstractListenerMethodsTest {
- public void testSplitterClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(HorizontalSplitPanel.class,
- SplitterClickEvent.class, SplitterClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.abstractsplitpanel; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.AbstractSplitPanel.SplitterClickEvent; +import com.vaadin.ui.AbstractSplitPanel.SplitterClickListener; +import com.vaadin.ui.HorizontalSplitPanel; + +public class TestAbstractSplitPanelListeners extends AbstractListenerMethodsTest { + public void testSplitterClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(HorizontalSplitPanel.class, + SplitterClickEvent.class, SplitterClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java b/tests/server-side/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java index fb8eb65f55..9868d6ebfd 100644 --- a/tests/server-side/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java @@ -1,27 +1,27 @@ -package com.vaadin.tests.server.component.abstracttextfield;
-
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
-import com.vaadin.event.FieldEvents.TextChangeEvent;
-import com.vaadin.event.FieldEvents.TextChangeListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.TextField;
-
-public class TestAbstractTextFieldListeners extends AbstractListenerMethodsTest {
- public void testTextChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(TextField.class, TextChangeEvent.class,
- TextChangeListener.class);
- }
-
- public void testFocusListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(TextField.class, FocusEvent.class,
- FocusListener.class);
- }
-
- public void testBlurListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(TextField.class, BlurEvent.class,
- BlurListener.class);
- }
-}
+package com.vaadin.tests.server.component.abstracttextfield; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.event.FieldEvents.TextChangeEvent; +import com.vaadin.event.FieldEvents.TextChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.TextField; + +public class TestAbstractTextFieldListeners extends AbstractListenerMethodsTest { + public void testTextChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TextField.class, TextChangeEvent.class, + TextChangeListener.class); + } + + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TextField.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TextField.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/button/ButtonListeners.java b/tests/server-side/com/vaadin/tests/server/component/button/ButtonListeners.java index 59ddad4efe..dc37312eea 100644 --- a/tests/server-side/com/vaadin/tests/server/component/button/ButtonListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/button/ButtonListeners.java @@ -1,27 +1,27 @@ -package com.vaadin.tests.server.component.button;
-
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Button;
-import com.vaadin.ui.Button.ClickEvent;
-import com.vaadin.ui.Button.ClickListener;
-
-public class ButtonListeners extends AbstractListenerMethodsTest {
- public void testFocusListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, FocusEvent.class,
- FocusListener.class);
- }
-
- public void testBlurListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, BlurEvent.class,
- BlurListener.class);
- }
-
- public void testClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Button.class, ClickEvent.class,
- ClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.button; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; + +public class ButtonListeners extends AbstractListenerMethodsTest { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, BlurEvent.class, + BlurListener.class); + } + + public void testClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, ClickEvent.class, + ClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/csslayout/AddComponentsTest.java b/tests/server-side/com/vaadin/tests/server/component/csslayout/AddComponentsTest.java index 29657830e8..d4a0592768 100644 --- a/tests/server-side/com/vaadin/tests/server/component/csslayout/AddComponentsTest.java +++ b/tests/server-side/com/vaadin/tests/server/component/csslayout/AddComponentsTest.java @@ -1,109 +1,109 @@ -package com.vaadin.tests.server.component.csslayout;
-
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-import org.junit.Test;
-
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
-
-import com.vaadin.ui.Component;
-import com.vaadin.ui.CssLayout;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.Layout;
-
-public class AddComponentsTest {
-
- private Component[] children = new Component[] { new Label("A"),
- new Label("B"), new Label("C"), new Label("D") };
-
- @Test
- public void moveComponentsBetweenLayouts() {
- CssLayout layout1 = new CssLayout();
- CssLayout layout2 = new CssLayout();
-
- layout1.addComponent(children[0]);
- layout1.addComponent(children[1]);
-
- layout2.addComponent(children[2]);
- layout2.addComponent(children[3]);
-
- layout2.addComponent(children[1], 1);
- assertOrder(layout1, new int[] { 0 });
- assertOrder(layout2, new int[] { 2, 1, 3 });
-
- layout1.addComponent(children[3], 0);
- assertOrder(layout1, new int[] { 3, 0 });
- assertOrder(layout2, new int[] { 2, 1 });
-
- layout2.addComponent(children[0]);
- assertOrder(layout1, new int[] { 3 });
- assertOrder(layout2, new int[] { 2, 1, 0 });
-
- layout1.addComponentAsFirst(children[1]);
- assertOrder(layout1, new int[] { 1, 3 });
- assertOrder(layout2, new int[] { 2, 0 });
- }
-
- @Test
- public void shuffleChildComponents() {
- CssLayout layout = new CssLayout();
-
- for (int i = 0; i < children.length; ++i) {
- layout.addComponent(children[i], i);
- }
-
- assertOrder(layout, new int[] { 0, 1, 2, 3 });
-
- // Move C from #2 to #1
- // Exhibits defect #7668
- layout.addComponent(children[2], 1);
- assertOrder(layout, new int[] { 0, 2, 1, 3 });
-
- // Move C from #1 to #4 (which becomes #3 when #1 is erased)
- layout.addComponent(children[2], 4);
- assertOrder(layout, new int[] { 0, 1, 3, 2 });
-
- // Keep everything in place
- layout.addComponent(children[1], 1);
- assertOrder(layout, new int[] { 0, 1, 3, 2 });
-
- // Move D from #2 to #0
- layout.addComponent(children[3], 0);
- assertOrder(layout, new int[] { 3, 0, 1, 2 });
-
- // Move A from #1 to end (#4 which becomes #3)
- layout.addComponent(children[0]);
- assertOrder(layout, new int[] { 3, 1, 2, 0 });
-
- // Keep everything in place
- layout.addComponent(children[0]);
- assertOrder(layout, new int[] { 3, 1, 2, 0 });
-
- // Move C from #2 to #0
- layout.addComponentAsFirst(children[2]);
- assertOrder(layout, new int[] { 2, 3, 1, 0 });
-
- // Keep everything in place
- layout.addComponentAsFirst(children[2]);
- assertOrder(layout, new int[] { 2, 3, 1, 0 });
- }
-
- /**
- * Asserts that layout has the components in children in the order specified
- * by indices.
- */
- private void assertOrder(Layout layout, int[] indices) {
- Iterator<?> i = layout.getComponentIterator();
- try {
- for (int index : indices) {
- assertSame(children[index], i.next());
- }
- assertFalse("Too many components in layout", i.hasNext());
- } catch (NoSuchElementException e) {
- fail("Too few components in layout");
- }
- }
-}
+package com.vaadin.tests.server.component.csslayout; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +import org.junit.Test; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +import com.vaadin.ui.Component; +import com.vaadin.ui.CssLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Layout; + +public class AddComponentsTest { + + private Component[] children = new Component[] { new Label("A"), + new Label("B"), new Label("C"), new Label("D") }; + + @Test + public void moveComponentsBetweenLayouts() { + CssLayout layout1 = new CssLayout(); + CssLayout layout2 = new CssLayout(); + + layout1.addComponent(children[0]); + layout1.addComponent(children[1]); + + layout2.addComponent(children[2]); + layout2.addComponent(children[3]); + + layout2.addComponent(children[1], 1); + assertOrder(layout1, new int[] { 0 }); + assertOrder(layout2, new int[] { 2, 1, 3 }); + + layout1.addComponent(children[3], 0); + assertOrder(layout1, new int[] { 3, 0 }); + assertOrder(layout2, new int[] { 2, 1 }); + + layout2.addComponent(children[0]); + assertOrder(layout1, new int[] { 3 }); + assertOrder(layout2, new int[] { 2, 1, 0 }); + + layout1.addComponentAsFirst(children[1]); + assertOrder(layout1, new int[] { 1, 3 }); + assertOrder(layout2, new int[] { 2, 0 }); + } + + @Test + public void shuffleChildComponents() { + CssLayout layout = new CssLayout(); + + for (int i = 0; i < children.length; ++i) { + layout.addComponent(children[i], i); + } + + assertOrder(layout, new int[] { 0, 1, 2, 3 }); + + // Move C from #2 to #1 + // Exhibits defect #7668 + layout.addComponent(children[2], 1); + assertOrder(layout, new int[] { 0, 2, 1, 3 }); + + // Move C from #1 to #4 (which becomes #3 when #1 is erased) + layout.addComponent(children[2], 4); + assertOrder(layout, new int[] { 0, 1, 3, 2 }); + + // Keep everything in place + layout.addComponent(children[1], 1); + assertOrder(layout, new int[] { 0, 1, 3, 2 }); + + // Move D from #2 to #0 + layout.addComponent(children[3], 0); + assertOrder(layout, new int[] { 3, 0, 1, 2 }); + + // Move A from #1 to end (#4 which becomes #3) + layout.addComponent(children[0]); + assertOrder(layout, new int[] { 3, 1, 2, 0 }); + + // Keep everything in place + layout.addComponent(children[0]); + assertOrder(layout, new int[] { 3, 1, 2, 0 }); + + // Move C from #2 to #0 + layout.addComponentAsFirst(children[2]); + assertOrder(layout, new int[] { 2, 3, 1, 0 }); + + // Keep everything in place + layout.addComponentAsFirst(children[2]); + assertOrder(layout, new int[] { 2, 3, 1, 0 }); + } + + /** + * Asserts that layout has the components in children in the order specified + * by indices. + */ + private void assertOrder(Layout layout, int[] indices) { + Iterator<?> i = layout.getComponentIterator(); + try { + for (int index : indices) { + assertSame(children[index], i.next()); + } + assertFalse("Too many components in layout", i.hasNext()); + } catch (NoSuchElementException e) { + fail("Too few components in layout"); + } + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java b/tests/server-side/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java index e646467cb2..21a48888d6 100644 --- a/tests/server-side/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.csslayout;
-
-import com.vaadin.event.LayoutEvents.LayoutClickEvent;
-import com.vaadin.event.LayoutEvents.LayoutClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.CssLayout;
-
-public class CssLayoutListeners extends AbstractListenerMethodsTest {
- public void testLayoutClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(CssLayout.class, LayoutClickEvent.class,
- LayoutClickListener.class);
- }
+package com.vaadin.tests.server.component.csslayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.CssLayout; + +public class CssLayoutListeners extends AbstractListenerMethodsTest { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(CssLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } }
\ No newline at end of file diff --git a/tests/server-side/com/vaadin/tests/server/component/datefield/DateFieldListeners.java b/tests/server-side/com/vaadin/tests/server/component/datefield/DateFieldListeners.java index 1d7f729868..0f4aee35c7 100644 --- a/tests/server-side/com/vaadin/tests/server/component/datefield/DateFieldListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/datefield/DateFieldListeners.java @@ -1,20 +1,20 @@ -package com.vaadin.tests.server.component.datefield;
-
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.DateField;
-
-public class DateFieldListeners extends AbstractListenerMethodsTest {
- public void testFocusListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(DateField.class, FocusEvent.class,
- FocusListener.class);
- }
-
- public void testBlurListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(DateField.class, BlurEvent.class,
- BlurListener.class);
- }
-}
+package com.vaadin.tests.server.component.datefield; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.DateField; + +public class DateFieldListeners extends AbstractListenerMethodsTest { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(DateField.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(DateField.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/datefield/WeekNumberCalculation.java b/tests/server-side/com/vaadin/tests/server/component/datefield/WeekNumberCalculation.java index 428a8634b3..ae8bc9beae 100644 --- a/tests/server-side/com/vaadin/tests/server/component/datefield/WeekNumberCalculation.java +++ b/tests/server-side/com/vaadin/tests/server/component/datefield/WeekNumberCalculation.java @@ -1,111 +1,111 @@ -package com.vaadin.tests.server.component.datefield;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import com.vaadin.terminal.gwt.client.DateTimeService;
-
-public class WeekNumberCalculation extends TestCase {
-
- final long MILLISECONDS_PER_DAY = 24 * 3600 * 1000;
-
- static Map<Date, Integer> isoWeekNumbers = new HashMap<Date, Integer>();
- static {
- isoWeekNumbers.put(getDate(2005, 02, 02), 5);
-
- isoWeekNumbers.put(getDate(2005, 1, 1), 53);
- isoWeekNumbers.put(getDate(2005, 1, 2), 53);
- isoWeekNumbers.put(getDate(2005, 1, 3), 1);
- isoWeekNumbers.put(getDate(2005, 1, 4), 1);
- isoWeekNumbers.put(getDate(2005, 1, 5), 1);
- isoWeekNumbers.put(getDate(2005, 1, 6), 1);
- isoWeekNumbers.put(getDate(2005, 1, 7), 1);
- isoWeekNumbers.put(getDate(2005, 1, 8), 1);
- isoWeekNumbers.put(getDate(2005, 1, 9), 1);
- isoWeekNumbers.put(getDate(2005, 1, 10), 2);
- isoWeekNumbers.put(getDate(2005, 12, 31), 52);
- isoWeekNumbers.put(getDate(2005, 12, 30), 52);
- isoWeekNumbers.put(getDate(2005, 12, 29), 52);
- isoWeekNumbers.put(getDate(2005, 12, 28), 52);
- isoWeekNumbers.put(getDate(2005, 12, 27), 52);
- isoWeekNumbers.put(getDate(2005, 12, 26), 52);
- isoWeekNumbers.put(getDate(2005, 12, 25), 51);
- isoWeekNumbers.put(getDate(2007, 1, 1), 1);
- isoWeekNumbers.put(getDate(2007, 12, 30), 52);
- isoWeekNumbers.put(getDate(2007, 12, 31), 1);
- isoWeekNumbers.put(getDate(2008, 1, 1), 1);
- isoWeekNumbers.put(getDate(2008, 12, 28), 52);
- isoWeekNumbers.put(getDate(2008, 12, 29), 1);
- isoWeekNumbers.put(getDate(2008, 12, 30), 1);
- isoWeekNumbers.put(getDate(2008, 12, 31), 1);
- isoWeekNumbers.put(getDate(2009, 1, 1), 1);
- isoWeekNumbers.put(getDate(2009, 12, 31), 53);
- isoWeekNumbers.put(getDate(2010, 1, 1), 53);
- isoWeekNumbers.put(getDate(2010, 1, 2), 53);
- isoWeekNumbers.put(getDate(2010, 1, 3), 53);
- isoWeekNumbers.put(getDate(2010, 1, 4), 1);
- isoWeekNumbers.put(getDate(2010, 1, 5), 1);
- isoWeekNumbers.put(getDate(2010, 10, 10), 40);
-
- }
-
- /**
- * Test all dates from 1990-1992 + some more and see that {@link Calendar}
- * calculates the ISO week number like we do.
- *
- */
- public void testISOWeekNumbers() {
- Calendar c = Calendar.getInstance();
- c.set(1990, 1, 1);
- long start = c.getTimeInMillis();
-
- for (int i = 0; i < 1000; i++) {
- Date d = new Date(start + i * MILLISECONDS_PER_DAY);
- int expected = getCalendarISOWeekNr(d);
- int calculated = DateTimeService.getISOWeekNumber(d);
- assertEquals(d + " should be week " + expected, expected,
- calculated);
-
- }
- }
-
- /**
- * Verify that special cases are handled correctly by us (and
- * {@link Calendar}).
- *
- */
- public void testSampleISOWeekNumbers() {
- for (Date d : isoWeekNumbers.keySet()) {
- // System.out.println("Sample: " + d);
- int expected = isoWeekNumbers.get(d);
- int calculated = DateTimeService.getISOWeekNumber(d);
- assertEquals(d + " should be week " + expected
- + " (Java Calendar is wrong?)", expected,
- getCalendarISOWeekNr(d));
- assertEquals(d + " should be week " + expected, expected,
- calculated);
-
- }
- }
-
- private int getCalendarISOWeekNr(Date d) {
- Calendar c = Calendar.getInstance();
- c.setFirstDayOfWeek(Calendar.MONDAY);
- c.setMinimalDaysInFirstWeek(4);
- c.setTime(d);
-
- return c.get(Calendar.WEEK_OF_YEAR);
- }
-
- private static Date getDate(int year, int month, int date) {
- Calendar c = Calendar.getInstance();
- c.clear();
- c.set(year, month - 1, date);
- return c.getTime();
- }
-
-}
+package com.vaadin.tests.server.component.datefield; + +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import com.vaadin.terminal.gwt.client.DateTimeService; + +public class WeekNumberCalculation extends TestCase { + + final long MILLISECONDS_PER_DAY = 24 * 3600 * 1000; + + static Map<Date, Integer> isoWeekNumbers = new HashMap<Date, Integer>(); + static { + isoWeekNumbers.put(getDate(2005, 02, 02), 5); + + isoWeekNumbers.put(getDate(2005, 1, 1), 53); + isoWeekNumbers.put(getDate(2005, 1, 2), 53); + isoWeekNumbers.put(getDate(2005, 1, 3), 1); + isoWeekNumbers.put(getDate(2005, 1, 4), 1); + isoWeekNumbers.put(getDate(2005, 1, 5), 1); + isoWeekNumbers.put(getDate(2005, 1, 6), 1); + isoWeekNumbers.put(getDate(2005, 1, 7), 1); + isoWeekNumbers.put(getDate(2005, 1, 8), 1); + isoWeekNumbers.put(getDate(2005, 1, 9), 1); + isoWeekNumbers.put(getDate(2005, 1, 10), 2); + isoWeekNumbers.put(getDate(2005, 12, 31), 52); + isoWeekNumbers.put(getDate(2005, 12, 30), 52); + isoWeekNumbers.put(getDate(2005, 12, 29), 52); + isoWeekNumbers.put(getDate(2005, 12, 28), 52); + isoWeekNumbers.put(getDate(2005, 12, 27), 52); + isoWeekNumbers.put(getDate(2005, 12, 26), 52); + isoWeekNumbers.put(getDate(2005, 12, 25), 51); + isoWeekNumbers.put(getDate(2007, 1, 1), 1); + isoWeekNumbers.put(getDate(2007, 12, 30), 52); + isoWeekNumbers.put(getDate(2007, 12, 31), 1); + isoWeekNumbers.put(getDate(2008, 1, 1), 1); + isoWeekNumbers.put(getDate(2008, 12, 28), 52); + isoWeekNumbers.put(getDate(2008, 12, 29), 1); + isoWeekNumbers.put(getDate(2008, 12, 30), 1); + isoWeekNumbers.put(getDate(2008, 12, 31), 1); + isoWeekNumbers.put(getDate(2009, 1, 1), 1); + isoWeekNumbers.put(getDate(2009, 12, 31), 53); + isoWeekNumbers.put(getDate(2010, 1, 1), 53); + isoWeekNumbers.put(getDate(2010, 1, 2), 53); + isoWeekNumbers.put(getDate(2010, 1, 3), 53); + isoWeekNumbers.put(getDate(2010, 1, 4), 1); + isoWeekNumbers.put(getDate(2010, 1, 5), 1); + isoWeekNumbers.put(getDate(2010, 10, 10), 40); + + } + + /** + * Test all dates from 1990-1992 + some more and see that {@link Calendar} + * calculates the ISO week number like we do. + * + */ + public void testISOWeekNumbers() { + Calendar c = Calendar.getInstance(); + c.set(1990, 1, 1); + long start = c.getTimeInMillis(); + + for (int i = 0; i < 1000; i++) { + Date d = new Date(start + i * MILLISECONDS_PER_DAY); + int expected = getCalendarISOWeekNr(d); + int calculated = DateTimeService.getISOWeekNumber(d); + assertEquals(d + " should be week " + expected, expected, + calculated); + + } + } + + /** + * Verify that special cases are handled correctly by us (and + * {@link Calendar}). + * + */ + public void testSampleISOWeekNumbers() { + for (Date d : isoWeekNumbers.keySet()) { + // System.out.println("Sample: " + d); + int expected = isoWeekNumbers.get(d); + int calculated = DateTimeService.getISOWeekNumber(d); + assertEquals(d + " should be week " + expected + + " (Java Calendar is wrong?)", expected, + getCalendarISOWeekNr(d)); + assertEquals(d + " should be week " + expected, expected, + calculated); + + } + } + + private int getCalendarISOWeekNr(Date d) { + Calendar c = Calendar.getInstance(); + c.setFirstDayOfWeek(Calendar.MONDAY); + c.setMinimalDaysInFirstWeek(4); + c.setTime(d); + + return c.get(Calendar.WEEK_OF_YEAR); + } + + private static Date getDate(int year, int month, int date) { + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(year, month - 1, date); + return c.getTime(); + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java b/tests/server-side/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java index 66a9a2b5d5..7512f0f499 100644 --- a/tests/server-side/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.embedded;
-
-import com.vaadin.event.MouseEvents.ClickEvent;
-import com.vaadin.event.MouseEvents.ClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Embedded;
-
-public class EmbeddedListeners extends AbstractListenerMethodsTest {
- public void testClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Embedded.class, ClickEvent.class,
- ClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.embedded; + +import com.vaadin.event.MouseEvents.ClickEvent; +import com.vaadin.event.MouseEvents.ClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Embedded; + +public class EmbeddedListeners extends AbstractListenerMethodsTest { + public void testClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Embedded.class, ClickEvent.class, + ClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java b/tests/server-side/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java index 24db0856da..ce3a9faa65 100644 --- a/tests/server-side/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.gridlayout;
-
-import com.vaadin.event.LayoutEvents.LayoutClickEvent;
-import com.vaadin.event.LayoutEvents.LayoutClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.GridLayout;
-
-public class GridLayoutListeners extends AbstractListenerMethodsTest {
- public void testLayoutClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(GridLayout.class, LayoutClickEvent.class,
- LayoutClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.gridlayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.GridLayout; + +public class GridLayoutListeners extends AbstractListenerMethodsTest { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(GridLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/label/LabelListeners.java b/tests/server-side/com/vaadin/tests/server/component/label/LabelListeners.java index a25309b32f..3ed79f5010 100644 --- a/tests/server-side/com/vaadin/tests/server/component/label/LabelListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/label/LabelListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.label;
-
-import com.vaadin.data.Property.ValueChangeListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.Label.ValueChangeEvent;
-
-public class LabelListeners extends AbstractListenerMethodsTest {
- public void testValueChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Label.class, ValueChangeEvent.class,
- ValueChangeListener.class);
- }
-}
+package com.vaadin.tests.server.component.label; + +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Label; +import com.vaadin.ui.Label.ValueChangeEvent; + +public class LabelListeners extends AbstractListenerMethodsTest { + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Label.class, ValueChangeEvent.class, + ValueChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/loginform/LoginFormListeners.java b/tests/server-side/com/vaadin/tests/server/component/loginform/LoginFormListeners.java index a8e7d76710..fd3e02994c 100644 --- a/tests/server-side/com/vaadin/tests/server/component/loginform/LoginFormListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/loginform/LoginFormListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.loginform;
-
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.LoginForm;
-import com.vaadin.ui.LoginForm.LoginEvent;
-import com.vaadin.ui.LoginForm.LoginListener;
-
-public class LoginFormListeners extends AbstractListenerMethodsTest {
- public void testLoginListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(LoginForm.class, LoginEvent.class,
- LoginListener.class);
- }
-}
+package com.vaadin.tests.server.component.loginform; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.LoginForm; +import com.vaadin.ui.LoginForm.LoginEvent; +import com.vaadin.ui.LoginForm.LoginListener; + +public class LoginFormListeners extends AbstractListenerMethodsTest { + public void testLoginListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(LoginForm.class, LoginEvent.class, + LoginListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/menubar/MenuBarIds.java b/tests/server-side/com/vaadin/tests/server/component/menubar/MenuBarIds.java index 9ce55361bd..a0dadf8cc6 100644 --- a/tests/server-side/com/vaadin/tests/server/component/menubar/MenuBarIds.java +++ b/tests/server-side/com/vaadin/tests/server/component/menubar/MenuBarIds.java @@ -1,97 +1,97 @@ -package com.vaadin.tests.server.component.menubar;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-import com.vaadin.ui.MenuBar;
-import com.vaadin.ui.MenuBar.Command;
-import com.vaadin.ui.MenuBar.MenuItem;
-
-public class MenuBarIds extends TestCase implements Command {
-
- private MenuItem lastSelectedItem;
- private MenuItem menuFile;
- private MenuItem menuEdit;
- private MenuItem menuEditCopy;
- private MenuItem menuEditCut;
- private MenuItem menuEditPaste;
- private MenuItem menuEditFind;
- private MenuItem menuFileOpen;
- private MenuItem menuFileSave;
- private MenuItem menuFileExit;
- private Set<MenuItem> menuItems = new HashSet<MenuItem>();
-
- private MenuBar menuBar;
-
- @Override
- public void setUp() {
- menuBar = new MenuBar();
- menuFile = menuBar.addItem("File", this);
- menuEdit = menuBar.addItem("Edit", this);
- menuEditCopy = menuEdit.addItem("Copy", this);
- menuEditCut = menuEdit.addItem("Cut", this);
- menuEditPaste = menuEdit.addItem("Paste", this);
- menuEdit.addSeparator();
- menuEditFind = menuEdit.addItem("Find...", this);
- menuFileOpen = menuFile.addItem("Open", this);
- menuFileSave = menuFile.addItem("Save", this);
- menuFile.addSeparator();
- menuFileExit = menuFile.addItem("Exit", this);
-
- menuItems.add(menuFile);
- menuItems.add(menuEdit);
- menuItems.add(menuEditCopy);
- menuItems.add(menuEditCut);
- menuItems.add(menuEditPaste);
- menuItems.add(menuEditFind);
- menuItems.add(menuFileOpen);
- menuItems.add(menuFileSave);
- menuItems.add(menuFileExit);
- }
-
- public void testMenubarIdUniqueness() {
- // Ids within a menubar must be unique
- assertUniqueIds(menuBar);
-
- menuBar.removeItem(menuFile);
- MenuItem file2 = menuBar.addItem("File2", this);
- MenuItem file3 = menuBar.addItem("File3", this);
- MenuItem file2sub = file2.addItem("File2 sub menu", this);
- menuItems.add(file2);
- menuItems.add(file2sub);
- menuItems.add(file3);
-
- assertUniqueIds(menuBar);
- }
-
- private static void assertUniqueIds(MenuBar menuBar) {
-
- Set<Object> ids = new HashSet<Object>();
-
- for (MenuItem item : menuBar.getItems()) {
- assertUniqueIds(ids, item);
- }
- }
-
- private static void assertUniqueIds(Set<Object> ids, MenuItem item) {
- int id = item.getId();
- System.out.println("Item " + item.getText() + ", id: " + id);
- assertFalse(ids.contains(id));
- ids.add(id);
- if (item.getChildren() != null) {
- for (MenuItem subItem : item.getChildren()) {
- assertUniqueIds(ids, subItem);
- }
- }
- }
-
- public void menuSelected(MenuItem selectedItem) {
- assertNull("lastSelectedItem was not cleared before selecting an item",
- lastSelectedItem);
-
- lastSelectedItem = selectedItem;
-
- }
-}
+package com.vaadin.tests.server.component.menubar; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import com.vaadin.ui.MenuBar; +import com.vaadin.ui.MenuBar.Command; +import com.vaadin.ui.MenuBar.MenuItem; + +public class MenuBarIds extends TestCase implements Command { + + private MenuItem lastSelectedItem; + private MenuItem menuFile; + private MenuItem menuEdit; + private MenuItem menuEditCopy; + private MenuItem menuEditCut; + private MenuItem menuEditPaste; + private MenuItem menuEditFind; + private MenuItem menuFileOpen; + private MenuItem menuFileSave; + private MenuItem menuFileExit; + private Set<MenuItem> menuItems = new HashSet<MenuItem>(); + + private MenuBar menuBar; + + @Override + public void setUp() { + menuBar = new MenuBar(); + menuFile = menuBar.addItem("File", this); + menuEdit = menuBar.addItem("Edit", this); + menuEditCopy = menuEdit.addItem("Copy", this); + menuEditCut = menuEdit.addItem("Cut", this); + menuEditPaste = menuEdit.addItem("Paste", this); + menuEdit.addSeparator(); + menuEditFind = menuEdit.addItem("Find...", this); + menuFileOpen = menuFile.addItem("Open", this); + menuFileSave = menuFile.addItem("Save", this); + menuFile.addSeparator(); + menuFileExit = menuFile.addItem("Exit", this); + + menuItems.add(menuFile); + menuItems.add(menuEdit); + menuItems.add(menuEditCopy); + menuItems.add(menuEditCut); + menuItems.add(menuEditPaste); + menuItems.add(menuEditFind); + menuItems.add(menuFileOpen); + menuItems.add(menuFileSave); + menuItems.add(menuFileExit); + } + + public void testMenubarIdUniqueness() { + // Ids within a menubar must be unique + assertUniqueIds(menuBar); + + menuBar.removeItem(menuFile); + MenuItem file2 = menuBar.addItem("File2", this); + MenuItem file3 = menuBar.addItem("File3", this); + MenuItem file2sub = file2.addItem("File2 sub menu", this); + menuItems.add(file2); + menuItems.add(file2sub); + menuItems.add(file3); + + assertUniqueIds(menuBar); + } + + private static void assertUniqueIds(MenuBar menuBar) { + + Set<Object> ids = new HashSet<Object>(); + + for (MenuItem item : menuBar.getItems()) { + assertUniqueIds(ids, item); + } + } + + private static void assertUniqueIds(Set<Object> ids, MenuItem item) { + int id = item.getId(); + System.out.println("Item " + item.getText() + ", id: " + id); + assertFalse(ids.contains(id)); + ids.add(id); + if (item.getChildren() != null) { + for (MenuItem subItem : item.getChildren()) { + assertUniqueIds(ids, subItem); + } + } + } + + public void menuSelected(MenuItem selectedItem) { + assertNull("lastSelectedItem was not cleared before selecting an item", + lastSelectedItem); + + lastSelectedItem = selectedItem; + + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java b/tests/server-side/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java index a4c2289da4..7eb35c3882 100644 --- a/tests/server-side/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java @@ -1,20 +1,20 @@ -package com.vaadin.tests.server.component.optiongroup;
-
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.OptionGroup;
-
-public class OptionGroupListeners extends AbstractListenerMethodsTest {
- public void testFocusListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(OptionGroup.class, FocusEvent.class,
- FocusListener.class);
- }
-
- public void testBlurListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(OptionGroup.class, BlurEvent.class,
- BlurListener.class);
- }
-}
+package com.vaadin.tests.server.component.optiongroup; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.OptionGroup; + +public class OptionGroupListeners extends AbstractListenerMethodsTest { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(OptionGroup.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(OptionGroup.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java b/tests/server-side/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java index e17fb284dc..6a9d55d7e4 100644 --- a/tests/server-side/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java +++ b/tests/server-side/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java @@ -1,49 +1,49 @@ -package com.vaadin.tests.server.component.orderedlayout;
-
-import java.util.Iterator;
-
-import junit.framework.TestCase;
-
-import com.vaadin.ui.AbstractOrderedLayout;
-import com.vaadin.ui.Component;
-import com.vaadin.ui.HorizontalLayout;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.VerticalLayout;
-
-public class TestOrderedLayout extends TestCase {
-
- public void testVLIteration() {
- testIndexing(new VerticalLayout(), 10);
- }
-
- public void testHLIteration() {
- testIndexing(new HorizontalLayout(), 12);
- }
-
- public void testIndexing(AbstractOrderedLayout aol, int nrComponents) {
- Component[] components = generateComponents(nrComponents);
- for (Component c : components) {
- aol.addComponent(c);
- }
- for (int i = 0; i < nrComponents; i++) {
- assert (aol.getComponent(i) == components[i]);
- assert (aol.getComponentIndex(components[i]) == i);
- }
-
- // Iteration should be in indexed order
- int idx = 0;
- for (Iterator<Component> i = aol.getComponentIterator(); i.hasNext();) {
- Component c = i.next();
- assert (aol.getComponentIndex(c) == idx++);
- }
- }
-
- private Component[] generateComponents(int nr) {
- Component[] components = new Component[nr];
- for (int i = 0; i < nr; i++) {
- components[i] = new Label("" + i);
- }
-
- return components;
- }
-}
+package com.vaadin.tests.server.component.orderedlayout; + +import java.util.Iterator; + +import junit.framework.TestCase; + +import com.vaadin.ui.AbstractOrderedLayout; +import com.vaadin.ui.Component; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; + +public class TestOrderedLayout extends TestCase { + + public void testVLIteration() { + testIndexing(new VerticalLayout(), 10); + } + + public void testHLIteration() { + testIndexing(new HorizontalLayout(), 12); + } + + public void testIndexing(AbstractOrderedLayout aol, int nrComponents) { + Component[] components = generateComponents(nrComponents); + for (Component c : components) { + aol.addComponent(c); + } + for (int i = 0; i < nrComponents; i++) { + assert (aol.getComponent(i) == components[i]); + assert (aol.getComponentIndex(components[i]) == i); + } + + // Iteration should be in indexed order + int idx = 0; + for (Iterator<Component> i = aol.getComponentIterator(); i.hasNext();) { + Component c = i.next(); + assert (aol.getComponentIndex(c) == idx++); + } + } + + private Component[] generateComponents(int nr) { + Component[] components = new Component[nr]; + for (int i = 0; i < nr; i++) { + components[i] = new Label("" + i); + } + + return components; + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/panel/PanelListeners.java b/tests/server-side/com/vaadin/tests/server/component/panel/PanelListeners.java index e6094225e2..275e90f5d1 100644 --- a/tests/server-side/com/vaadin/tests/server/component/panel/PanelListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/panel/PanelListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.panel;
-
-import com.vaadin.event.MouseEvents.ClickEvent;
-import com.vaadin.event.MouseEvents.ClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Panel;
-
-public class PanelListeners extends AbstractListenerMethodsTest {
- public void testClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Panel.class, ClickEvent.class,
- ClickListener.class);
- }
-}
+package com.vaadin.tests.server.component.panel; + +import com.vaadin.event.MouseEvents.ClickEvent; +import com.vaadin.event.MouseEvents.ClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Panel; + +public class PanelListeners extends AbstractListenerMethodsTest { + public void testClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Panel.class, ClickEvent.class, + ClickListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/popupview/PopupViewListeners.java b/tests/server-side/com/vaadin/tests/server/component/popupview/PopupViewListeners.java index 5b5fc2eb31..12a5a0f520 100644 --- a/tests/server-side/com/vaadin/tests/server/component/popupview/PopupViewListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/popupview/PopupViewListeners.java @@ -1,14 +1,14 @@ -package com.vaadin.tests.server.component.popupview;
-
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.PopupView;
-import com.vaadin.ui.PopupView.PopupVisibilityEvent;
-import com.vaadin.ui.PopupView.PopupVisibilityListener;
-
-public class PopupViewListeners extends AbstractListenerMethodsTest {
- public void testPopupVisibilityListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(PopupView.class, PopupVisibilityEvent.class,
- PopupVisibilityListener.class, new PopupView("", new Label()));
- }
-}
+package com.vaadin.tests.server.component.popupview; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Label; +import com.vaadin.ui.PopupView; +import com.vaadin.ui.PopupView.PopupVisibilityEvent; +import com.vaadin.ui.PopupView.PopupVisibilityListener; + +public class PopupViewListeners extends AbstractListenerMethodsTest { + public void testPopupVisibilityListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(PopupView.class, PopupVisibilityEvent.class, + PopupVisibilityListener.class, new PopupView("", new Label())); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/select/SelectListeners.java b/tests/server-side/com/vaadin/tests/server/component/select/SelectListeners.java index 8f90f2021e..c7703303d3 100644 --- a/tests/server-side/com/vaadin/tests/server/component/select/SelectListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/select/SelectListeners.java @@ -1,20 +1,20 @@ -package com.vaadin.tests.server.component.select;
-
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Select;
-
-public class SelectListeners extends AbstractListenerMethodsTest {
- public void testFocusListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Select.class, FocusEvent.class,
- FocusListener.class);
- }
-
- public void testBlurListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Select.class, BlurEvent.class,
- BlurListener.class);
- }
+package com.vaadin.tests.server.component.select; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Select; + +public class SelectListeners extends AbstractListenerMethodsTest { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Select.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Select.class, BlurEvent.class, + BlurListener.class); + } }
\ No newline at end of file diff --git a/tests/server-side/com/vaadin/tests/server/component/table/TableListeners.java b/tests/server-side/com/vaadin/tests/server/component/table/TableListeners.java index 75ec839823..6d9c7ed0eb 100644 --- a/tests/server-side/com/vaadin/tests/server/component/table/TableListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/table/TableListeners.java @@ -1,40 +1,40 @@ -package com.vaadin.tests.server.component.table;
-
-import com.vaadin.event.ItemClickEvent;
-import com.vaadin.event.ItemClickEvent.ItemClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Table;
-import com.vaadin.ui.Table.ColumnReorderEvent;
-import com.vaadin.ui.Table.ColumnReorderListener;
-import com.vaadin.ui.Table.ColumnResizeEvent;
-import com.vaadin.ui.Table.ColumnResizeListener;
-import com.vaadin.ui.Table.FooterClickEvent;
-import com.vaadin.ui.Table.FooterClickListener;
-import com.vaadin.ui.Table.HeaderClickEvent;
-import com.vaadin.ui.Table.HeaderClickListener;
-
-public class TableListeners extends AbstractListenerMethodsTest {
- public void testColumnResizeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Table.class, ColumnResizeEvent.class,
- ColumnResizeListener.class);
- }
-
- public void testItemClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Table.class, ItemClickEvent.class, ItemClickListener.class);
- }
-
- public void testFooterClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Table.class, FooterClickEvent.class,
- FooterClickListener.class);
- }
-
- public void testHeaderClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Table.class, HeaderClickEvent.class,
- HeaderClickListener.class);
- }
-
- public void testColumnReorderListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Table.class, ColumnReorderEvent.class,
- ColumnReorderListener.class);
- }
+package com.vaadin.tests.server.component.table; + +import com.vaadin.event.ItemClickEvent; +import com.vaadin.event.ItemClickEvent.ItemClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Table; +import com.vaadin.ui.Table.ColumnReorderEvent; +import com.vaadin.ui.Table.ColumnReorderListener; +import com.vaadin.ui.Table.ColumnResizeEvent; +import com.vaadin.ui.Table.ColumnResizeListener; +import com.vaadin.ui.Table.FooterClickEvent; +import com.vaadin.ui.Table.FooterClickListener; +import com.vaadin.ui.Table.HeaderClickEvent; +import com.vaadin.ui.Table.HeaderClickListener; + +public class TableListeners extends AbstractListenerMethodsTest { + public void testColumnResizeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, ColumnResizeEvent.class, + ColumnResizeListener.class); + } + + public void testItemClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, ItemClickEvent.class, ItemClickListener.class); + } + + public void testFooterClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, FooterClickEvent.class, + FooterClickListener.class); + } + + public void testHeaderClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, HeaderClickEvent.class, + HeaderClickListener.class); + } + + public void testColumnReorderListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, ColumnReorderEvent.class, + ColumnReorderListener.class); + } }
\ No newline at end of file diff --git a/tests/server-side/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java b/tests/server-side/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java index 30dcbca155..5c01a1c99f 100644 --- a/tests/server-side/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.tabsheet;
-
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.TabSheet;
-import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
-import com.vaadin.ui.TabSheet.SelectedTabChangeListener;
-
-public class TabSheetListeners extends AbstractListenerMethodsTest {
- public void testSelectedTabChangeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(TabSheet.class, SelectedTabChangeEvent.class,
- SelectedTabChangeListener.class);
- }
-}
+package com.vaadin.tests.server.component.tabsheet; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.TabSheet.SelectedTabChangeEvent; +import com.vaadin.ui.TabSheet.SelectedTabChangeListener; + +public class TabSheetListeners extends AbstractListenerMethodsTest { + public void testSelectedTabChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TabSheet.class, SelectedTabChangeEvent.class, + SelectedTabChangeListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java b/tests/server-side/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java index 873bb1c030..1832d1bd95 100644 --- a/tests/server-side/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java +++ b/tests/server-side/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java @@ -1,124 +1,124 @@ -package com.vaadin.tests.server.component.tabsheet;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Iterator;
-
-import org.junit.Test;
-
-import com.vaadin.ui.Component;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.TabSheet;
-import com.vaadin.ui.TabSheet.Tab;
-
-public class TestTabSheet {
-
- @Test
- public void addExistingComponent() {
- Component c = new Label("abc");
- TabSheet tabSheet = new TabSheet();
- tabSheet.addComponent(c);
- tabSheet.addComponent(c);
-
- Iterator<Component> iter = tabSheet.getComponentIterator();
-
- assertEquals(c, iter.next());
- assertEquals(false, iter.hasNext());
- assertNotNull(tabSheet.getTab(c));
- }
-
- @Test
- public void getComponentFromTab() {
- Component c = new Label("abc");
- TabSheet tabSheet = new TabSheet();
- Tab tab = tabSheet.addTab(c);
- assertEquals(c, tab.getComponent());
- }
-
- @Test
- public void addTabWithComponentOnly() {
- TabSheet tabSheet = new TabSheet();
- Tab tab1 = tabSheet.addTab(new Label("aaa"));
- Tab tab2 = tabSheet.addTab(new Label("bbb"));
- Tab tab3 = tabSheet.addTab(new Label("ccc"));
-
- // Check right order of tabs
- assertEquals(0, tabSheet.getTabPosition(tab1));
- assertEquals(1, tabSheet.getTabPosition(tab2));
- assertEquals(2, tabSheet.getTabPosition(tab3));
-
- // Calling addTab with existing component does not move tab
- tabSheet.addTab(tab1.getComponent());
-
- // Check right order of tabs
- assertEquals(0, tabSheet.getTabPosition(tab1));
- assertEquals(1, tabSheet.getTabPosition(tab2));
- assertEquals(2, tabSheet.getTabPosition(tab3));
- }
-
- @Test
- public void addTabWithComponentAndIndex() {
- TabSheet tabSheet = new TabSheet();
- Tab tab1 = tabSheet.addTab(new Label("aaa"));
- Tab tab2 = tabSheet.addTab(new Label("bbb"));
- Tab tab3 = tabSheet.addTab(new Label("ccc"));
-
- Tab tab4 = tabSheet.addTab(new Label("ddd"), 1);
- Tab tab5 = tabSheet.addTab(new Label("eee"), 3);
-
- assertEquals(0, tabSheet.getTabPosition(tab1));
- assertEquals(1, tabSheet.getTabPosition(tab4));
- assertEquals(2, tabSheet.getTabPosition(tab2));
- assertEquals(3, tabSheet.getTabPosition(tab5));
- assertEquals(4, tabSheet.getTabPosition(tab3));
-
- // Calling addTab with existing component does not move tab
- tabSheet.addTab(tab1.getComponent(), 3);
-
- assertEquals(0, tabSheet.getTabPosition(tab1));
- assertEquals(1, tabSheet.getTabPosition(tab4));
- assertEquals(2, tabSheet.getTabPosition(tab2));
- assertEquals(3, tabSheet.getTabPosition(tab5));
- assertEquals(4, tabSheet.getTabPosition(tab3));
- }
-
- @Test
- public void addTabWithAllParameters() {
- TabSheet tabSheet = new TabSheet();
- Tab tab1 = tabSheet.addTab(new Label("aaa"));
- Tab tab2 = tabSheet.addTab(new Label("bbb"));
- Tab tab3 = tabSheet.addTab(new Label("ccc"));
-
- Tab tab4 = tabSheet.addTab(new Label("ddd"), "ddd", null, 1);
- Tab tab5 = tabSheet.addTab(new Label("eee"), "eee", null, 3);
-
- assertEquals(0, tabSheet.getTabPosition(tab1));
- assertEquals(1, tabSheet.getTabPosition(tab4));
- assertEquals(2, tabSheet.getTabPosition(tab2));
- assertEquals(3, tabSheet.getTabPosition(tab5));
- assertEquals(4, tabSheet.getTabPosition(tab3));
-
- // Calling addTab with existing component does not move tab
- tabSheet.addTab(tab1.getComponent(), "xxx", null, 3);
-
- assertEquals(0, tabSheet.getTabPosition(tab1));
- assertEquals(1, tabSheet.getTabPosition(tab4));
- assertEquals(2, tabSheet.getTabPosition(tab2));
- assertEquals(3, tabSheet.getTabPosition(tab5));
- assertEquals(4, tabSheet.getTabPosition(tab3));
- }
-
- @Test
- public void getTabByPosition() {
- TabSheet tabSheet = new TabSheet();
- Tab tab1 = tabSheet.addTab(new Label("aaa"));
- Tab tab2 = tabSheet.addTab(new Label("bbb"));
- Tab tab3 = tabSheet.addTab(new Label("ccc"));
-
- assertEquals(tab1, tabSheet.getTab(0));
- assertEquals(tab2, tabSheet.getTab(1));
- assertEquals(tab3, tabSheet.getTab(2));
- }
-
-}
+package com.vaadin.tests.server.component.tabsheet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Iterator; + +import org.junit.Test; + +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.TabSheet.Tab; + +public class TestTabSheet { + + @Test + public void addExistingComponent() { + Component c = new Label("abc"); + TabSheet tabSheet = new TabSheet(); + tabSheet.addComponent(c); + tabSheet.addComponent(c); + + Iterator<Component> iter = tabSheet.getComponentIterator(); + + assertEquals(c, iter.next()); + assertEquals(false, iter.hasNext()); + assertNotNull(tabSheet.getTab(c)); + } + + @Test + public void getComponentFromTab() { + Component c = new Label("abc"); + TabSheet tabSheet = new TabSheet(); + Tab tab = tabSheet.addTab(c); + assertEquals(c, tab.getComponent()); + } + + @Test + public void addTabWithComponentOnly() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + // Check right order of tabs + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab2)); + assertEquals(2, tabSheet.getTabPosition(tab3)); + + // Calling addTab with existing component does not move tab + tabSheet.addTab(tab1.getComponent()); + + // Check right order of tabs + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab2)); + assertEquals(2, tabSheet.getTabPosition(tab3)); + } + + @Test + public void addTabWithComponentAndIndex() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + Tab tab4 = tabSheet.addTab(new Label("ddd"), 1); + Tab tab5 = tabSheet.addTab(new Label("eee"), 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + + // Calling addTab with existing component does not move tab + tabSheet.addTab(tab1.getComponent(), 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + } + + @Test + public void addTabWithAllParameters() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + Tab tab4 = tabSheet.addTab(new Label("ddd"), "ddd", null, 1); + Tab tab5 = tabSheet.addTab(new Label("eee"), "eee", null, 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + + // Calling addTab with existing component does not move tab + tabSheet.addTab(tab1.getComponent(), "xxx", null, 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + } + + @Test + public void getTabByPosition() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + assertEquals(tab1, tabSheet.getTab(0)); + assertEquals(tab2, tabSheet.getTab(1)); + assertEquals(tab3, tabSheet.getTab(2)); + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/component/tree/TestListeners.java b/tests/server-side/com/vaadin/tests/server/component/tree/TestListeners.java index 391ef02e3c..49610ff293 100644 --- a/tests/server-side/com/vaadin/tests/server/component/tree/TestListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/tree/TestListeners.java @@ -1,135 +1,135 @@ -package com.vaadin.tests.server.component.tree;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import com.vaadin.ui.Tree;
-import com.vaadin.ui.Tree.CollapseEvent;
-import com.vaadin.ui.Tree.CollapseListener;
-import com.vaadin.ui.Tree.ExpandEvent;
-import com.vaadin.ui.Tree.ExpandListener;
-
-public class TestListeners extends TestCase implements ExpandListener,
- CollapseListener {
- private int expandCalled;
- private int collapseCalled;
- private Object lastExpanded;
- private Object lastCollapsed;
-
- @Override
- protected void setUp() {
- expandCalled = 0;
- }
-
- public void testExpandListener() {
- Tree tree = createTree(10, 20, false);
- tree.addListener((ExpandListener) this);
- List<Object> rootIds = new ArrayList<Object>(tree.rootItemIds());
-
- assertEquals(10, rootIds.size());
- assertEquals(10 + 10 * 20 + 10, tree.size());
-
- // Expanding should send one expand event for the root item id
- tree.expandItem(rootIds.get(0));
- assertEquals(1, expandCalled);
- assertEquals(rootIds.get(0), lastExpanded);
-
- // Expand should send one event for each expanded item id.
- // In this case root + child 4
- expandCalled = 0;
- tree.expandItemsRecursively(rootIds.get(1));
- assertEquals(2, expandCalled);
- List<Object> c = new ArrayList<Object>(tree.getChildren(rootIds.get(1)));
-
- assertEquals(c.get(4), lastExpanded);
-
- // Expanding an already expanded item should send no expand event
- expandCalled = 0;
- tree.expandItem(rootIds.get(0));
- assertEquals(0, expandCalled);
- }
-
- /**
- * Creates a tree with "rootItems" roots, each with "children" children,
- * each with 1 child.
- *
- * @param rootItems
- * @param children
- * @param expand
- * @return
- */
- private Tree createTree(int rootItems, int children, boolean expand) {
- Tree tree = new Tree();
- for (int i = 0; i < rootItems; i++) {
- String rootId = "root " + i;
- tree.addItem(rootId);
- if (expand) {
- tree.expandItemsRecursively(rootId);
- } else {
- tree.collapseItemsRecursively(rootId);
-
- }
- for (int j = 0; j < children; j++) {
- String childId = "child " + i + "/" + j;
- tree.addItem(childId);
- tree.setParent(childId, rootId);
- tree.setChildrenAllowed(childId, false);
- if (j == 4) {
- tree.setChildrenAllowed(childId, true);
- Object grandChildId = tree.addItem();
- tree.setParent(grandChildId, childId);
- tree.setChildrenAllowed(grandChildId, false);
- if (expand) {
- tree.expandItemsRecursively(childId);
- } else {
- tree.collapseItemsRecursively(childId);
- }
- }
- }
- }
-
- return tree;
- }
-
- public void testCollapseListener() {
- Tree tree = createTree(7, 15, true);
- tree.addListener((CollapseListener) this);
-
- List<Object> rootIds = new ArrayList<Object>(tree.rootItemIds());
-
- assertEquals(7, rootIds.size());
- assertEquals(7 + 7 * 15 + 7, tree.size());
-
- // Expanding should send one expand event for the root item id
- tree.collapseItem(rootIds.get(0));
- assertEquals(1, collapseCalled);
- assertEquals(rootIds.get(0), lastCollapsed);
-
- // Collapse sends one event for each collapsed node.
- // In this case root + child 4
- collapseCalled = 0;
- tree.collapseItemsRecursively(rootIds.get(1));
- assertEquals(2, collapseCalled);
- List<Object> c = new ArrayList<Object>(tree.getChildren(rootIds.get(1)));
- assertEquals(c.get(4), lastCollapsed);
-
- // Collapsing an already expanded item should send no expand event
- collapseCalled = 0;
- tree.collapseItem(rootIds.get(0));
- assertEquals(0, collapseCalled);
- }
-
- public void nodeExpand(ExpandEvent event) {
- lastExpanded = event.getItemId();
- expandCalled++;
-
- }
-
- public void nodeCollapse(CollapseEvent event) {
- lastCollapsed = event.getItemId();
- collapseCalled++;
-
- }
-}
+package com.vaadin.tests.server.component.tree; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.vaadin.ui.Tree; +import com.vaadin.ui.Tree.CollapseEvent; +import com.vaadin.ui.Tree.CollapseListener; +import com.vaadin.ui.Tree.ExpandEvent; +import com.vaadin.ui.Tree.ExpandListener; + +public class TestListeners extends TestCase implements ExpandListener, + CollapseListener { + private int expandCalled; + private int collapseCalled; + private Object lastExpanded; + private Object lastCollapsed; + + @Override + protected void setUp() { + expandCalled = 0; + } + + public void testExpandListener() { + Tree tree = createTree(10, 20, false); + tree.addListener((ExpandListener) this); + List<Object> rootIds = new ArrayList<Object>(tree.rootItemIds()); + + assertEquals(10, rootIds.size()); + assertEquals(10 + 10 * 20 + 10, tree.size()); + + // Expanding should send one expand event for the root item id + tree.expandItem(rootIds.get(0)); + assertEquals(1, expandCalled); + assertEquals(rootIds.get(0), lastExpanded); + + // Expand should send one event for each expanded item id. + // In this case root + child 4 + expandCalled = 0; + tree.expandItemsRecursively(rootIds.get(1)); + assertEquals(2, expandCalled); + List<Object> c = new ArrayList<Object>(tree.getChildren(rootIds.get(1))); + + assertEquals(c.get(4), lastExpanded); + + // Expanding an already expanded item should send no expand event + expandCalled = 0; + tree.expandItem(rootIds.get(0)); + assertEquals(0, expandCalled); + } + + /** + * Creates a tree with "rootItems" roots, each with "children" children, + * each with 1 child. + * + * @param rootItems + * @param children + * @param expand + * @return + */ + private Tree createTree(int rootItems, int children, boolean expand) { + Tree tree = new Tree(); + for (int i = 0; i < rootItems; i++) { + String rootId = "root " + i; + tree.addItem(rootId); + if (expand) { + tree.expandItemsRecursively(rootId); + } else { + tree.collapseItemsRecursively(rootId); + + } + for (int j = 0; j < children; j++) { + String childId = "child " + i + "/" + j; + tree.addItem(childId); + tree.setParent(childId, rootId); + tree.setChildrenAllowed(childId, false); + if (j == 4) { + tree.setChildrenAllowed(childId, true); + Object grandChildId = tree.addItem(); + tree.setParent(grandChildId, childId); + tree.setChildrenAllowed(grandChildId, false); + if (expand) { + tree.expandItemsRecursively(childId); + } else { + tree.collapseItemsRecursively(childId); + } + } + } + } + + return tree; + } + + public void testCollapseListener() { + Tree tree = createTree(7, 15, true); + tree.addListener((CollapseListener) this); + + List<Object> rootIds = new ArrayList<Object>(tree.rootItemIds()); + + assertEquals(7, rootIds.size()); + assertEquals(7 + 7 * 15 + 7, tree.size()); + + // Expanding should send one expand event for the root item id + tree.collapseItem(rootIds.get(0)); + assertEquals(1, collapseCalled); + assertEquals(rootIds.get(0), lastCollapsed); + + // Collapse sends one event for each collapsed node. + // In this case root + child 4 + collapseCalled = 0; + tree.collapseItemsRecursively(rootIds.get(1)); + assertEquals(2, collapseCalled); + List<Object> c = new ArrayList<Object>(tree.getChildren(rootIds.get(1))); + assertEquals(c.get(4), lastCollapsed); + + // Collapsing an already expanded item should send no expand event + collapseCalled = 0; + tree.collapseItem(rootIds.get(0)); + assertEquals(0, collapseCalled); + } + + public void nodeExpand(ExpandEvent event) { + lastExpanded = event.getItemId(); + expandCalled++; + + } + + public void nodeCollapse(CollapseEvent event) { + lastCollapsed = event.getItemId(); + collapseCalled++; + + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/tree/TreeListeners.java b/tests/server-side/com/vaadin/tests/server/component/tree/TreeListeners.java index 8ba2e1de4d..e14ebe739d 100644 --- a/tests/server-side/com/vaadin/tests/server/component/tree/TreeListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/tree/TreeListeners.java @@ -1,27 +1,27 @@ -package com.vaadin.tests.server.component.tree;
-
-import com.vaadin.event.ItemClickEvent;
-import com.vaadin.event.ItemClickEvent.ItemClickListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Tree;
-import com.vaadin.ui.Tree.CollapseEvent;
-import com.vaadin.ui.Tree.CollapseListener;
-import com.vaadin.ui.Tree.ExpandEvent;
-import com.vaadin.ui.Tree.ExpandListener;
-
-public class TreeListeners extends AbstractListenerMethodsTest {
- public void testExpandListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Tree.class, ExpandEvent.class,
- ExpandListener.class);
- }
-
- public void testItemClickListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Tree.class, ItemClickEvent.class,
- ItemClickListener.class);
- }
-
- public void testCollapseListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Tree.class, CollapseEvent.class,
- CollapseListener.class);
- }
+package com.vaadin.tests.server.component.tree; + +import com.vaadin.event.ItemClickEvent; +import com.vaadin.event.ItemClickEvent.ItemClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Tree; +import com.vaadin.ui.Tree.CollapseEvent; +import com.vaadin.ui.Tree.CollapseListener; +import com.vaadin.ui.Tree.ExpandEvent; +import com.vaadin.ui.Tree.ExpandListener; + +public class TreeListeners extends AbstractListenerMethodsTest { + public void testExpandListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Tree.class, ExpandEvent.class, + ExpandListener.class); + } + + public void testItemClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Tree.class, ItemClickEvent.class, + ItemClickListener.class); + } + + public void testCollapseListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Tree.class, CollapseEvent.class, + CollapseListener.class); + } }
\ No newline at end of file diff --git a/tests/server-side/com/vaadin/tests/server/component/upload/UploadListeners.java b/tests/server-side/com/vaadin/tests/server/component/upload/UploadListeners.java index ea5fa94326..c9ce0ac0a2 100644 --- a/tests/server-side/com/vaadin/tests/server/component/upload/UploadListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/upload/UploadListeners.java @@ -1,41 +1,41 @@ -package com.vaadin.tests.server.component.upload;
-
-import com.vaadin.terminal.StreamVariable.StreamingProgressEvent;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Upload;
-import com.vaadin.ui.Upload.FailedEvent;
-import com.vaadin.ui.Upload.FailedListener;
-import com.vaadin.ui.Upload.FinishedEvent;
-import com.vaadin.ui.Upload.FinishedListener;
-import com.vaadin.ui.Upload.ProgressListener;
-import com.vaadin.ui.Upload.StartedEvent;
-import com.vaadin.ui.Upload.StartedListener;
-import com.vaadin.ui.Upload.SucceededEvent;
-import com.vaadin.ui.Upload.SucceededListener;
-
-public class UploadListeners extends AbstractListenerMethodsTest {
- public void testProgressListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Upload.class, StreamingProgressEvent.class,
- ProgressListener.class);
- }
-
- public void testSucceededListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Upload.class, SucceededEvent.class,
- SucceededListener.class);
- }
-
- public void testStartedListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Upload.class, StartedEvent.class,
- StartedListener.class);
- }
-
- public void testFailedListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Upload.class, FailedEvent.class,
- FailedListener.class);
- }
-
- public void testFinishedListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Upload.class, FinishedEvent.class,
- FinishedListener.class);
- }
-}
+package com.vaadin.tests.server.component.upload; + +import com.vaadin.terminal.StreamVariable.StreamingProgressEvent; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Upload; +import com.vaadin.ui.Upload.FailedEvent; +import com.vaadin.ui.Upload.FailedListener; +import com.vaadin.ui.Upload.FinishedEvent; +import com.vaadin.ui.Upload.FinishedListener; +import com.vaadin.ui.Upload.ProgressListener; +import com.vaadin.ui.Upload.StartedEvent; +import com.vaadin.ui.Upload.StartedListener; +import com.vaadin.ui.Upload.SucceededEvent; +import com.vaadin.ui.Upload.SucceededListener; + +public class UploadListeners extends AbstractListenerMethodsTest { + public void testProgressListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, StreamingProgressEvent.class, + ProgressListener.class); + } + + public void testSucceededListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, SucceededEvent.class, + SucceededListener.class); + } + + public void testStartedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, StartedEvent.class, + StartedListener.class); + } + + public void testFailedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, FailedEvent.class, + FailedListener.class); + } + + public void testFinishedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, FinishedEvent.class, + FinishedListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/urifragmentutility/UriFragmentUtilityListeners.java b/tests/server-side/com/vaadin/tests/server/component/urifragmentutility/UriFragmentUtilityListeners.java index fe400e55b9..70fb68b9ec 100644 --- a/tests/server-side/com/vaadin/tests/server/component/urifragmentutility/UriFragmentUtilityListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/urifragmentutility/UriFragmentUtilityListeners.java @@ -1,13 +1,13 @@ -package com.vaadin.tests.server.component.urifragmentutility;
-
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.UriFragmentUtility;
-import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent;
-import com.vaadin.ui.UriFragmentUtility.FragmentChangedListener;
-
-public class UriFragmentUtilityListeners extends AbstractListenerMethodsTest {
- public void testFragmentChangedListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(UriFragmentUtility.class,
- FragmentChangedEvent.class, FragmentChangedListener.class);
- }
-}
+package com.vaadin.tests.server.component.urifragmentutility; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.UriFragmentUtility; +import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent; +import com.vaadin.ui.UriFragmentUtility.FragmentChangedListener; + +public class UriFragmentUtilityListeners extends AbstractListenerMethodsTest { + public void testFragmentChangedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(UriFragmentUtility.class, + FragmentChangedEvent.class, FragmentChangedListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java b/tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java index afc050b981..50de91e2af 100644 --- a/tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java +++ b/tests/server-side/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java @@ -1,83 +1,83 @@ -package com.vaadin.tests.server.component.window;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-import com.vaadin.Application;
-import com.vaadin.ui.Window;
-
-public class AddRemoveSubWindow {
-
- public class TestApp extends Application {
-
- @Override
- public void init() {
- Window w = new Window("Main window");
- setMainWindow(w);
- }
- }
-
- @Test
- public void addSubWindow() {
- TestApp app = new TestApp();
- app.init();
- Window subWindow = new Window("Sub window");
- Window mainWindow = app.getMainWindow();
-
- mainWindow.addWindow(subWindow);
- // Added to main window so the parent of the sub window should be the
- // main window
- assertEquals(subWindow.getParent(), mainWindow);
-
- try {
- mainWindow.addWindow(subWindow);
- assertTrue("Window.addWindow did not throw the expected exception",
- false);
- } catch (IllegalArgumentException e) {
- // Should throw an exception as it has already been added to the
- // main window
- }
-
- // Try to add the same sub window to another window
- try {
- Window w = new Window();
- w.addWindow(subWindow);
- assertTrue("Window.addWindow did not throw the expected exception",
- false);
- } catch (IllegalArgumentException e) {
- // Should throw an exception as it has already been added to the
- // main window
- }
-
- }
-
- @Test
- public void removeSubWindow() {
- TestApp app = new TestApp();
- app.init();
- Window subWindow = new Window("Sub window");
- Window mainWindow = app.getMainWindow();
- mainWindow.addWindow(subWindow);
-
- // Added to main window so the parent of the sub window should be the
- // main window
- assertEquals(subWindow.getParent(), mainWindow);
-
- // Remove from the wrong window, should result in an exception
- boolean removed = subWindow.removeWindow(subWindow);
- assertFalse("Window was removed even though it should not have been",
- removed);
-
- // Parent should still be set
- assertEquals(subWindow.getParent(), mainWindow);
-
- // Remove from the main window and assert it has been removed
- removed = mainWindow.removeWindow(subWindow);
- assertTrue("Window was not removed correctly", removed);
- assertNull(subWindow.getParent());
- }
-}
+package com.vaadin.tests.server.component.window; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.vaadin.Application; +import com.vaadin.ui.Window; + +public class AddRemoveSubWindow { + + public class TestApp extends Application { + + @Override + public void init() { + Window w = new Window("Main window"); + setMainWindow(w); + } + } + + @Test + public void addSubWindow() { + TestApp app = new TestApp(); + app.init(); + Window subWindow = new Window("Sub window"); + Window mainWindow = app.getMainWindow(); + + mainWindow.addWindow(subWindow); + // Added to main window so the parent of the sub window should be the + // main window + assertEquals(subWindow.getParent(), mainWindow); + + try { + mainWindow.addWindow(subWindow); + assertTrue("Window.addWindow did not throw the expected exception", + false); + } catch (IllegalArgumentException e) { + // Should throw an exception as it has already been added to the + // main window + } + + // Try to add the same sub window to another window + try { + Window w = new Window(); + w.addWindow(subWindow); + assertTrue("Window.addWindow did not throw the expected exception", + false); + } catch (IllegalArgumentException e) { + // Should throw an exception as it has already been added to the + // main window + } + + } + + @Test + public void removeSubWindow() { + TestApp app = new TestApp(); + app.init(); + Window subWindow = new Window("Sub window"); + Window mainWindow = app.getMainWindow(); + mainWindow.addWindow(subWindow); + + // Added to main window so the parent of the sub window should be the + // main window + assertEquals(subWindow.getParent(), mainWindow); + + // Remove from the wrong window, should result in an exception + boolean removed = subWindow.removeWindow(subWindow); + assertFalse("Window was removed even though it should not have been", + removed); + + // Parent should still be set + assertEquals(subWindow.getParent(), mainWindow); + + // Remove from the main window and assert it has been removed + removed = mainWindow.removeWindow(subWindow); + assertTrue("Window was not removed correctly", removed); + assertNull(subWindow.getParent()); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java b/tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java index 8daee1ba65..5fabe40bb7 100644 --- a/tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java +++ b/tests/server-side/com/vaadin/tests/server/component/window/AttachDetachWindow.java @@ -1,179 +1,179 @@ -package com.vaadin.tests.server.component.window;
-
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-
-import com.vaadin.Application;
-import com.vaadin.ui.Component;
-import com.vaadin.ui.Label;
-import com.vaadin.ui.VerticalLayout;
-import com.vaadin.ui.Window;
-
-import org.junit.Test;
-
-public class AttachDetachWindow {
-
- private Application testApp = new Application() {
- @Override
- public void init() {
- }
- };
-
- private class TestWindow extends Window {
- boolean windowAttachCalled = false;
- boolean contentAttachCalled = false;
- boolean childAttachCalled = false;
- boolean windowDetachCalled = false;
- boolean contentDetachCalled = false;
- boolean childDetachCalled = false;
-
- TestWindow() {
- setContent(new VerticalLayout() {
- @Override
- public void attach() {
- super.attach();
- contentAttachCalled = true;
- }
-
- @Override
- public void detach() {
- super.detach();
- contentDetachCalled = true;
- }
- });
- addComponent(new Label() {
- @Override
- public void attach() {
- super.attach();
- childAttachCalled = true;
- }
-
- @Override
- public void detach() {
- super.detach();
- childDetachCalled = true;
- }
- });
- }
-
- Component getChild() {
- return getComponentIterator().next();
- }
-
- @Override
- public void attach() {
- super.attach();
- windowAttachCalled = true;
- }
-
- @Override
- public void detach() {
- super.detach();
- windowDetachCalled = true;
- }
- }
-
- TestWindow main = new TestWindow();
- TestWindow sub = new TestWindow();
-
- @Test
- public void addSubWindowBeforeAttachingMainWindow() {
- assertUnattached(main);
- assertUnattached(sub);
-
- main.addWindow(sub);
- assertUnattached(main);
- assertUnattached(sub);
-
- // attaching main should recurse to sub
- testApp.setMainWindow(main);
- assertAttached(main);
- assertAttached(sub);
- }
-
- @Test
- public void addSubWindowAfterAttachingMainWindow() {
- assertUnattached(main);
- assertUnattached(sub);
-
- testApp.setMainWindow(main);
- assertAttached(main);
- assertUnattached(sub);
-
- // main is already attached, so attach should be called for sub
- main.addWindow(sub);
- assertAttached(main);
- assertAttached(sub);
- }
-
- @Test
- public void removeSubWindowBeforeDetachingMainWindow() {
- testApp.addWindow(main);
- main.addWindow(sub);
-
- // sub should be detached when removing from attached main
- main.removeWindow(sub);
- assertAttached(main);
- assertDetached(sub);
-
- // main detach should recurse to sub
- testApp.removeWindow(main);
- assertDetached(main);
- assertDetached(sub);
- }
-
- @Test
- public void removeSubWindowAfterDetachingMainWindow() {
- testApp.addWindow(main);
- main.addWindow(sub);
-
- // main detach should recurse to sub
- testApp.removeWindow(main);
- assertDetached(main);
- assertDetached(sub);
-
- main.removeWindow(sub);
- assertDetached(main);
- assertDetached(sub);
- }
-
- /**
- * Asserts that win and its children are attached to testApp and their
- * attach() methods have been called.
- */
- private void assertAttached(TestWindow win) {
- assertTrue("window attach not called", win.windowAttachCalled);
- assertTrue("window content attach not called", win.contentAttachCalled);
- assertTrue("window child attach not called", win.childAttachCalled);
-
- assertSame("window not attached", win.getApplication(), testApp);
- assertSame("window content not attached", win.getContent()
- .getApplication(), testApp);
- assertSame("window children not attached", win.getChild()
- .getApplication(), testApp);
- }
-
- /**
- * Asserts that win and its children are not attached.
- */
- private void assertUnattached(TestWindow win) {
- assertSame("window not detached", win.getApplication(), null);
- assertSame("window content not detached", win.getContent()
- .getApplication(), null);
- assertSame("window children not detached", win.getChild()
- .getApplication(), null);
- }
-
- /**
- * Asserts that win and its children are unattached and their detach()
- * methods have been been called.
- *
- * @param win
- */
- private void assertDetached(TestWindow win) {
- assertUnattached(win);
- assertTrue("window detach not called", win.windowDetachCalled);
- assertTrue("window content detach not called", win.contentDetachCalled);
- assertTrue("window child detach not called", win.childDetachCalled);
- }
-}
+package com.vaadin.tests.server.component.window; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import com.vaadin.Application; +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; + +import org.junit.Test; + +public class AttachDetachWindow { + + private Application testApp = new Application() { + @Override + public void init() { + } + }; + + private class TestWindow extends Window { + boolean windowAttachCalled = false; + boolean contentAttachCalled = false; + boolean childAttachCalled = false; + boolean windowDetachCalled = false; + boolean contentDetachCalled = false; + boolean childDetachCalled = false; + + TestWindow() { + setContent(new VerticalLayout() { + @Override + public void attach() { + super.attach(); + contentAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + contentDetachCalled = true; + } + }); + addComponent(new Label() { + @Override + public void attach() { + super.attach(); + childAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + childDetachCalled = true; + } + }); + } + + Component getChild() { + return getComponentIterator().next(); + } + + @Override + public void attach() { + super.attach(); + windowAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + windowDetachCalled = true; + } + } + + TestWindow main = new TestWindow(); + TestWindow sub = new TestWindow(); + + @Test + public void addSubWindowBeforeAttachingMainWindow() { + assertUnattached(main); + assertUnattached(sub); + + main.addWindow(sub); + assertUnattached(main); + assertUnattached(sub); + + // attaching main should recurse to sub + testApp.setMainWindow(main); + assertAttached(main); + assertAttached(sub); + } + + @Test + public void addSubWindowAfterAttachingMainWindow() { + assertUnattached(main); + assertUnattached(sub); + + testApp.setMainWindow(main); + assertAttached(main); + assertUnattached(sub); + + // main is already attached, so attach should be called for sub + main.addWindow(sub); + assertAttached(main); + assertAttached(sub); + } + + @Test + public void removeSubWindowBeforeDetachingMainWindow() { + testApp.addWindow(main); + main.addWindow(sub); + + // sub should be detached when removing from attached main + main.removeWindow(sub); + assertAttached(main); + assertDetached(sub); + + // main detach should recurse to sub + testApp.removeWindow(main); + assertDetached(main); + assertDetached(sub); + } + + @Test + public void removeSubWindowAfterDetachingMainWindow() { + testApp.addWindow(main); + main.addWindow(sub); + + // main detach should recurse to sub + testApp.removeWindow(main); + assertDetached(main); + assertDetached(sub); + + main.removeWindow(sub); + assertDetached(main); + assertDetached(sub); + } + + /** + * Asserts that win and its children are attached to testApp and their + * attach() methods have been called. + */ + private void assertAttached(TestWindow win) { + assertTrue("window attach not called", win.windowAttachCalled); + assertTrue("window content attach not called", win.contentAttachCalled); + assertTrue("window child attach not called", win.childAttachCalled); + + assertSame("window not attached", win.getApplication(), testApp); + assertSame("window content not attached", win.getContent() + .getApplication(), testApp); + assertSame("window children not attached", win.getChild() + .getApplication(), testApp); + } + + /** + * Asserts that win and its children are not attached. + */ + private void assertUnattached(TestWindow win) { + assertSame("window not detached", win.getApplication(), null); + assertSame("window content not detached", win.getContent() + .getApplication(), null); + assertSame("window children not detached", win.getChild() + .getApplication(), null); + } + + /** + * Asserts that win and its children are unattached and their detach() + * methods have been been called. + * + * @param win + */ + private void assertDetached(TestWindow win) { + assertUnattached(win); + assertTrue("window detach not called", win.windowDetachCalled); + assertTrue("window content detach not called", win.contentDetachCalled); + assertTrue("window child detach not called", win.childDetachCalled); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/component/window/WindowListeners.java b/tests/server-side/com/vaadin/tests/server/component/window/WindowListeners.java index b8d9579dae..c33871cbd8 100644 --- a/tests/server-side/com/vaadin/tests/server/component/window/WindowListeners.java +++ b/tests/server-side/com/vaadin/tests/server/component/window/WindowListeners.java @@ -1,34 +1,34 @@ -package com.vaadin.tests.server.component.window;
-
-import com.vaadin.event.FieldEvents.BlurEvent;
-import com.vaadin.event.FieldEvents.BlurListener;
-import com.vaadin.event.FieldEvents.FocusEvent;
-import com.vaadin.event.FieldEvents.FocusListener;
-import com.vaadin.tests.server.component.AbstractListenerMethodsTest;
-import com.vaadin.ui.Window;
-import com.vaadin.ui.Window.CloseEvent;
-import com.vaadin.ui.Window.CloseListener;
-import com.vaadin.ui.Window.ResizeEvent;
-import com.vaadin.ui.Window.ResizeListener;
-
-public class WindowListeners extends AbstractListenerMethodsTest {
- public void testFocusListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Window.class, FocusEvent.class,
- FocusListener.class);
- }
-
- public void testBlurListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Window.class, BlurEvent.class,
- BlurListener.class);
- }
-
- public void testResizeListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Window.class, ResizeEvent.class,
- ResizeListener.class);
- }
-
- public void testCloseListenerAddGetRemove() throws Exception {
- testListenerAddGetRemove(Window.class, CloseEvent.class,
- CloseListener.class);
- }
-}
+package com.vaadin.tests.server.component.window; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTest; +import com.vaadin.ui.Window; +import com.vaadin.ui.Window.CloseEvent; +import com.vaadin.ui.Window.CloseListener; +import com.vaadin.ui.Window.ResizeEvent; +import com.vaadin.ui.Window.ResizeListener; + +public class WindowListeners extends AbstractListenerMethodsTest { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, BlurEvent.class, + BlurListener.class); + } + + public void testResizeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, ResizeEvent.class, + ResizeListener.class); + } + + public void testCloseListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, CloseEvent.class, + CloseListener.class); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java b/tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java index 3aebd5bf9d..fcea309e84 100644 --- a/tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java +++ b/tests/server-side/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java @@ -1,169 +1,169 @@ -package com.vaadin.tests.server.components;
-
-import junit.framework.TestCase;
-
-import org.easymock.EasyMock;
-
-import com.vaadin.data.Property.ValueChangeEvent;
-import com.vaadin.data.Property.ValueChangeListener;
-import com.vaadin.data.Property.ValueChangeNotifier;
-import com.vaadin.data.util.ObjectProperty;
-import com.vaadin.ui.AbstractField;
-
-/**
- * Base class for tests for checking that value change listeners for fields are
- * not called exactly once when they should be, and not at other times.
- *
- * Does not check all cases (e.g. properties that do not implement
- * {@link ValueChangeNotifier}).
- *
- * Subclasses should implement {@link #setValue()} and call
- * <code>super.setValue(AbstractField)</code>. Also, subclasses should typically
- * override {@link #setValue(AbstractField)} to set the field value via
- * <code>changeVariables()</code>.
- */
-public abstract class AbstractTestFieldValueChange extends TestCase {
-
- private AbstractField field;
- private ValueChangeListener listener;
-
- protected void setUp(AbstractField field) throws Exception {
- this.field = field;
- listener = EasyMock.createStrictMock(ValueChangeListener.class);
-
- }
-
- protected ValueChangeListener getListener() {
- return listener;
- }
-
- /**
- * Test that listeners are not called when they have been unregistered.
- */
- public void testRemoveListener() {
- getField().setPropertyDataSource(new ObjectProperty<String>(""));
- getField().setWriteThrough(true);
- getField().setReadThrough(true);
-
- // Expectations and start test
- listener.valueChange(EasyMock.isA(ValueChangeEvent.class));
- EasyMock.replay(listener);
-
- // Add listener and set the value -> should end up in listener once
- getField().addListener(listener);
- setValue(getField());
-
- // Ensure listener was called once
- EasyMock.verify(listener);
-
- // Remove the listener and set the value -> should not end up in
- // listener
- getField().removeListener(listener);
- setValue(getField());
-
- // Ensure listener still has been called only once
- EasyMock.verify(listener);
- }
-
- /**
- * Common unbuffered case: both writeThrough (auto-commit) and readThrough
- * are on. Calling commit() should not cause notifications.
- *
- * Using the readThrough mode allows changes made to the property value to
- * be seen in some cases also when there is no notification of value change
- * from the property.
- *
- * Field value change notifications closely mirror value changes of the data
- * source behind the field.
- */
- public void testWriteThroughReadThrough() {
- getField().setPropertyDataSource(new ObjectProperty<String>(""));
- getField().setWriteThrough(true);
- getField().setReadThrough(true);
-
- expectValueChangeFromSetValueNotCommit();
- }
-
- /**
- * Fully buffered use where the data source is neither read nor modified
- * during editing, and is updated at commit().
- *
- * Field value change notifications reflect the buffered value in the field,
- * not the original data source value changes.
- */
- public void testNoWriteThroughNoReadThrough() {
- getField().setPropertyDataSource(new ObjectProperty<String>(""));
- getField().setWriteThrough(false);
- getField().setReadThrough(false);
-
- expectValueChangeFromSetValueNotCommit();
- }
-
- /**
- * Less common partly buffered case: writeThrough (auto-commit) is on and
- * readThrough is off. Calling commit() should not cause notifications.
- *
- * Without readThrough activated, changes to the data source that do not
- * cause notifications are not reflected by the field value.
- *
- * Field value change notifications correspond to changes made to the data
- * source value through the text field or the (notifying) property.
- */
- public void testWriteThroughNoReadThrough() {
- getField().setPropertyDataSource(new ObjectProperty<String>(""));
- getField().setWriteThrough(true);
- getField().setReadThrough(false);
-
- expectValueChangeFromSetValueNotCommit();
- }
-
- /**
- * Partly buffered use where the data source is read but not nor modified
- * during editing, and is updated at commit().
- *
- * When used like this, a field is updated from the data source if necessary
- * when its value is requested and the property value has changed but the
- * field has not been modified in its buffer.
- *
- * Field value change notifications reflect the buffered value in the field,
- * not the original data source value changes.
- */
- public void testNoWriteThroughReadThrough() {
- getField().setPropertyDataSource(new ObjectProperty<String>(""));
- getField().setWriteThrough(false);
- getField().setReadThrough(true);
-
- expectValueChangeFromSetValueNotCommit();
- }
-
- protected void expectValueChangeFromSetValueNotCommit() {
- // Expectations and start test
- listener.valueChange(EasyMock.isA(ValueChangeEvent.class));
- EasyMock.replay(listener);
-
- // Add listener and set the value -> should end up in listener once
- getField().addListener(listener);
- setValue(getField());
-
- // Ensure listener was called once
- EasyMock.verify(listener);
-
- // commit
- getField().commit();
-
- // Ensure listener was not called again
- EasyMock.verify(listener);
- }
-
- protected AbstractField getField() {
- return field;
- }
-
- /**
- * Override in subclasses to set value with changeVariables().
- */
- protected void setValue(AbstractField field) {
- field.setValue("newValue");
- }
-
-}
+package com.vaadin.tests.server.components; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.Property.ValueChangeNotifier; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.ui.AbstractField; + +/** + * Base class for tests for checking that value change listeners for fields are + * not called exactly once when they should be, and not at other times. + * + * Does not check all cases (e.g. properties that do not implement + * {@link ValueChangeNotifier}). + * + * Subclasses should implement {@link #setValue()} and call + * <code>super.setValue(AbstractField)</code>. Also, subclasses should typically + * override {@link #setValue(AbstractField)} to set the field value via + * <code>changeVariables()</code>. + */ +public abstract class AbstractTestFieldValueChange extends TestCase { + + private AbstractField field; + private ValueChangeListener listener; + + protected void setUp(AbstractField field) throws Exception { + this.field = field; + listener = EasyMock.createStrictMock(ValueChangeListener.class); + + } + + protected ValueChangeListener getListener() { + return listener; + } + + /** + * Test that listeners are not called when they have been unregistered. + */ + public void testRemoveListener() { + getField().setPropertyDataSource(new ObjectProperty<String>("")); + getField().setWriteThrough(true); + getField().setReadThrough(true); + + // Expectations and start test + listener.valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(listener); + + // Add listener and set the value -> should end up in listener once + getField().addListener(listener); + setValue(getField()); + + // Ensure listener was called once + EasyMock.verify(listener); + + // Remove the listener and set the value -> should not end up in + // listener + getField().removeListener(listener); + setValue(getField()); + + // Ensure listener still has been called only once + EasyMock.verify(listener); + } + + /** + * Common unbuffered case: both writeThrough (auto-commit) and readThrough + * are on. Calling commit() should not cause notifications. + * + * Using the readThrough mode allows changes made to the property value to + * be seen in some cases also when there is no notification of value change + * from the property. + * + * Field value change notifications closely mirror value changes of the data + * source behind the field. + */ + public void testWriteThroughReadThrough() { + getField().setPropertyDataSource(new ObjectProperty<String>("")); + getField().setWriteThrough(true); + getField().setReadThrough(true); + + expectValueChangeFromSetValueNotCommit(); + } + + /** + * Fully buffered use where the data source is neither read nor modified + * during editing, and is updated at commit(). + * + * Field value change notifications reflect the buffered value in the field, + * not the original data source value changes. + */ + public void testNoWriteThroughNoReadThrough() { + getField().setPropertyDataSource(new ObjectProperty<String>("")); + getField().setWriteThrough(false); + getField().setReadThrough(false); + + expectValueChangeFromSetValueNotCommit(); + } + + /** + * Less common partly buffered case: writeThrough (auto-commit) is on and + * readThrough is off. Calling commit() should not cause notifications. + * + * Without readThrough activated, changes to the data source that do not + * cause notifications are not reflected by the field value. + * + * Field value change notifications correspond to changes made to the data + * source value through the text field or the (notifying) property. + */ + public void testWriteThroughNoReadThrough() { + getField().setPropertyDataSource(new ObjectProperty<String>("")); + getField().setWriteThrough(true); + getField().setReadThrough(false); + + expectValueChangeFromSetValueNotCommit(); + } + + /** + * Partly buffered use where the data source is read but not nor modified + * during editing, and is updated at commit(). + * + * When used like this, a field is updated from the data source if necessary + * when its value is requested and the property value has changed but the + * field has not been modified in its buffer. + * + * Field value change notifications reflect the buffered value in the field, + * not the original data source value changes. + */ + public void testNoWriteThroughReadThrough() { + getField().setPropertyDataSource(new ObjectProperty<String>("")); + getField().setWriteThrough(false); + getField().setReadThrough(true); + + expectValueChangeFromSetValueNotCommit(); + } + + protected void expectValueChangeFromSetValueNotCommit() { + // Expectations and start test + listener.valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(listener); + + // Add listener and set the value -> should end up in listener once + getField().addListener(listener); + setValue(getField()); + + // Ensure listener was called once + EasyMock.verify(listener); + + // commit + getField().commit(); + + // Ensure listener was not called again + EasyMock.verify(listener); + } + + protected AbstractField getField() { + return field; + } + + /** + * Override in subclasses to set value with changeVariables(). + */ + protected void setValue(AbstractField field) { + field.setValue("newValue"); + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java b/tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java index cb73199fb8..3fbe1406f2 100644 --- a/tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java +++ b/tests/server-side/com/vaadin/tests/server/components/TestComboBoxValueChange.java @@ -1,30 +1,30 @@ -package com.vaadin.tests.server.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.vaadin.ui.AbstractField;
-import com.vaadin.ui.ComboBox;
-
-/**
- * Check that the value change listener for a combo box is triggered exactly
- * once when setting the value, at the correct time.
- *
- * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>.
- */
-public class TestComboBoxValueChange extends AbstractTestFieldValueChange {
- @Override
- protected void setUp() throws Exception {
- ComboBox combo = new ComboBox();
- combo.addItem("myvalue");
- super.setUp(combo);
- }
-
- @Override
- protected void setValue(AbstractField field) {
- Map<String, Object> variables = new HashMap<String, Object>();
- variables.put("selected", new String[] { "myvalue" });
- field.changeVariables(field, variables);
- }
-
-}
+package com.vaadin.tests.server.components; + +import java.util.HashMap; +import java.util.Map; + +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.ComboBox; + +/** + * Check that the value change listener for a combo box is triggered exactly + * once when setting the value, at the correct time. + * + * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>. + */ +public class TestComboBoxValueChange extends AbstractTestFieldValueChange { + @Override + protected void setUp() throws Exception { + ComboBox combo = new ComboBox(); + combo.addItem("myvalue"); + super.setUp(combo); + } + + @Override + protected void setValue(AbstractField field) { + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("selected", new String[] { "myvalue" }); + field.changeVariables(field, variables); + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java b/tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java index 1144caf805..2c911d5f3f 100644 --- a/tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java +++ b/tests/server-side/com/vaadin/tests/server/components/TestTextFieldValueChange.java @@ -1,180 +1,180 @@ -package com.vaadin.tests.server.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import junit.framework.Assert;
-
-import org.easymock.EasyMock;
-
-import com.vaadin.data.Property.ValueChangeEvent;
-import com.vaadin.data.util.ObjectProperty;
-import com.vaadin.ui.AbstractField;
-import com.vaadin.ui.TextField;
-
-/**
- * Check that the value change listener for a text field is triggered exactly
- * once when setting the value, at the correct time.
- *
- * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>.
- */
-public class TestTextFieldValueChange extends AbstractTestFieldValueChange {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp(new TextField());
- }
-
- /**
- * Case where the text field only uses its internal buffer, no external
- * property data source.
- */
- public void testNoDataSource() {
- getField().setPropertyDataSource(null);
-
- expectValueChangeFromSetValueNotCommit();
- }
-
- @Override
- protected void setValue(AbstractField field) {
- Map<String, Object> variables = new HashMap<String, Object>();
- variables.put("text", "newValue");
- field.changeVariables(field, variables);
- }
-
- /**
- * Test that field propagates value change events originating from property,
- * but don't fire value change events twice if value has only changed once.
- *
- *
- * TODO make test field type agnostic (eg. combobox)
- */
- public void testValueChangeEventPropagationWithReadThrough() {
- ObjectProperty<String> property = new ObjectProperty<String>("");
- getField().setPropertyDataSource(property);
-
- // defaults, buffering off
- getField().setWriteThrough(true);
- getField().setReadThrough(true);
-
- // Expectations and start test
- getListener().valueChange(EasyMock.isA(ValueChangeEvent.class));
- EasyMock.replay(getListener());
-
- // Add listener and set the value -> should end up in listener once
- getField().addListener(getListener());
-
- property.setValue("Foo");
-
- // Ensure listener was called once
- EasyMock.verify(getListener());
-
- // get value should not fire value change again
- Object value = getField().getValue();
- Assert.assertEquals("Foo", value);
-
- // Ensure listener still has been called only once
- EasyMock.verify(getListener());
- }
-
- /**
- * If read through is on and value has been modified, but not committed, the
- * value should not propagate similar to
- * {@link #testValueChangeEventPropagationWithReadThrough()}
- *
- * TODO make test field type agnostic (eg. combobox)
- */
- public void testValueChangePropagationWithReadThroughWithModifiedValue() {
- final String initialValue = "initial";
- ObjectProperty<String> property = new ObjectProperty<String>(
- initialValue);
- getField().setPropertyDataSource(property);
-
- // write buffering on, read buffering off
- getField().setWriteThrough(false);
- getField().setReadThrough(true);
-
- // Expect no value changes calls to listener
- EasyMock.replay(getListener());
-
- // first set the value (note, write through false -> not forwarded to
- // property)
- setValue(getField());
-
- Assert.assertTrue(getField().isModified());
-
- // Add listener and set the value -> should end up in listener once
- getField().addListener(getListener());
-
- // modify property value, should not fire value change in field as the
- // field has uncommitted value (aka isModified() == true)
- property.setValue("Foo");
-
- // Ensure listener was called once
- EasyMock.verify(getListener());
-
- // get value should not fire value change again
- Object value = getField().getValue();
- // Ensure listener still has been called only once
- EasyMock.verify(getListener());
-
- // field value should be different from the original value and current
- // proeprty value
- boolean isValueEqualToInitial = value.equals(initialValue);
- Assert.assertFalse(isValueEqualToInitial);
- boolean isValueEqualToPropertyValue = value.equals(property.getValue());
- Assert.assertFalse(isValueEqualToPropertyValue);
-
- // Ensure listener has not been called
- EasyMock.verify(getListener());
-
- }
-
- /**
- * Value change events from property should not propagate if read through is
- * false. Execpt when the property is being set.
- *
- * TODO make test field type agnostic (eg. combobox)
- */
- public void testValueChangePropagationWithReadThroughOff() {
- final String initialValue = "initial";
- ObjectProperty<String> property = new ObjectProperty<String>(
- initialValue);
-
- // set buffering
- getField().setWriteThrough(false);
- getField().setReadThrough(false);
-
- // Value change should only happen once, when setting the property,
- // further changes via property should not cause value change listener
- // in field to be notified
- getListener().valueChange(EasyMock.isA(ValueChangeEvent.class));
- EasyMock.replay(getListener());
-
- getField().addListener(getListener());
- getField().setPropertyDataSource(property);
-
- // Ensure listener was called once
- EasyMock.verify(getListener());
-
- // modify property value, should not fire value change in field as the
- // read buffering is on (read through == false)
- property.setValue("Foo");
-
- // Ensure listener still has been called only once
- EasyMock.verify(getListener());
-
- // get value should not fire value change again
- Object value = getField().getValue();
-
- // field value should be different from the original value and current
- // proeprty value
- boolean isValueEqualToInitial = value.equals(initialValue);
- Assert.assertTrue(isValueEqualToInitial);
-
- // Ensure listener still has been called only once
- EasyMock.verify(getListener());
-
- }
-
-}
+package com.vaadin.tests.server.components; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.Assert; + +import org.easymock.EasyMock; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.TextField; + +/** + * Check that the value change listener for a text field is triggered exactly + * once when setting the value, at the correct time. + * + * See <a href="http://dev.vaadin.com/ticket/4394">Ticket 4394</a>. + */ +public class TestTextFieldValueChange extends AbstractTestFieldValueChange { + + @Override + protected void setUp() throws Exception { + super.setUp(new TextField()); + } + + /** + * Case where the text field only uses its internal buffer, no external + * property data source. + */ + public void testNoDataSource() { + getField().setPropertyDataSource(null); + + expectValueChangeFromSetValueNotCommit(); + } + + @Override + protected void setValue(AbstractField field) { + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("text", "newValue"); + field.changeVariables(field, variables); + } + + /** + * Test that field propagates value change events originating from property, + * but don't fire value change events twice if value has only changed once. + * + * + * TODO make test field type agnostic (eg. combobox) + */ + public void testValueChangeEventPropagationWithReadThrough() { + ObjectProperty<String> property = new ObjectProperty<String>(""); + getField().setPropertyDataSource(property); + + // defaults, buffering off + getField().setWriteThrough(true); + getField().setReadThrough(true); + + // Expectations and start test + getListener().valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(getListener()); + + // Add listener and set the value -> should end up in listener once + getField().addListener(getListener()); + + property.setValue("Foo"); + + // Ensure listener was called once + EasyMock.verify(getListener()); + + // get value should not fire value change again + Object value = getField().getValue(); + Assert.assertEquals("Foo", value); + + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + } + + /** + * If read through is on and value has been modified, but not committed, the + * value should not propagate similar to + * {@link #testValueChangeEventPropagationWithReadThrough()} + * + * TODO make test field type agnostic (eg. combobox) + */ + public void testValueChangePropagationWithReadThroughWithModifiedValue() { + final String initialValue = "initial"; + ObjectProperty<String> property = new ObjectProperty<String>( + initialValue); + getField().setPropertyDataSource(property); + + // write buffering on, read buffering off + getField().setWriteThrough(false); + getField().setReadThrough(true); + + // Expect no value changes calls to listener + EasyMock.replay(getListener()); + + // first set the value (note, write through false -> not forwarded to + // property) + setValue(getField()); + + Assert.assertTrue(getField().isModified()); + + // Add listener and set the value -> should end up in listener once + getField().addListener(getListener()); + + // modify property value, should not fire value change in field as the + // field has uncommitted value (aka isModified() == true) + property.setValue("Foo"); + + // Ensure listener was called once + EasyMock.verify(getListener()); + + // get value should not fire value change again + Object value = getField().getValue(); + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + + // field value should be different from the original value and current + // proeprty value + boolean isValueEqualToInitial = value.equals(initialValue); + Assert.assertFalse(isValueEqualToInitial); + boolean isValueEqualToPropertyValue = value.equals(property.getValue()); + Assert.assertFalse(isValueEqualToPropertyValue); + + // Ensure listener has not been called + EasyMock.verify(getListener()); + + } + + /** + * Value change events from property should not propagate if read through is + * false. Execpt when the property is being set. + * + * TODO make test field type agnostic (eg. combobox) + */ + public void testValueChangePropagationWithReadThroughOff() { + final String initialValue = "initial"; + ObjectProperty<String> property = new ObjectProperty<String>( + initialValue); + + // set buffering + getField().setWriteThrough(false); + getField().setReadThrough(false); + + // Value change should only happen once, when setting the property, + // further changes via property should not cause value change listener + // in field to be notified + getListener().valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(getListener()); + + getField().addListener(getListener()); + getField().setPropertyDataSource(property); + + // Ensure listener was called once + EasyMock.verify(getListener()); + + // modify property value, should not fire value change in field as the + // read buffering is on (read through == false) + property.setValue("Foo"); + + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + + // get value should not fire value change again + Object value = getField().getValue(); + + // field value should be different from the original value and current + // proeprty value + boolean isValueEqualToInitial = value.equals(initialValue); + Assert.assertTrue(isValueEqualToInitial); + + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + + } + +} diff --git a/tests/server-side/com/vaadin/tests/server/components/TestWindow.java b/tests/server-side/com/vaadin/tests/server/components/TestWindow.java index 05604aba61..89d018c8a5 100644 --- a/tests/server-side/com/vaadin/tests/server/components/TestWindow.java +++ b/tests/server-side/com/vaadin/tests/server/components/TestWindow.java @@ -1,90 +1,90 @@ -package com.vaadin.tests.server.components;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import org.easymock.EasyMock;
-
-import com.vaadin.ui.Window;
-import com.vaadin.ui.Window.CloseEvent;
-import com.vaadin.ui.Window.CloseListener;
-import com.vaadin.ui.Window.ResizeEvent;
-import com.vaadin.ui.Window.ResizeListener;
-
-public class TestWindow extends TestCase {
-
- private Window window;
-
- @Override
- protected void setUp() throws Exception {
- window = new Window();
- }
-
- public void testCloseListener() {
- CloseListener cl = EasyMock.createMock(Window.CloseListener.class);
-
- // Expectations
- cl.windowClose(EasyMock.isA(CloseEvent.class));
-
- // Start actual test
- EasyMock.replay(cl);
-
- // Add listener and send a close event -> should end up in listener once
- window.addListener(cl);
- sendClose(window);
-
- // Ensure listener was called once
- EasyMock.verify(cl);
-
- // Remove the listener and send close event -> should not end up in
- // listener
- window.removeListener(cl);
- sendClose(window);
-
- // Ensure listener still has been called only once
- EasyMock.verify(cl);
-
- }
-
- public void testResizeListener() {
- ResizeListener rl = EasyMock.createMock(Window.ResizeListener.class);
-
- // Expectations
- rl.windowResized(EasyMock.isA(ResizeEvent.class));
-
- // Start actual test
- EasyMock.replay(rl);
-
- // Add listener and send a resize event -> should end up in listener
- // once
- window.addListener(rl);
- sendResize(window);
-
- // Ensure listener was called once
- EasyMock.verify(rl);
-
- // Remove the listener and send close event -> should not end up in
- // listener
- window.removeListener(rl);
- sendResize(window);
-
- // Ensure listener still has been called only once
- EasyMock.verify(rl);
-
- }
-
- private void sendResize(Window window2) {
- Map<String, Object> variables = new HashMap<String, Object>();
- variables.put("height", 1234);
- window.changeVariables(window, variables);
-
- }
-
- private static void sendClose(Window window) {
- Map<String, Object> variables = new HashMap<String, Object>();
- variables.put("close", true);
- window.changeVariables(window, variables);
- }
-}
+package com.vaadin.tests.server.components; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.ui.Window; +import com.vaadin.ui.Window.CloseEvent; +import com.vaadin.ui.Window.CloseListener; +import com.vaadin.ui.Window.ResizeEvent; +import com.vaadin.ui.Window.ResizeListener; + +public class TestWindow extends TestCase { + + private Window window; + + @Override + protected void setUp() throws Exception { + window = new Window(); + } + + public void testCloseListener() { + CloseListener cl = EasyMock.createMock(Window.CloseListener.class); + + // Expectations + cl.windowClose(EasyMock.isA(CloseEvent.class)); + + // Start actual test + EasyMock.replay(cl); + + // Add listener and send a close event -> should end up in listener once + window.addListener(cl); + sendClose(window); + + // Ensure listener was called once + EasyMock.verify(cl); + + // Remove the listener and send close event -> should not end up in + // listener + window.removeListener(cl); + sendClose(window); + + // Ensure listener still has been called only once + EasyMock.verify(cl); + + } + + public void testResizeListener() { + ResizeListener rl = EasyMock.createMock(Window.ResizeListener.class); + + // Expectations + rl.windowResized(EasyMock.isA(ResizeEvent.class)); + + // Start actual test + EasyMock.replay(rl); + + // Add listener and send a resize event -> should end up in listener + // once + window.addListener(rl); + sendResize(window); + + // Ensure listener was called once + EasyMock.verify(rl); + + // Remove the listener and send close event -> should not end up in + // listener + window.removeListener(rl); + sendResize(window); + + // Ensure listener still has been called only once + EasyMock.verify(rl); + + } + + private void sendResize(Window window2) { + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("height", 1234); + window.changeVariables(window, variables); + + } + + private static void sendClose(Window window) { + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("close", true); + window.changeVariables(window, variables); + } +} diff --git a/tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java b/tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java index 6939ce27d2..c4052c2db8 100644 --- a/tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java +++ b/tests/server-side/com/vaadin/tests/server/validation/TestReadOnlyValidation.java @@ -1,17 +1,17 @@ -package com.vaadin.tests.server.validation;
-
-import org.junit.Test;
-
-import com.vaadin.data.validator.IntegerValidator;
-import com.vaadin.ui.TextField;
-
-public class TestReadOnlyValidation {
-
- @Test
- public void testIntegerValidation() {
- TextField field = new TextField();
- field.addValidator(new IntegerValidator("Enter a Valid Number"));
- field.setValue(Integer.valueOf(10));
- field.validate();
- }
-}
+package com.vaadin.tests.server.validation; + +import org.junit.Test; + +import com.vaadin.data.validator.IntegerValidator; +import com.vaadin.ui.TextField; + +public class TestReadOnlyValidation { + + @Test + public void testIntegerValidation() { + TextField field = new TextField(); + field.addValidator(new IntegerValidator("Enter a Valid Number")); + field.setValue(Integer.valueOf(10)); + field.validate(); + } +} |