From c2722bfeb2552158c9717110b35518a07e13ab85 Mon Sep 17 00:00:00 2001 From: Artur Signell Date: Fri, 27 Jan 2012 14:08:53 +0000 Subject: #8311 Converted CRLF to LF in all source files svn changeset:22797/svn branch:6.7 --- .../ApplicationConnectionTestURLGeneration.java | 154 +- .../client/TestVBrowserDetailsUserAgentParser.java | 738 ++--- .../vaadin/data/util/AbstractContainerTest.java | 1340 ++++----- .../util/AbstractHierarchicalContainerTest.java | 512 ++-- .../com/vaadin/data/util/ObjectPropertyTest.java | 198 +- .../util/TestContainerHierarchicalWrapper.java | 90 +- .../com/vaadin/data/util/TestContainerSorting.java | 476 +-- .../data/util/TestHierarchicalContainer.java | 538 ++-- .../com/vaadin/data/util/TestIndexedContainer.java | 542 ++-- .../sqlcontainer/SQLContainerTableQueryTest.java | 3038 ++++++++++---------- .../sqlcontainer/generator/SQLGeneratorsTest.java | 482 ++-- .../util/sqlcontainer/query/TableQueryTest.java | 1324 ++++----- .../tests/server/IndexedContainerListeners.java | 40 +- .../tests/server/PropertysetItemListeners.java | 26 +- .../server/TestAbstractBeanContainerListeners.java | 30 +- .../server/TestAbstractContainerListeners.java | 42 +- .../TestAbstractInMemoryContainerListeners.java | 26 +- .../server/TestAbstractPropertyListeners.java | 48 +- .../tests/server/TestClassesSerializable.java | 524 ++-- .../com/vaadin/tests/server/TestKeyMapper.java | 204 +- .../server/TransactionListenersConcurrency.java | 370 +-- .../absolutelayout/AbsoluteLayoutListeners.java | 26 +- .../absolutelayout/ComponentPosition.java | 410 +-- .../TestAbstractComponentContainerListeners.java | 42 +- .../abstractfield/TestAbstractFieldListeners.java | 40 +- .../abstractorderedlayout/AddComponentsTest.java | 230 +- .../TestAbstractOrderedLayoutListeners.java | 26 +- .../TestAbstractSelectListeners.java | 40 +- .../TestAbstractSplitPanelListeners.java | 26 +- .../TestAbstractTextFieldListeners.java | 54 +- .../server/component/button/ButtonListeners.java | 54 +- .../component/csslayout/AddComponentsTest.java | 218 +- .../component/csslayout/CssLayoutListeners.java | 24 +- .../component/datefield/DateFieldListeners.java | 40 +- .../component/datefield/WeekNumberCalculation.java | 222 +- .../component/embedded/EmbeddedListeners.java | 26 +- .../component/gridlayout/GridLayoutListeners.java | 26 +- .../server/component/label/LabelListeners.java | 26 +- .../component/loginform/LoginFormListeners.java | 26 +- .../tests/server/component/menubar/MenuBarIds.java | 194 +- .../optiongroup/OptionGroupListeners.java | 40 +- .../component/orderedlayout/TestOrderedLayout.java | 98 +- .../server/component/panel/PanelListeners.java | 26 +- .../component/popupview/PopupViewListeners.java | 28 +- .../server/component/select/SelectListeners.java | 38 +- .../server/component/table/TableListeners.java | 78 +- .../component/tabsheet/TabSheetListeners.java | 26 +- .../server/component/tabsheet/TestTabSheet.java | 248 +- .../tests/server/component/tree/TestListeners.java | 270 +- .../tests/server/component/tree/TreeListeners.java | 52 +- .../server/component/upload/UploadListeners.java | 82 +- .../UriFragmentUtilityListeners.java | 26 +- .../component/window/AddRemoveSubWindow.java | 166 +- .../component/window/AttachDetachWindow.java | 358 +-- .../server/component/window/WindowListeners.java | 68 +- .../components/AbstractTestFieldValueChange.java | 338 +-- .../server/components/TestComboBoxValueChange.java | 60 +- .../components/TestTextFieldValueChange.java | 360 +-- .../vaadin/tests/server/components/TestWindow.java | 180 +- .../server/validation/TestReadOnlyValidation.java | 34 +- .../vaadin/launcher/DevelopmentServerLauncher.java | 436 +-- .../com/vaadin/launcher/util/BrowserLauncher.java | 254 +- tests/testbench/com/vaadin/tests/Components.java | 536 ++-- .../com/vaadin/tests/StressComponentsInTable.java | 150 +- .../com/vaadin/tests/TableChangingDatasource.java | 106 +- .../com/vaadin/tests/TableSelectTest.java | 246 +- .../vaadin/tests/TestComponentAddAndRecursion.java | 256 +- .../com/vaadin/tests/TestContainerChanges.java | 424 +-- .../testbench/com/vaadin/tests/TestDateField.java | 148 +- .../tests/TestForBasicApplicationLayout.java | 202 +- .../tests/application/ApplicationCloseTest.java | 140 +- .../vaadin/tests/application/WebBrowserTest.java | 196 +- .../tests/applicationcontext/ChangeSessionId.java | 136 +- .../tests/applicationservlet/NoMainWindow.java | 44 +- .../components/AbstractComponentContainerTest.java | 712 ++--- .../tests/components/AbstractComponentTest.java | 1342 ++++----- .../tests/components/AbstractLayoutTest.java | 200 +- .../components/AbstractOrderedLayoutTest.java | 170 +- .../vaadin/tests/components/AbstractTestCase.java | 48 +- .../components/HierarchicalContainerSorting.java | 216 +- .../com/vaadin/tests/components/LongTooltip.java | 98 +- .../com/vaadin/tests/components/TestBase.java | 106 +- ...eComponentsFromAbsoluteLayoutToInnerLayout.java | 116 +- .../components/abstractcomponent/EnableState.java | 154 +- .../AbstractFieldDataSourceReadOnly.java | 120 +- .../abstractfield/AbstractFieldTest.java | 468 +-- .../abstractfield/AbstractTextFieldTest.java | 482 ++-- .../abstractfield/ShortcutAddAndRemove.java | 128 +- .../tests/components/accordion/RemoveTabs.java | 254 +- .../components/button/ButtonErrorMessage.java | 62 +- .../components/button/ButtonUndefinedWidth.java | 80 +- .../vaadin/tests/components/button/Buttons2.java | 148 +- .../button/ButtonsInHorizontalLayout.java | 104 +- .../button/TooltipForDisabledButton.java | 96 +- .../tests/components/caption/EmptyCaptions.java | 112 +- .../tests/components/checkbox/CheckBoxes.java | 152 +- .../tests/components/checkbox/CheckBoxes2.java | 112 +- .../checkbox/CheckboxCaptionWrapping.java | 78 +- .../tests/components/checkbox/CheckboxIcon.java | 58 +- .../combobox/ComboBoxDataSourceChange.java | 204 +- .../combobox/ComboBoxEnablesComboBox.java | 98 +- .../combobox/ComboBoxIdenticalItems.java | 108 +- .../combobox/ComboBoxInvalidNullSelection.java | 152 +- .../combobox/ComboBoxTextFieldEventOrder.java | 76 +- .../combobox/ComboBoxUndefinedWidthAndIcon.java | 72 +- .../components/combobox/ComboBoxValueInput.java | 126 +- .../components/combobox/ComboxBoxErrorMessage.java | 52 +- .../components/customcomponent/ClipContent.java | 112 +- .../customcomponent/CustomComponentSizeUpdate.java | 88 +- .../components/datefield/CustomDateFormats.java | 412 +-- .../components/datefield/DateFieldEmptyValid.java | 288 +- .../components/datefield/DateFieldLocale.java | 94 +- .../datefield/DateFieldPopupOffScreen.java | 124 +- .../components/datefield/DateFieldReadOnly.java | 106 +- .../tests/components/datefield/DateFieldTest.java | 274 +- .../datefield/DateFieldUnparsableDate.java | 202 +- .../components/datefield/DatePopupStyleName.java | 66 +- .../datefield/DisabledDateFieldWidth.java | 84 +- .../components/datefield/InlineDateFieldTest.java | 24 +- .../components/datefield/InlineDateFields.java | 212 +- .../datefield/NarrowPopupDateFieldInTable.java | 66 +- .../components/datefield/PopupDateFieldTest.java | 76 +- .../components/datefield/PopupDateFields.java | 210 +- .../datefield/ShowSelectedDateAfterInvalid.java | 114 +- .../WidthRecalculationOnEnableStateChange.java | 88 +- .../tests/components/embedded/EmbeddedFlash.java | 68 +- .../tests/components/embedded/EmbeddedPdf.java | 64 +- .../tests/components/embedded/EmbeddedTooltip.java | 54 +- .../tests/components/form/FormFieldCaptions.java | 172 +- .../components/form/FormRenderingFlicker.java | 130 +- .../components/form/FormWithEnterShortCut.java | 94 +- .../form/FormWithPropertyFormatterConnected.java | 180 +- .../formlayout/FormLayoutReplaceComponent.java | 112 +- .../TableInFormLayoutCausesScrolling.java | 88 +- .../MoveComponentsFromGridLayoutToInnerLayout.java | 116 +- .../label/HundredPercentWideLabelResize.java | 84 +- .../vaadin/tests/components/label/LabelTest.java | 200 +- .../tests/components/label/LabelTooltip.java | 106 +- .../tests/components/label/LabelWrapping.java | 92 +- .../com/vaadin/tests/components/link/LinkIcon.java | 60 +- .../tests/components/link/LinkTargetSize.java | 60 +- .../tests/components/listselect/ListSelects.java | 88 +- .../components/menubar/HiddenAndDisabledMenus.java | 68 +- .../components/menubar/MenuBarNavigation.java | 124 +- .../menubar/MenuBarRunsOutOfBrowser.java | 84 +- .../tests/components/menubar/MenuBarTest.java | 676 ++--- .../vaadin/tests/components/menubar/Menubars.java | 176 +- .../components/nativebutton/NativeButtonTest.java | 24 +- .../components/nativeselect/NativeSelects.java | 84 +- .../components/notification/Notifications.java | 116 +- .../notification/NotificationsHtmlAllowed.java | 152 +- .../tests/components/optiongroup/OptionGroups.java | 134 +- .../orderedlayout/HorizontalLayoutTest.java | 26 +- .../orderedlayout/ReplaceComponentNPE.java | 80 +- .../orderedlayout/VerticalLayoutTest.java | 28 +- .../passwordfield/PasswordFieldTest.java | 40 +- .../popupview/PopupViewLabelResized.java | 74 +- .../components/popupview/PopupViewNullValues.java | 206 +- .../components/popupview/PopupViewWithRTE.java | 100 +- .../ProgressIndicatorInvisible.java | 104 +- .../components/richtextarea/RichTextAreaTest.java | 108 +- .../components/select/AbstractSelectTestCase.java | 480 ++-- .../tests/components/select/MultiSelect.java | 64 +- .../components/select/NullSelectionItemId.java | 154 +- .../components/select/SelectDisplaysOldValue.java | 326 +-- .../vaadin/tests/components/select/SelectTest.java | 26 +- .../select/TwinColSelectCaptionStyles.java | 84 +- .../tests/components/select/TwinColSelectTest.java | 130 +- .../tests/components/select/TwinColSelects.java | 96 +- .../vaadin/tests/components/slider/SliderTest.java | 148 +- .../splitpanel/AbstractSplitPanelTest.java | 254 +- .../splitpanel/HorizontalSplitPanels.java | 26 +- .../splitpanel/SplitPanelExtraScrollbars.java | 136 +- .../splitpanel/SplitPanelWidthOnResize.java | 86 +- .../tests/components/splitpanel/SplitPanels.java | 74 +- .../components/splitpanel/VerticalSplitPanels.java | 26 +- .../components/table/ClippedComponentsInTable.java | 80 +- .../table/ColumnCollapsingAndColumnExpansion.java | 182 +- .../table/ColumnExpandWithFixedColumns.java | 90 +- .../tests/components/table/EditableModeChange.java | 196 +- .../tests/components/table/EditableTableFocus.java | 68 +- .../tests/components/table/FixedHeightTable.java | 76 +- .../components/table/ModifyContainerProperty.java | 120 +- .../table/NotselectablePaintSelections.java | 110 +- .../tests/components/table/RowAdditionTest.java | 118 +- .../components/table/ScrollCausesRequestLoop.java | 130 +- .../table/TableAndBrowserContextMenu.java | 298 +- .../table/TableClickValueChangeInteraction.java | 170 +- .../components/table/TableExtraScrollbars.java | 120 +- .../components/table/TableLastRowMissing.java | 70 +- .../table/TableModifcationsWhenScrolledRight.java | 102 +- .../table/TablePageLengthCalculation.java | 98 +- .../table/TableRepaintWhenMadeVisibile.java | 86 +- .../tests/components/table/TableScrollOnFocus.java | 96 +- .../components/table/TableScrollsOnSelection.java | 72 +- .../components/table/TableSelectPagingOff.java | 138 +- .../tests/components/table/TableSingleSelect.java | 108 +- .../tests/components/table/TableSorting.java | 132 +- .../components/table/TableToggleVisibility.java | 336 +-- .../components/table/TableWithManyColumns.java | 84 +- .../com/vaadin/tests/components/table/Tables.java | 1676 +++++------ .../components/table/TestCurrentPageFirstItem.java | 120 +- .../components/table/TextFieldRelativeWidth.java | 258 +- .../tests/components/tabsheet/RemoveTabs.java | 290 +- .../components/tabsheet/TabSheetCaptions.java | 128 +- .../components/tabsheet/TabSheetDisabling.java | 124 +- .../tabsheet/TabSheetDiscardsMovedComponents.java | 104 +- .../tests/components/tabsheet/TabSheetIcons.java | 108 +- .../tests/components/tabsheet/TabSheetMinimal.java | 78 +- .../components/tabsheet/TabSheetTabStyleNames.java | 100 +- .../components/tabsheet/TabSheetTabTheming.java | 52 +- .../tests/components/tabsheet/TabSheetTest.java | 404 +-- .../tests/components/tabsheet/TabsheetNPE.java | 118 +- .../components/tabsheet/TabsheetScrolling.java | 148 +- .../tabsheet/VerticalScrollbarPosition.java | 80 +- .../tabsheet/WrapTabSheetInTabSheet.java | 84 +- .../tests/components/textarea/TextAreaTest.java | 86 +- .../vaadin/tests/components/textarea/Wordwrap.java | 118 +- .../tests/components/textfield/IE6Cursor.java | 56 +- .../textfield/TextFieldInLayoutInTable.java | 68 +- .../tests/components/textfield/TextFieldTest.java | 118 +- .../tests/components/tree/TreeContainerChange.java | 202 +- .../tests/components/tree/TreeFiltering.java | 250 +- .../tests/components/tree/TreeScrolling.java | 108 +- .../com/vaadin/tests/components/tree/Trees.java | 782 ++--- .../treetable/ChangeDataSourcePageLengthZero.java | 178 +- .../components/treetable/DynamicallyModified.java | 248 +- .../treetable/TreeTableCacheOnPartialUpdates.java | 474 +-- .../tests/components/treetable/TreeTableTest.java | 600 ++-- .../components/twincolselect/TwinColSelects.java | 128 +- .../tests/components/upload/ForceSubmit.java | 170 +- .../tests/components/upload/TestFileUpload.java | 116 +- .../upload/TestImmediateUploadInFormLayout.java | 106 +- .../vaadin/tests/components/upload/TestUpload.java | 118 +- .../upload/TestUploadAndDisableOnSuccess.java | 204 +- .../window/AttachShouldBeCalledForSubWindows.java | 258 +- .../tests/components/window/CloseSubWindow.java | 258 +- .../components/window/ExtraLargeSubWindow.java | 64 +- .../tests/components/window/ExtraWindowShown.java | 106 +- .../tests/components/window/FullSizedWindow.java | 62 +- .../components/window/ModalWindowNativeSelect.java | 62 +- .../components/window/SubwindowInvalidLayout.java | 70 +- .../window/WindowScrollingComponentIntoView.java | 274 +- .../tests/components/window/WindowScrollingUp.java | 78 +- .../window/WindowShouldRemoveActionHandler.java | 232 +- .../containers/BeanItemContainerFilteringTest.java | 344 +-- .../containers/IndexedContainerFilteringTest.java | 278 +- .../FileSystemContainerInTreeTable.java | 280 +- .../vaadin/tests/layouts/CaptionsInLayouts.java | 554 ++-- .../tests/layouts/CssLayoutRemoveComponent.java | 84 +- .../CssLayoutRemoveComponentWithCaption.java | 82 +- .../vaadin/tests/layouts/DeepComponentTrees.java | 228 +- .../tests/layouts/GridLayoutMoveComponent.java | 132 +- .../com/vaadin/tests/layouts/GridLayoutNPE.java | 144 +- .../tests/layouts/GridLayoutWidthChange.java | 128 +- .../tests/layouts/HiddenHorizontalLayout.java | 112 +- .../vaadin/tests/layouts/OrderedLayoutBasics.java | 2402 ++++++++-------- .../vaadin/tests/layouts/TestAbsoluteLayout.java | 628 ++-- .../tests/layouts/TestLayoutPerformance.java | 266 +- .../tests/layouts/TreeWithBordersInLayout.java | 84 +- .../VerticalLayoutExpandRatioModification.java | 154 +- .../VerticalLayoutWithRelativeSizeComponents.java | 76 +- ...tWithRelativeSizeComponentsInitiallyHidden.java | 116 +- .../layouts/layouttester/AbstractLayoutTests.java | 60 +- .../layouts/layouttester/GridLayoutTests.java | 1186 ++++---- .../layouttester/HorizontalLayoutTests.java | 1118 +++---- .../layouts/layouttester/VerticalLayoutTests.java | 1178 ++++---- .../tests/resources/NonExistingFileResource.java | 96 +- .../vaadin/tests/resources/ResourceDownload.java | 178 +- .../com/vaadin/tests/tickets/Ticket124.java | 180 +- .../com/vaadin/tests/tickets/Ticket1245.java | 184 +- .../com/vaadin/tests/tickets/Ticket1365.java | 88 +- .../com/vaadin/tests/tickets/Ticket1506_Panel.java | 96 +- .../tests/tickets/Ticket1506_TestContainer.java | 252 +- .../tests/tickets/Ticket1506_TestContainer2.java | 234 +- .../com/vaadin/tests/tickets/Ticket1572.java | 236 +- .../com/vaadin/tests/tickets/Ticket1581.java | 142 +- .../com/vaadin/tests/tickets/Ticket1589.java | 186 +- .../com/vaadin/tests/tickets/Ticket1663.java | 44 +- .../com/vaadin/tests/tickets/Ticket1673.java | 56 +- .../com/vaadin/tests/tickets/Ticket1710.java | 822 +++--- .../com/vaadin/tests/tickets/Ticket1767.java | 60 +- .../com/vaadin/tests/tickets/Ticket1772.java | 74 +- .../com/vaadin/tests/tickets/Ticket1775.java | 96 +- .../com/vaadin/tests/tickets/Ticket1804.java | 300 +- .../com/vaadin/tests/tickets/Ticket1805.java | 114 +- .../com/vaadin/tests/tickets/Ticket1806.java | 88 +- .../com/vaadin/tests/tickets/Ticket1811.java | 156 +- .../com/vaadin/tests/tickets/Ticket1819.java | 128 +- .../tests/tickets/Ticket1834PanelScrolling.java | 176 +- .../com/vaadin/tests/tickets/Ticket1868.java | 38 +- .../com/vaadin/tests/tickets/Ticket1869.java | 110 +- .../com/vaadin/tests/tickets/Ticket1878.java | 768 ++--- .../com/vaadin/tests/tickets/Ticket1919.java | 104 +- .../com/vaadin/tests/tickets/Ticket1923.java | 158 +- .../tests/tickets/Ticket1924ThemeChanging.java | 100 +- .../com/vaadin/tests/tickets/Ticket1925.java | 30 +- .../com/vaadin/tests/tickets/Ticket1966.java | 222 +- .../com/vaadin/tests/tickets/Ticket1966_2.java | 336 +-- .../com/vaadin/tests/tickets/Ticket1966_3.java | 126 +- .../com/vaadin/tests/tickets/Ticket1969.java | 208 +- .../com/vaadin/tests/tickets/Ticket1972.java | 60 +- .../com/vaadin/tests/tickets/Ticket1973.java | 100 +- .../com/vaadin/tests/tickets/Ticket1975.java | 124 +- .../com/vaadin/tests/tickets/Ticket1986.java | 158 +- .../com/vaadin/tests/tickets/Ticket1991.java | 54 +- .../com/vaadin/tests/tickets/Ticket1995.java | 134 +- .../com/vaadin/tests/tickets/Ticket2002.java | 102 +- .../com/vaadin/tests/tickets/Ticket2009.java | 250 +- .../com/vaadin/tests/tickets/Ticket2011.java | 52 +- .../com/vaadin/tests/tickets/Ticket2014.java | 126 +- .../com/vaadin/tests/tickets/Ticket2021.java | 282 +- .../com/vaadin/tests/tickets/Ticket2022.java | 64 +- .../com/vaadin/tests/tickets/Ticket2024.java | 70 +- .../com/vaadin/tests/tickets/Ticket2026.java | 70 +- .../com/vaadin/tests/tickets/Ticket2029.java | 278 +- .../com/vaadin/tests/tickets/Ticket2037.java | 94 +- .../com/vaadin/tests/tickets/Ticket2040.java | 172 +- .../com/vaadin/tests/tickets/Ticket2042.java | 76 +- .../com/vaadin/tests/tickets/Ticket2043.java | 56 +- .../com/vaadin/tests/tickets/Ticket2048.java | 206 +- .../com/vaadin/tests/tickets/Ticket2051.java | 88 +- .../com/vaadin/tests/tickets/Ticket2060.java | 100 +- .../com/vaadin/tests/tickets/Ticket2062.java | 80 +- .../com/vaadin/tests/tickets/Ticket2083.java | 56 +- .../com/vaadin/tests/tickets/Ticket2095.java | 58 +- .../com/vaadin/tests/tickets/Ticket2098.java | 74 +- .../com/vaadin/tests/tickets/Ticket2099.java | 154 +- .../com/vaadin/tests/tickets/Ticket2101.java | 42 +- .../com/vaadin/tests/tickets/Ticket2126.java | 122 +- .../com/vaadin/tests/tickets/Ticket2208.java | 136 +- .../com/vaadin/tests/tickets/Ticket2209.java | 84 +- .../com/vaadin/tests/tickets/Ticket2209OL.java | 98 +- .../com/vaadin/tests/tickets/Ticket2209OL2.java | 110 +- .../com/vaadin/tests/tickets/Ticket2215.java | 58 +- .../com/vaadin/tests/tickets/Ticket2232.java | 148 +- .../com/vaadin/tests/tickets/Ticket2287.java | 62 +- .../com/vaadin/tests/tickets/Ticket2292.java | 174 +- .../com/vaadin/tests/tickets/Ticket2297.java | 80 +- .../com/vaadin/tests/tickets/Ticket2303.java | 86 +- .../com/vaadin/tests/tickets/Ticket2407.java | 42 +- .../com/vaadin/tests/tickets/Ticket2411.java | 58 +- .../com/vaadin/tests/tickets/Ticket2998.java | 664 ++--- .../com/vaadin/tests/tickets/Ticket3146.java | 192 +- .../com/vaadin/tests/tickets/Ticket5053.java | 70 +- .../com/vaadin/tests/tickets/Ticket5157.java | 104 +- .../com/vaadin/tests/tickets/Ticket5952.java | 60 +- .../com/vaadin/tests/tickets/Ticket6002.java | 176 +- .../com/vaadin/tests/tickets/Ticket677.java | 420 +-- tests/testbench/com/vaadin/tests/util/Log.java | 124 +- .../com/vaadin/tests/util/PortableRandom.java | 102 +- .../validation/EmptyFieldErrorIndicators.java | 292 +- .../ValidationOfRequiredEmptyFields.java | 188 +- 353 files changed, 34482 insertions(+), 34482 deletions(-) (limited to 'tests') diff --git a/tests/client-side/com/vaadin/terminal/gwt/client/ApplicationConnectionTestURLGeneration.java b/tests/client-side/com/vaadin/terminal/gwt/client/ApplicationConnectionTestURLGeneration.java index fe3b724aaf..3535d50529 100644 --- a/tests/client-side/com/vaadin/terminal/gwt/client/ApplicationConnectionTestURLGeneration.java +++ b/tests/client-side/com/vaadin/terminal/gwt/client/ApplicationConnectionTestURLGeneration.java @@ -1,77 +1,77 @@ -package com.vaadin.terminal.gwt.client; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.vaadin.terminal.gwt.client.ApplicationConnection; - -public class ApplicationConnectionTestURLGeneration { - - private static final String[] URIS = new String[] { - "http://demo.vaadin.com/", // - "https://demo.vaadin.com/", - "http://demo.vaadin.com/foo", - "http://demo.vaadin.com/foo?f", - "http://demo.vaadin.com/foo?f=1", - "http://demo.vaadin.com:1234/foo?a", - "http://demo.vaadin.com:1234/foo#frag?fakeparam", - // Jetspeed - "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__", - // Liferay generated url - "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1", - - }; - private static final String[] URIS_WITH_ABCD_PARAM = new String[] { - "http://demo.vaadin.com/?a=b&c=d", - "https://demo.vaadin.com/?a=b&c=d", - "http://demo.vaadin.com/foo?a=b&c=d", - "http://demo.vaadin.com/foo?f&a=b&c=d", - "http://demo.vaadin.com/foo?f=1&a=b&c=d", - "http://demo.vaadin.com:1234/foo?a&a=b&c=d", - "http://demo.vaadin.com:1234/foo?a=b&c=d#frag?fakeparam", - "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d", - "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d", - - }; - - private static final String[] URIS_WITH_ABCD_PARAM_AND_FRAGMENT = new String[] { - "http://demo.vaadin.com/?a=b&c=d#fragment", - "https://demo.vaadin.com/?a=b&c=d#fragment", - "http://demo.vaadin.com/foo?a=b&c=d#fragment", - "http://demo.vaadin.com/foo?f&a=b&c=d#fragment", - "http://demo.vaadin.com/foo?f=1&a=b&c=d#fragment", - "http://demo.vaadin.com:1234/foo?a&a=b&c=d#fragment", - "", - "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d#fragment", - "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d#fragment", - - }; - - @Test - public void testParameterAdding() { - for (int i = 0; i < URIS.length; i++) { - // Adding nothing - assertEquals(URIS[i], - ApplicationConnection.addGetParameters(URIS[i], "")); - - // Adding a=b&c=d - assertEquals(URIS_WITH_ABCD_PARAM[i], - ApplicationConnection.addGetParameters(URIS[i], "a=b&c=d")); - - // Fragments - if (URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].length() > 0) { - assertEquals( - URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i], - ApplicationConnection.addGetParameters(URIS[i] - + "#fragment", "a=b&c=d")); - - // Empty fragment - assertEquals(URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].replace( - "#fragment", "#"), - ApplicationConnection.addGetParameters(URIS[i] + "#", - "a=b&c=d")); - } - } - } -} +package com.vaadin.terminal.gwt.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.vaadin.terminal.gwt.client.ApplicationConnection; + +public class ApplicationConnectionTestURLGeneration { + + private static final String[] URIS = new String[] { + "http://demo.vaadin.com/", // + "https://demo.vaadin.com/", + "http://demo.vaadin.com/foo", + "http://demo.vaadin.com/foo?f", + "http://demo.vaadin.com/foo?f=1", + "http://demo.vaadin.com:1234/foo?a", + "http://demo.vaadin.com:1234/foo#frag?fakeparam", + // Jetspeed + "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__", + // Liferay generated url + "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1", + + }; + private static final String[] URIS_WITH_ABCD_PARAM = new String[] { + "http://demo.vaadin.com/?a=b&c=d", + "https://demo.vaadin.com/?a=b&c=d", + "http://demo.vaadin.com/foo?a=b&c=d", + "http://demo.vaadin.com/foo?f&a=b&c=d", + "http://demo.vaadin.com/foo?f=1&a=b&c=d", + "http://demo.vaadin.com:1234/foo?a&a=b&c=d", + "http://demo.vaadin.com:1234/foo?a=b&c=d#frag?fakeparam", + "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d", + "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d", + + }; + + private static final String[] URIS_WITH_ABCD_PARAM_AND_FRAGMENT = new String[] { + "http://demo.vaadin.com/?a=b&c=d#fragment", + "https://demo.vaadin.com/?a=b&c=d#fragment", + "http://demo.vaadin.com/foo?a=b&c=d#fragment", + "http://demo.vaadin.com/foo?f&a=b&c=d#fragment", + "http://demo.vaadin.com/foo?f=1&a=b&c=d#fragment", + "http://demo.vaadin.com:1234/foo?a&a=b&c=d#fragment", + "", + "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d#fragment", + "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d#fragment", + + }; + + @Test + public void testParameterAdding() { + for (int i = 0; i < URIS.length; i++) { + // Adding nothing + assertEquals(URIS[i], + ApplicationConnection.addGetParameters(URIS[i], "")); + + // Adding a=b&c=d + assertEquals(URIS_WITH_ABCD_PARAM[i], + ApplicationConnection.addGetParameters(URIS[i], "a=b&c=d")); + + // Fragments + if (URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].length() > 0) { + assertEquals( + URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i], + ApplicationConnection.addGetParameters(URIS[i] + + "#fragment", "a=b&c=d")); + + // Empty fragment + assertEquals(URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].replace( + "#fragment", "#"), + ApplicationConnection.addGetParameters(URIS[i] + "#", + "a=b&c=d")); + } + } + } +} diff --git a/tests/client-side/com/vaadin/terminal/gwt/client/TestVBrowserDetailsUserAgentParser.java b/tests/client-side/com/vaadin/terminal/gwt/client/TestVBrowserDetailsUserAgentParser.java index 183a4d0fe3..f661b6cf15 100644 --- a/tests/client-side/com/vaadin/terminal/gwt/client/TestVBrowserDetailsUserAgentParser.java +++ b/tests/client-side/com/vaadin/terminal/gwt/client/TestVBrowserDetailsUserAgentParser.java @@ -1,369 +1,369 @@ -package com.vaadin.terminal.gwt.client; - -import junit.framework.TestCase; - -import com.vaadin.terminal.gwt.client.VBrowserDetails; - -public class TestVBrowserDetailsUserAgentParser extends TestCase { - - private static final String FIREFOX30_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6"; - private static final String FIREFOX30_LINUX = "Mozilla/5.0 (X11; U; Linux x86_64; es-ES; rv:1.9.0.12) Gecko/2009070811 Ubuntu/9.04 (jaunty) Firefox/3.0.12"; - private static final String FIREFOX35_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729) FirePHP/0.4"; - private static final String FIREFOX36_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)"; - private static final String FIREFOX36B_MAC = "UAString mozilla/5.0 (macintosh; u; intel mac os x 10.6; en-us; rv:1.9.2) gecko/20100115 firefox/3.6"; - private static final String FIREFOX_30B5_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9b5) Gecko/2008032619 Firefox/3.0b5"; - private static final String FIREFOX_40B7_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/20100101 Firefox/4.0b7"; - private static final String FIREFOX_40B11_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b11) Gecko/20100101 Firefox/4.0b11"; - private static final String KONQUEROR_LINUX = "Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Exabot-Thumbnails)"; - - private static final String IE6_WINDOWS = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"; - private static final String IE7_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; - - private static final String IE8_WINDOWS = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; - private static final String IE8_IN_IE7_MODE_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; - - private static final String IE9_BETA_IN_IE7_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; - private static final String IE9_BETA_IN_IE8_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; - private static final String IE9_BETA_WINDOWS_7 = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; - - // "Version/" was added in 10.00 - private static final String OPERA964_WINDOWS = "Opera/9.64(Windows NT 5.1; U; en) Presto/2.1.1"; - private static final String OPERA1010_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.10"; - private static final String OPERA1050_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.5.22 Version/10.50"; - - private static final String CHROME3_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.198 Safari/532.0"; - private static final String CHROME4_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/532.5"; - - private static final String SAFARI3_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; cs-CZ) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 Safari/525.29"; - private static final String SAFARI4_MAC = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_8; en-us) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7"; - - public void testSafari3() { - VBrowserDetails bd = new VBrowserDetails(SAFARI3_WINDOWS); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 2); - assertEngineVersion(bd, 525.0f); - assertWindows(bd); - } - - public void testSafari4() { - VBrowserDetails bd = new VBrowserDetails(SAFARI4_MAC); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 531f); - assertMacOSX(bd); - } - - public void testChrome3() { - VBrowserDetails bd = new VBrowserDetails(CHROME3_MAC); - assertWebKit(bd); - assertChrome(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 532.0f); - assertMacOSX(bd); - } - - public void testChrome4() { - VBrowserDetails bd = new VBrowserDetails(CHROME4_WINDOWS); - assertWebKit(bd); - assertChrome(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 532f); - assertWindows(bd); - } - - public void testFirefox3() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX30_WINDOWS); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 1.9f); - assertWindows(bd); - - bd = new VBrowserDetails(FIREFOX30_LINUX); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 1.9f); - assertLinux(bd); - } - - public void testFirefox35() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX35_WINDOWS); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 5); - assertEngineVersion(bd, 1.9f); - assertWindows(bd); - } - - public void testFirefox36() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX36_WINDOWS); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 6); - assertEngineVersion(bd, 1.9f); - assertWindows(bd); - } - - public void testFirefox30b5() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX_30B5_MAC); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 1.9f); - assertMacOSX(bd); - } - - public void testFirefox40b11() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B11_WIN); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 2.0f); - assertWindows(bd); - } - - public void testFirefox40b7() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B7_WIN); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 2.0f); - assertWindows(bd); - } - - public void testKonquerorLinux() { - // Just ensure detection does not crash - VBrowserDetails bd = new VBrowserDetails(KONQUEROR_LINUX); - assertLinux(bd); - } - - public void testFirefox36b() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX36B_MAC); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 6); - assertEngineVersion(bd, 1.9f); - assertMacOSX(bd); - } - - public void testOpera964() { - VBrowserDetails bd = new VBrowserDetails(OPERA964_WINDOWS); - assertPresto(bd); - assertOpera(bd); - assertBrowserMajorVersion(bd, 9); - assertBrowserMinorVersion(bd, 64); - assertWindows(bd); - } - - public void testOpera1010() { - VBrowserDetails bd = new VBrowserDetails(OPERA1010_WINDOWS); - assertPresto(bd); - assertOpera(bd); - assertBrowserMajorVersion(bd, 10); - assertBrowserMinorVersion(bd, 10); - assertWindows(bd); - } - - public void testOpera1050() { - VBrowserDetails bd = new VBrowserDetails(OPERA1050_WINDOWS); - assertPresto(bd); - assertOpera(bd); - assertBrowserMajorVersion(bd, 10); - assertBrowserMinorVersion(bd, 50); - assertWindows(bd); - } - - public void testIE6() { - VBrowserDetails bd = new VBrowserDetails(IE6_WINDOWS); - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 6); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE7() { - VBrowserDetails bd = new VBrowserDetails(IE7_WINDOWS); - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 7); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE8() { - VBrowserDetails bd = new VBrowserDetails(IE8_WINDOWS); - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 8); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE8CompatibilityMode() { - VBrowserDetails bd = new VBrowserDetails(IE8_IN_IE7_MODE_WINDOWS); - bd.setIEMode(7); - - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 7); - assertBrowserMinorVersion(bd, 0); - - assertWindows(bd); - } - - public void testIE9() { - VBrowserDetails bd = new VBrowserDetails(IE9_BETA_WINDOWS_7); - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 9); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE9InIE7CompatibilityMode() { - VBrowserDetails bd = new VBrowserDetails(IE9_BETA_IN_IE7_MODE_WINDOWS_7); - // bd.setIE8InCompatibilityMode(); - - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 7); - assertBrowserMinorVersion(bd, 0); - - assertWindows(bd); - } - - public void testIE9InIE8CompatibilityMode() { - VBrowserDetails bd = new VBrowserDetails(IE9_BETA_IN_IE8_MODE_WINDOWS_7); - // bd.setIE8InCompatibilityMode(); - - // assertTrident(bd); - assertIE(bd); - assertBrowserMajorVersion(bd, 8); - assertBrowserMinorVersion(bd, 0); - - assertWindows(bd); - } - - /* - * Helper methods below - */ - - private void assertEngineVersion(VBrowserDetails browserDetails, - float version) { - assertEquals(version, browserDetails.getBrowserEngineVersion()); - - } - - private void assertBrowserMajorVersion(VBrowserDetails browserDetails, - int version) { - assertEquals(version, browserDetails.getBrowserMajorVersion()); - - } - - private void assertBrowserMinorVersion(VBrowserDetails browserDetails, - int version) { - assertEquals(version, browserDetails.getBrowserMinorVersion()); - - } - - private void assertGecko(VBrowserDetails browserDetails) { - // Engine - assertTrue(browserDetails.isGecko()); - assertFalse(browserDetails.isWebKit()); - assertFalse(browserDetails.isPresto()); - } - - private void assertPresto(VBrowserDetails browserDetails) { - // Engine - assertFalse(browserDetails.isGecko()); - assertFalse(browserDetails.isWebKit()); - assertTrue(browserDetails.isPresto()); - } - - private void assertWebKit(VBrowserDetails browserDetails) { - // Engine - assertFalse(browserDetails.isGecko()); - assertTrue(browserDetails.isWebKit()); - assertFalse(browserDetails.isPresto()); - } - - private void assertFirefox(VBrowserDetails browserDetails) { - // Browser - assertTrue(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertChrome(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertTrue(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertIE(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertTrue(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertOpera(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertTrue(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertSafari(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertTrue(browserDetails.isSafari()); - } - - private void assertMacOSX(VBrowserDetails browserDetails) { - assertFalse(browserDetails.isLinux()); - assertFalse(browserDetails.isWindows()); - assertTrue(browserDetails.isMacOSX()); - } - - private void assertWindows(VBrowserDetails browserDetails) { - assertFalse(browserDetails.isLinux()); - assertTrue(browserDetails.isWindows()); - assertFalse(browserDetails.isMacOSX()); - } - - private void assertLinux(VBrowserDetails browserDetails) { - assertTrue(browserDetails.isLinux()); - assertFalse(browserDetails.isWindows()); - assertFalse(browserDetails.isMacOSX()); - } - -} +package com.vaadin.terminal.gwt.client; + +import junit.framework.TestCase; + +import com.vaadin.terminal.gwt.client.VBrowserDetails; + +public class TestVBrowserDetailsUserAgentParser extends TestCase { + + private static final String FIREFOX30_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6"; + private static final String FIREFOX30_LINUX = "Mozilla/5.0 (X11; U; Linux x86_64; es-ES; rv:1.9.0.12) Gecko/2009070811 Ubuntu/9.04 (jaunty) Firefox/3.0.12"; + private static final String FIREFOX35_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729) FirePHP/0.4"; + private static final String FIREFOX36_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)"; + private static final String FIREFOX36B_MAC = "UAString mozilla/5.0 (macintosh; u; intel mac os x 10.6; en-us; rv:1.9.2) gecko/20100115 firefox/3.6"; + private static final String FIREFOX_30B5_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9b5) Gecko/2008032619 Firefox/3.0b5"; + private static final String FIREFOX_40B7_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/20100101 Firefox/4.0b7"; + private static final String FIREFOX_40B11_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b11) Gecko/20100101 Firefox/4.0b11"; + private static final String KONQUEROR_LINUX = "Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Exabot-Thumbnails)"; + + private static final String IE6_WINDOWS = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"; + private static final String IE7_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; + + private static final String IE8_WINDOWS = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; + private static final String IE8_IN_IE7_MODE_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; + + private static final String IE9_BETA_IN_IE7_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; + private static final String IE9_BETA_IN_IE8_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; + private static final String IE9_BETA_WINDOWS_7 = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; + + // "Version/" was added in 10.00 + private static final String OPERA964_WINDOWS = "Opera/9.64(Windows NT 5.1; U; en) Presto/2.1.1"; + private static final String OPERA1010_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.10"; + private static final String OPERA1050_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.5.22 Version/10.50"; + + private static final String CHROME3_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.198 Safari/532.0"; + private static final String CHROME4_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/532.5"; + + private static final String SAFARI3_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; cs-CZ) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 Safari/525.29"; + private static final String SAFARI4_MAC = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_8; en-us) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7"; + + public void testSafari3() { + VBrowserDetails bd = new VBrowserDetails(SAFARI3_WINDOWS); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 2); + assertEngineVersion(bd, 525.0f); + assertWindows(bd); + } + + public void testSafari4() { + VBrowserDetails bd = new VBrowserDetails(SAFARI4_MAC); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 531f); + assertMacOSX(bd); + } + + public void testChrome3() { + VBrowserDetails bd = new VBrowserDetails(CHROME3_MAC); + assertWebKit(bd); + assertChrome(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 532.0f); + assertMacOSX(bd); + } + + public void testChrome4() { + VBrowserDetails bd = new VBrowserDetails(CHROME4_WINDOWS); + assertWebKit(bd); + assertChrome(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 532f); + assertWindows(bd); + } + + public void testFirefox3() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX30_WINDOWS); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 1.9f); + assertWindows(bd); + + bd = new VBrowserDetails(FIREFOX30_LINUX); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 1.9f); + assertLinux(bd); + } + + public void testFirefox35() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX35_WINDOWS); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 5); + assertEngineVersion(bd, 1.9f); + assertWindows(bd); + } + + public void testFirefox36() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX36_WINDOWS); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 6); + assertEngineVersion(bd, 1.9f); + assertWindows(bd); + } + + public void testFirefox30b5() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX_30B5_MAC); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 1.9f); + assertMacOSX(bd); + } + + public void testFirefox40b11() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B11_WIN); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 2.0f); + assertWindows(bd); + } + + public void testFirefox40b7() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B7_WIN); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 2.0f); + assertWindows(bd); + } + + public void testKonquerorLinux() { + // Just ensure detection does not crash + VBrowserDetails bd = new VBrowserDetails(KONQUEROR_LINUX); + assertLinux(bd); + } + + public void testFirefox36b() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX36B_MAC); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 6); + assertEngineVersion(bd, 1.9f); + assertMacOSX(bd); + } + + public void testOpera964() { + VBrowserDetails bd = new VBrowserDetails(OPERA964_WINDOWS); + assertPresto(bd); + assertOpera(bd); + assertBrowserMajorVersion(bd, 9); + assertBrowserMinorVersion(bd, 64); + assertWindows(bd); + } + + public void testOpera1010() { + VBrowserDetails bd = new VBrowserDetails(OPERA1010_WINDOWS); + assertPresto(bd); + assertOpera(bd); + assertBrowserMajorVersion(bd, 10); + assertBrowserMinorVersion(bd, 10); + assertWindows(bd); + } + + public void testOpera1050() { + VBrowserDetails bd = new VBrowserDetails(OPERA1050_WINDOWS); + assertPresto(bd); + assertOpera(bd); + assertBrowserMajorVersion(bd, 10); + assertBrowserMinorVersion(bd, 50); + assertWindows(bd); + } + + public void testIE6() { + VBrowserDetails bd = new VBrowserDetails(IE6_WINDOWS); + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 6); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE7() { + VBrowserDetails bd = new VBrowserDetails(IE7_WINDOWS); + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 7); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE8() { + VBrowserDetails bd = new VBrowserDetails(IE8_WINDOWS); + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 8); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE8CompatibilityMode() { + VBrowserDetails bd = new VBrowserDetails(IE8_IN_IE7_MODE_WINDOWS); + bd.setIEMode(7); + + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 7); + assertBrowserMinorVersion(bd, 0); + + assertWindows(bd); + } + + public void testIE9() { + VBrowserDetails bd = new VBrowserDetails(IE9_BETA_WINDOWS_7); + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 9); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE9InIE7CompatibilityMode() { + VBrowserDetails bd = new VBrowserDetails(IE9_BETA_IN_IE7_MODE_WINDOWS_7); + // bd.setIE8InCompatibilityMode(); + + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 7); + assertBrowserMinorVersion(bd, 0); + + assertWindows(bd); + } + + public void testIE9InIE8CompatibilityMode() { + VBrowserDetails bd = new VBrowserDetails(IE9_BETA_IN_IE8_MODE_WINDOWS_7); + // bd.setIE8InCompatibilityMode(); + + // assertTrident(bd); + assertIE(bd); + assertBrowserMajorVersion(bd, 8); + assertBrowserMinorVersion(bd, 0); + + assertWindows(bd); + } + + /* + * Helper methods below + */ + + private void assertEngineVersion(VBrowserDetails browserDetails, + float version) { + assertEquals(version, browserDetails.getBrowserEngineVersion()); + + } + + private void assertBrowserMajorVersion(VBrowserDetails browserDetails, + int version) { + assertEquals(version, browserDetails.getBrowserMajorVersion()); + + } + + private void assertBrowserMinorVersion(VBrowserDetails browserDetails, + int version) { + assertEquals(version, browserDetails.getBrowserMinorVersion()); + + } + + private void assertGecko(VBrowserDetails browserDetails) { + // Engine + assertTrue(browserDetails.isGecko()); + assertFalse(browserDetails.isWebKit()); + assertFalse(browserDetails.isPresto()); + } + + private void assertPresto(VBrowserDetails browserDetails) { + // Engine + assertFalse(browserDetails.isGecko()); + assertFalse(browserDetails.isWebKit()); + assertTrue(browserDetails.isPresto()); + } + + private void assertWebKit(VBrowserDetails browserDetails) { + // Engine + assertFalse(browserDetails.isGecko()); + assertTrue(browserDetails.isWebKit()); + assertFalse(browserDetails.isPresto()); + } + + private void assertFirefox(VBrowserDetails browserDetails) { + // Browser + assertTrue(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertChrome(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertTrue(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertIE(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertTrue(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertOpera(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertTrue(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertSafari(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertTrue(browserDetails.isSafari()); + } + + private void assertMacOSX(VBrowserDetails browserDetails) { + assertFalse(browserDetails.isLinux()); + assertFalse(browserDetails.isWindows()); + assertTrue(browserDetails.isMacOSX()); + } + + private void assertWindows(VBrowserDetails browserDetails) { + assertFalse(browserDetails.isLinux()); + assertTrue(browserDetails.isWindows()); + assertFalse(browserDetails.isMacOSX()); + } + + private void assertLinux(VBrowserDetails browserDetails) { + assertTrue(browserDetails.isLinux()); + assertFalse(browserDetails.isWindows()); + assertFalse(browserDetails.isMacOSX()); + } + +} 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 itemIdList = new ArrayList(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 itemIdList = new ArrayList(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 prop1 = new ObjectProperty( - super1, TestSuperClass.class); - Assert.assertEquals("super1", prop1.getValue().getName()); - prop1 = new ObjectProperty(super1); - Assert.assertEquals("super1", prop1.getValue().getName()); - - ObjectProperty prop2 = new ObjectProperty( - sub1, TestSubClass.class); - Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); - prop2 = new ObjectProperty(sub1); - Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); - } - - public void testSetValueObjectSuper() { - ObjectProperty prop = new ObjectProperty( - 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 prop = new ObjectProperty( - 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 prop = new ObjectProperty( - 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 prop = new ObjectProperty( - 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 prop = new ObjectProperty( - 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 prop1 = new ObjectProperty( + super1, TestSuperClass.class); + Assert.assertEquals("super1", prop1.getValue().getName()); + prop1 = new ObjectProperty(super1); + Assert.assertEquals("super1", prop1.getValue().getName()); + + ObjectProperty prop2 = new ObjectProperty( + sub1, TestSubClass.class); + Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); + prop2 = new ObjectProperty(sub1); + Assert.assertEquals("Subclass: sub1", prop2.getValue().getName()); + } + + public void testSetValueObjectSuper() { + ObjectProperty prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 prop = new ObjectProperty( + 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 nameToId = new HashMap(); - private static Map idToName = new HashMap(); - - 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 { - 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 nameToId = new HashMap(); + private static Map idToName = new HashMap(); + + 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 { + 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 oracle = new ArrayList(); - 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 oracle = new ArrayList(); + 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 f = new ArrayList(); - f.add(new Like("name", "%lle")); - List 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 f = new ArrayList(); - f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); - List 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 f = new ArrayList(); - f.add(new Like("name", "%lle")); - List 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 f = new ArrayList(); - f.add(new Like("name", "%lle")); - List 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 f = new ArrayList(); - f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); - List 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 f = new ArrayList(); - f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); - List 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 f = new ArrayList(); + f.add(new Like("name", "%lle")); + List 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 f = new ArrayList(); + f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); + List 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 f = new ArrayList(); + f.add(new Like("name", "%lle")); + List 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 f = new ArrayList(); + f.add(new Like("name", "%lle")); + List 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 f = new ArrayList(); + f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); + List 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 f = new ArrayList(); + f.add(new Or(new Like("name", "%lle"), new Like("name", "vi%"))); + List 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 filters = new ArrayList(); - 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 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 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 filters = new ArrayList(); - 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 filters = new ArrayList(); + 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 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 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 filters = new ArrayList(); + 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.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.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("")); - } - - public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(AbstractProperty.class, - ReadOnlyStatusChangeEvent.class, - ReadOnlyStatusChangeListener.class, new ObjectProperty( - "")); - } -} +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("")); + } + + public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbstractProperty.class, + ReadOnlyStatusChangeEvent.class, + ReadOnlyStatusChangeListener.class, new ObjectProperty( + "")); + } +} 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 rawClasspathEntries = getRawClasspathEntries(); - - List classes = new ArrayList(); - for (String location : rawClasspathEntries) { - classes.addAll(findServerClasses(location)); - } - - ArrayList> nonSerializableClasses = new ArrayList>(); - 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> 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 getRawClasspathEntries() { - // try to keep the order of the classpath - List locations = new ArrayList(); - - 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 findServerClasses(String classpathEntry) - throws IOException { - Collection classes = new ArrayList(); - - 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 filteredClasses = new ArrayList(); - 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 findClassesInJar(File file) throws IOException { - Collection classes = new ArrayList(); - - JarFile jar = new JarFile(file); - Enumeration 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 findClassesInDirectory( - String parentPackage, File parent) { - if (parent.isHidden() - || parent.getPath().contains(File.separator + ".")) { - return Collections.emptyList(); - } - - if (parentPackage == null) { - parentPackage = ""; - } else { - parentPackage += "."; - } - - Collection classNames = new ArrayList(); - - // 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 rawClasspathEntries = getRawClasspathEntries(); + + List classes = new ArrayList(); + for (String location : rawClasspathEntries) { + classes.addAll(findServerClasses(location)); + } + + ArrayList> nonSerializableClasses = new ArrayList>(); + 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> 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 getRawClasspathEntries() { + // try to keep the order of the classpath + List locations = new ArrayList(); + + 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 findServerClasses(String classpathEntry) + throws IOException { + Collection classes = new ArrayList(); + + 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 filteredClasses = new ArrayList(); + 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 findClassesInJar(File file) throws IOException { + Collection classes = new ArrayList(); + + JarFile jar = new JarFile(file); + Enumeration 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 findClassesInDirectory( + String parentPackage, File parent) { + if (parent.isHidden() + || parent.getPath().contains(File.separator + ".")) { + return Collections.emptyList(); + } + + if (parentPackage == null) { + parentPackage = ""; + } else { + parentPackage += "."; + } + + Collection classNames = new ArrayList(); + + // 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 exceptions = new ArrayList(); - - HttpSession session = createSession(); - final WebApplicationContext context = WebApplicationContext - .getApplicationContext(session); - List threads = new ArrayList(); - - 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 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 exceptions = new ArrayList(); + + HttpSession session = createSession(); + final WebApplicationContext context = WebApplicationContext + .getApplicationContext(session); + List threads = new ArrayList(); + + 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 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 isoWeekNumbers = new HashMap(); - 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 isoWeekNumbers = new HashMap(); + 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 menuItems = new HashSet(); - - 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 ids = new HashSet(); - - for (MenuItem item : menuBar.getItems()) { - assertUniqueIds(ids, item); - } - } - - private static void assertUniqueIds(Set 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 menuItems = new HashSet(); + + 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 ids = new HashSet(); + + for (MenuItem item : menuBar.getItems()) { + assertUniqueIds(ids, item); + } + } + + private static void assertUniqueIds(Set 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 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 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 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 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 rootIds = new ArrayList(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 c = new ArrayList(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 rootIds = new ArrayList(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 c = new ArrayList(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 rootIds = new ArrayList(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 c = new ArrayList(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 rootIds = new ArrayList(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 c = new ArrayList(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 - * super.setValue(AbstractField). Also, subclasses should typically - * override {@link #setValue(AbstractField)} to set the field value via - * changeVariables(). - */ -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("")); - 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("")); - 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("")); - 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("")); - 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("")); - 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 + * super.setValue(AbstractField). Also, subclasses should typically + * override {@link #setValue(AbstractField)} to set the field value via + * changeVariables(). + */ +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("")); + 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("")); + 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("")); + 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("")); + 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("")); + 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 Ticket 4394. - */ -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 variables = new HashMap(); - 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 Ticket 4394. + */ +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 variables = new HashMap(); + 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 Ticket 4394. - */ -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 variables = new HashMap(); - 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 property = new ObjectProperty(""); - 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 property = new ObjectProperty( - 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 property = new ObjectProperty( - 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 Ticket 4394. + */ +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 variables = new HashMap(); + 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 property = new ObjectProperty(""); + 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 property = new ObjectProperty( + 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 property = new ObjectProperty( + 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 variables = new HashMap(); - variables.put("height", 1234); - window.changeVariables(window, variables); - - } - - private static void sendClose(Window window) { - Map variables = new HashMap(); - 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 variables = new HashMap(); + variables.put("height", 1234); + window.changeVariables(window, variables); + + } + + private static void sendClose(Window window) { + Map variables = new HashMap(); + 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(); + } +} diff --git a/tests/testbench/com/vaadin/launcher/DevelopmentServerLauncher.java b/tests/testbench/com/vaadin/launcher/DevelopmentServerLauncher.java index 2146d8472b..0fb346736e 100644 --- a/tests/testbench/com/vaadin/launcher/DevelopmentServerLauncher.java +++ b/tests/testbench/com/vaadin/launcher/DevelopmentServerLauncher.java @@ -1,218 +1,218 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.launcher; - -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.HashMap; -import java.util.Map; - -import org.mortbay.jetty.Connector; -import org.mortbay.jetty.Server; -import org.mortbay.jetty.nio.SelectChannelConnector; -import org.mortbay.jetty.security.SslSocketConnector; -import org.mortbay.jetty.webapp.WebAppContext; - -import com.vaadin.launcher.util.BrowserLauncher; - -/** - * Class for running Jetty servlet container within Eclipse project. - * - */ -public class DevelopmentServerLauncher { - - private static final String KEYSTORE = "src/com/vaadin/launcher/keystore"; - private final static int serverPort = 8888; - - /** - * Main function for running Jetty. - * - * Command line Arguments are passed through to Jetty, see runServer method - * for options. - * - * @param args - * @throws Exception - */ - public static void main(String[] args) { - - // Pass-through of arguments for Jetty - final Map serverArgs = parseArguments(args); - - if (serverArgs.containsKey("shutdownPort")) { - int port = Integer.parseInt(serverArgs.get("shutdownPort")); - try { - // Try to notify another instance that it's time to close - Socket socket = new Socket((String) null, port); - // Wait until the other instance says it has closed - socket.getInputStream().read(); - // Then tidy up - socket.close(); - } catch (IOException e) { - // Ignore if port is not open - } - } - - // Start Jetty - System.out.println("Starting Jetty servlet container."); - String url; - try { - url = runServer(serverArgs, "Development Server Mode"); - // Start Browser - if (!serverArgs.containsKey("nogui") && url != null) { - System.out.println("Starting Web Browser."); - - // Open browser into application URL - BrowserLauncher.openBrowser(url); - } - } catch (Exception e) { - // NOP exception already on console by jetty - } - } - - /** - * Run the server with specified arguments. - * - * @param serverArgs - * @return - * @throws Exception - * @throws Exception - */ - protected static String runServer(Map serverArgs, - String mode) throws Exception { - - // Assign default values for some arguments - assignDefault(serverArgs, "webroot", "WebContent"); - assignDefault(serverArgs, "httpPort", "" + serverPort); - assignDefault(serverArgs, "context", ""); - - int port = serverPort; - try { - port = Integer.parseInt(serverArgs.get("httpPort")); - } catch (NumberFormatException e) { - // keep default value for port - } - - // Add help for System.out - System.out - .println("-------------------------------------------------\n" - + "Starting Vaadin in " - + mode - + ".\n" - + "Running in http://localhost:" - + serverPort - + "\n-------------------------------------------------\n"); - - final Server server = new Server(); - - final Connector connector = new SelectChannelConnector(); - - connector.setPort(port); - if (serverArgs.containsKey("withssl")) { - final SslSocketConnector sslConnector = new SslSocketConnector(); - sslConnector.setPort(8444); - sslConnector.setTruststore(KEYSTORE); - sslConnector.setTrustPassword("password"); - sslConnector.setKeystore(KEYSTORE); - sslConnector.setKeyPassword("password"); - sslConnector.setPassword("password"); - server.setConnectors(new Connector[] { connector, sslConnector }); - } else { - server.setConnectors(new Connector[] { connector }); - } - - final WebAppContext webappcontext = new WebAppContext(); - String path = DevelopmentServerLauncher.class.getPackage().getName() - .replace(".", File.separator); - webappcontext.setDefaultsDescriptor(path + File.separator - + "jetty-webdefault.xml"); - webappcontext.setContextPath(serverArgs.get("context")); - webappcontext.setWar(serverArgs.get("webroot")); - server.setHandler(webappcontext); - - try { - server.start(); - - if (serverArgs.containsKey("shutdownPort")) { - int shutdownPort = Integer.parseInt(serverArgs - .get("shutdownPort")); - final ServerSocket serverSocket = new ServerSocket( - shutdownPort, 1, InetAddress.getByName("127.0.0.1")); - new Thread() { - @Override - public void run() { - try { - System.out - .println("Waiting for shutdown signal on port " - + serverSocket.getLocalPort()); - // Start waiting for a close signal - Socket accept = serverSocket.accept(); - // First stop listening to the port - serverSocket.close(); - // Then stop the jetty server - server.stop(); - // Send a byte to tell the other process that it can - // start jetty - OutputStream outputStream = accept - .getOutputStream(); - outputStream.write(0); - outputStream.flush(); - // Finally close the socket - accept.close(); - } catch (Exception e) { - e.printStackTrace(); - } - }; - - }.start(); - - } - } catch (Exception e) { - server.stop(); - throw e; - } - - return "http://localhost:" + port + serverArgs.get("context"); - } - - /** - * Assign default value for given key. - * - * @param map - * @param key - * @param value - */ - private static void assignDefault(Map map, String key, - String value) { - if (!map.containsKey(key)) { - map.put(key, value); - } - } - - /** - * Parse all command line arguments into a map. - * - * Arguments format "key=value" are put into map. - * - * @param args - * @return map of arguments key value pairs. - */ - protected static Map parseArguments(String[] args) { - final Map map = new HashMap(); - for (int i = 0; i < args.length; i++) { - final int d = args[i].indexOf("="); - if (d > 0 && d < args[i].length() && args[i].startsWith("--")) { - final String name = args[i].substring(2, d); - final String value = args[i].substring(d + 1); - map.put(name, value); - } - } - return map; - } - -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.launcher; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.HashMap; +import java.util.Map; + +import org.mortbay.jetty.Connector; +import org.mortbay.jetty.Server; +import org.mortbay.jetty.nio.SelectChannelConnector; +import org.mortbay.jetty.security.SslSocketConnector; +import org.mortbay.jetty.webapp.WebAppContext; + +import com.vaadin.launcher.util.BrowserLauncher; + +/** + * Class for running Jetty servlet container within Eclipse project. + * + */ +public class DevelopmentServerLauncher { + + private static final String KEYSTORE = "src/com/vaadin/launcher/keystore"; + private final static int serverPort = 8888; + + /** + * Main function for running Jetty. + * + * Command line Arguments are passed through to Jetty, see runServer method + * for options. + * + * @param args + * @throws Exception + */ + public static void main(String[] args) { + + // Pass-through of arguments for Jetty + final Map serverArgs = parseArguments(args); + + if (serverArgs.containsKey("shutdownPort")) { + int port = Integer.parseInt(serverArgs.get("shutdownPort")); + try { + // Try to notify another instance that it's time to close + Socket socket = new Socket((String) null, port); + // Wait until the other instance says it has closed + socket.getInputStream().read(); + // Then tidy up + socket.close(); + } catch (IOException e) { + // Ignore if port is not open + } + } + + // Start Jetty + System.out.println("Starting Jetty servlet container."); + String url; + try { + url = runServer(serverArgs, "Development Server Mode"); + // Start Browser + if (!serverArgs.containsKey("nogui") && url != null) { + System.out.println("Starting Web Browser."); + + // Open browser into application URL + BrowserLauncher.openBrowser(url); + } + } catch (Exception e) { + // NOP exception already on console by jetty + } + } + + /** + * Run the server with specified arguments. + * + * @param serverArgs + * @return + * @throws Exception + * @throws Exception + */ + protected static String runServer(Map serverArgs, + String mode) throws Exception { + + // Assign default values for some arguments + assignDefault(serverArgs, "webroot", "WebContent"); + assignDefault(serverArgs, "httpPort", "" + serverPort); + assignDefault(serverArgs, "context", ""); + + int port = serverPort; + try { + port = Integer.parseInt(serverArgs.get("httpPort")); + } catch (NumberFormatException e) { + // keep default value for port + } + + // Add help for System.out + System.out + .println("-------------------------------------------------\n" + + "Starting Vaadin in " + + mode + + ".\n" + + "Running in http://localhost:" + + serverPort + + "\n-------------------------------------------------\n"); + + final Server server = new Server(); + + final Connector connector = new SelectChannelConnector(); + + connector.setPort(port); + if (serverArgs.containsKey("withssl")) { + final SslSocketConnector sslConnector = new SslSocketConnector(); + sslConnector.setPort(8444); + sslConnector.setTruststore(KEYSTORE); + sslConnector.setTrustPassword("password"); + sslConnector.setKeystore(KEYSTORE); + sslConnector.setKeyPassword("password"); + sslConnector.setPassword("password"); + server.setConnectors(new Connector[] { connector, sslConnector }); + } else { + server.setConnectors(new Connector[] { connector }); + } + + final WebAppContext webappcontext = new WebAppContext(); + String path = DevelopmentServerLauncher.class.getPackage().getName() + .replace(".", File.separator); + webappcontext.setDefaultsDescriptor(path + File.separator + + "jetty-webdefault.xml"); + webappcontext.setContextPath(serverArgs.get("context")); + webappcontext.setWar(serverArgs.get("webroot")); + server.setHandler(webappcontext); + + try { + server.start(); + + if (serverArgs.containsKey("shutdownPort")) { + int shutdownPort = Integer.parseInt(serverArgs + .get("shutdownPort")); + final ServerSocket serverSocket = new ServerSocket( + shutdownPort, 1, InetAddress.getByName("127.0.0.1")); + new Thread() { + @Override + public void run() { + try { + System.out + .println("Waiting for shutdown signal on port " + + serverSocket.getLocalPort()); + // Start waiting for a close signal + Socket accept = serverSocket.accept(); + // First stop listening to the port + serverSocket.close(); + // Then stop the jetty server + server.stop(); + // Send a byte to tell the other process that it can + // start jetty + OutputStream outputStream = accept + .getOutputStream(); + outputStream.write(0); + outputStream.flush(); + // Finally close the socket + accept.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }; + + }.start(); + + } + } catch (Exception e) { + server.stop(); + throw e; + } + + return "http://localhost:" + port + serverArgs.get("context"); + } + + /** + * Assign default value for given key. + * + * @param map + * @param key + * @param value + */ + private static void assignDefault(Map map, String key, + String value) { + if (!map.containsKey(key)) { + map.put(key, value); + } + } + + /** + * Parse all command line arguments into a map. + * + * Arguments format "key=value" are put into map. + * + * @param args + * @return map of arguments key value pairs. + */ + protected static Map parseArguments(String[] args) { + final Map map = new HashMap(); + for (int i = 0; i < args.length; i++) { + final int d = args[i].indexOf("="); + if (d > 0 && d < args[i].length() && args[i].startsWith("--")) { + final String name = args[i].substring(2, d); + final String value = args[i].substring(d + 1); + map.put(name, value); + } + } + return map; + } + +} diff --git a/tests/testbench/com/vaadin/launcher/util/BrowserLauncher.java b/tests/testbench/com/vaadin/launcher/util/BrowserLauncher.java index 55692cb251..0ade893238 100644 --- a/tests/testbench/com/vaadin/launcher/util/BrowserLauncher.java +++ b/tests/testbench/com/vaadin/launcher/util/BrowserLauncher.java @@ -1,127 +1,127 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.launcher.util; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; - -/** - * This class opens default browser for DemoLauncher class. Default browser is - * detected by the operating system. - * - */ -public class BrowserLauncher { - - /** - * Open browser on specified URL. - * - * @param url - */ - public static void openBrowser(String url) { - - final Runtime runtime = Runtime.getRuntime(); - boolean started = false; - - final String os = System.getProperty("os.name", "windows") - .toLowerCase(); - - // Linux - if (os.indexOf("linux") >= 0) { - // See if the default browser is Konqueror by resolving the symlink. - boolean isDefaultKonqueror = false; - try { - // Find out the location of the x-www-browser link from path. - Process process = runtime.exec("which x-www-browser"); - BufferedInputStream ins = new BufferedInputStream( - process.getInputStream()); - BufferedReader bufreader = new BufferedReader( - new InputStreamReader(ins)); - String defaultLinkPath = bufreader.readLine(); - ins.close(); - - // The path is null if the link did not exist. - if (defaultLinkPath != null) { - // See if the default browser is Konqueror. - File file = new File(defaultLinkPath); - String canonical = file.getCanonicalPath(); - if (canonical.indexOf("konqueror") != -1) { - isDefaultKonqueror = true; - } - } - } catch (IOException e1) { - // The symlink was probably not found, so this is ok. - } - - // Try x-www-browser, which is symlink to the default browser, - // except if we found that it is Konqueror. - if (!started && !isDefaultKonqueror) { - try { - runtime.exec("x-www-browser " + url); - started = true; - } catch (final IOException e) { - } - } - - // Try firefox - if (!started) { - try { - runtime.exec("firefox " + url); - started = true; - } catch (final IOException e) { - } - } - - // Try mozilla - if (!started) { - try { - runtime.exec("mozilla " + url); - started = true; - } catch (final IOException e) { - } - } - - // Try konqueror - if (!started) { - try { - runtime.exec("konqueror " + url); - started = true; - } catch (final IOException e) { - } - } - } - - // OS X - if (os.indexOf("mac os x") >= 0) { - - // Try open - if (!started) { - try { - runtime.exec("open " + url); - started = true; - } catch (final IOException e) { - } - } - } - - // Try cmd /start command on windows - if (os.indexOf("win") >= 0) { - if (!started) { - try { - runtime.exec("cmd /c start " + url); - started = true; - } catch (final IOException e) { - } - } - } - - if (!started) { - System.out.println("Failed to open browser. Please go to " + url); - } - } - -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.launcher.util; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * This class opens default browser for DemoLauncher class. Default browser is + * detected by the operating system. + * + */ +public class BrowserLauncher { + + /** + * Open browser on specified URL. + * + * @param url + */ + public static void openBrowser(String url) { + + final Runtime runtime = Runtime.getRuntime(); + boolean started = false; + + final String os = System.getProperty("os.name", "windows") + .toLowerCase(); + + // Linux + if (os.indexOf("linux") >= 0) { + // See if the default browser is Konqueror by resolving the symlink. + boolean isDefaultKonqueror = false; + try { + // Find out the location of the x-www-browser link from path. + Process process = runtime.exec("which x-www-browser"); + BufferedInputStream ins = new BufferedInputStream( + process.getInputStream()); + BufferedReader bufreader = new BufferedReader( + new InputStreamReader(ins)); + String defaultLinkPath = bufreader.readLine(); + ins.close(); + + // The path is null if the link did not exist. + if (defaultLinkPath != null) { + // See if the default browser is Konqueror. + File file = new File(defaultLinkPath); + String canonical = file.getCanonicalPath(); + if (canonical.indexOf("konqueror") != -1) { + isDefaultKonqueror = true; + } + } + } catch (IOException e1) { + // The symlink was probably not found, so this is ok. + } + + // Try x-www-browser, which is symlink to the default browser, + // except if we found that it is Konqueror. + if (!started && !isDefaultKonqueror) { + try { + runtime.exec("x-www-browser " + url); + started = true; + } catch (final IOException e) { + } + } + + // Try firefox + if (!started) { + try { + runtime.exec("firefox " + url); + started = true; + } catch (final IOException e) { + } + } + + // Try mozilla + if (!started) { + try { + runtime.exec("mozilla " + url); + started = true; + } catch (final IOException e) { + } + } + + // Try konqueror + if (!started) { + try { + runtime.exec("konqueror " + url); + started = true; + } catch (final IOException e) { + } + } + } + + // OS X + if (os.indexOf("mac os x") >= 0) { + + // Try open + if (!started) { + try { + runtime.exec("open " + url); + started = true; + } catch (final IOException e) { + } + } + } + + // Try cmd /start command on windows + if (os.indexOf("win") >= 0) { + if (!started) { + try { + runtime.exec("cmd /c start " + url); + started = true; + } catch (final IOException e) { + } + } + } + + if (!started) { + System.out.println("Failed to open browser. Please go to " + url); + } + } + +} diff --git a/tests/testbench/com/vaadin/tests/Components.java b/tests/testbench/com/vaadin/tests/Components.java index d7bc18e2f6..3366f6db43 100644 --- a/tests/testbench/com/vaadin/tests/Components.java +++ b/tests/testbench/com/vaadin/tests/Components.java @@ -1,268 +1,268 @@ -package com.vaadin.tests; - -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.vaadin.Application; -import com.vaadin.data.Item; -import com.vaadin.data.util.DefaultItemSorter; -import com.vaadin.data.util.HierarchicalContainer; -import com.vaadin.event.ItemClickEvent; -import com.vaadin.event.ItemClickEvent.ItemClickListener; -import com.vaadin.terminal.ExternalResource; -import com.vaadin.terminal.Sizeable; -import com.vaadin.tests.components.AbstractComponentTest; -import com.vaadin.ui.AbstractComponent; -import com.vaadin.ui.Component; -import com.vaadin.ui.ComponentContainer; -import com.vaadin.ui.Embedded; -import com.vaadin.ui.HorizontalSplitPanel; -import com.vaadin.ui.Label; -import com.vaadin.ui.Tree; -import com.vaadin.ui.Tree.ItemStyleGenerator; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.Window; - -public class Components extends Application { - - private static final Object CAPTION = "c"; - private Map, String> tests = new HashMap, String>(); - private Tree naviTree; - private HorizontalSplitPanel sp; - private Window mainWindow; - private final Embedded applicationEmbedder = new Embedded(); - private String baseUrl; - private List> componentsWithoutTests = new ArrayList>(); - - { - for (Class c : VaadinClasses.getBasicComponentTests()) { - String testClass = c.getSimpleName(); - tests.put((Class) c, testClass); - } - - List> componentsWithoutTest = VaadinClasses - .getComponents(); - Set availableTests = new HashSet(); - for (String testName : tests.values()) { - availableTests.add(testName); - } - - for (Class component : componentsWithoutTest) { - String baseName = component.getSimpleName(); - if (availableTests.contains(baseName + "es")) { - continue; - } - if (availableTests.contains(baseName + "es2")) { - continue; - } - if (availableTests.contains(baseName + "s2")) { - continue; - } - if (availableTests.contains(baseName + "s")) { - continue; - } - if (availableTests.contains(baseName + "Test")) { - continue; - } - - componentsWithoutTests.add(component); - } - - } - - class MissingTest extends AbstractComponentTest { - @Override - protected Class getTestClass() { - return null; - } - } - - @Override - public void init() { - mainWindow = new Window(); - setTheme("tests-components"); - mainWindow.getContent().setSizeFull(); - setMainWindow(mainWindow); - sp = new HorizontalSplitPanel(); - sp.setSizeFull(); - VerticalLayout naviLayout = new VerticalLayout(); - naviLayout - .addComponent(new Label( - "Click to open a test case.
Right click to open test in a new window

", - Label.CONTENT_XHTML)); - naviLayout.addComponent(createMenu()); - naviLayout.addComponent(createMissingTestsList()); - - sp.setFirstComponent(naviLayout); - sp.setSplitPosition(250, Sizeable.UNITS_PIXELS); - VerticalLayout embeddingLayout = new VerticalLayout(); - embeddingLayout.setSizeFull(); - embeddingLayout - .addComponent(new Label( - "Do not use the embedded version for creating automated tests. Open the test in a new window before recording.
", - Label.CONTENT_XHTML)); - applicationEmbedder.setSizeFull(); - embeddingLayout.addComponent(applicationEmbedder); - embeddingLayout.setExpandRatio(applicationEmbedder, 1); - sp.setSecondComponent(embeddingLayout); - mainWindow.addComponent(sp); - - applicationEmbedder.setType(Embedded.TYPE_BROWSER); - baseUrl = getURL().toString().replace(getClass().getName(), "") - .replaceAll("//$", "/"); - } - - private Component createMissingTestsList() { - String missingTests = ""; - for (Class component : componentsWithoutTests) { - String cls = "missing"; - if (component.getAnnotation(Deprecated.class) != null) { - cls = "missing-deprecated"; - } - missingTests += "" - + component.getSimpleName() + "
"; - } - return new Label("Components without a test:
" - + missingTests, Label.CONTENT_XHTML); - } - - private Component createMenu() { - naviTree = new Tree(); - naviTree.setItemStyleGenerator(new ItemStyleGenerator() { - - public String getStyle(Object itemId) { - Class cls = (Class) itemId; - if (!isAbstract(cls)) { - return "blue"; - } - return null; - } - }); - HierarchicalContainer hc = new HierarchicalContainer(); - naviTree.setContainerDataSource(hc); - DefaultItemSorter sorter = new DefaultItemSorter() { - @SuppressWarnings("rawtypes") - @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof Class && o2 instanceof Class && o1 != null - && o2 != null) { - Class c1 = (Class) o1; - Class c2 = (Class) o2; - boolean a1 = isAbstract(c1); - boolean a2 = isAbstract(c2); - - if (a1 && !a2) { - return 1; - } else if (!a1 && a2) { - return -1; - } - - } - return super.compare(o1, o2); - } - }; - hc.setItemSorter(sorter); - naviTree.addContainerProperty(CAPTION, String.class, ""); - naviTree.setItemCaptionPropertyId(CAPTION); - for (Class cls : tests.keySet()) { - addTreeItem(cls); - } - hc.sort(new Object[] { CAPTION }, new boolean[] { true }); - naviTree.setSelectable(false); - for (Object o : naviTree.rootItemIds()) { - expandAndSetChildrenAllowed(o); - } - - naviTree.addListener(new ItemClickListener() { - - public void itemClick(ItemClickEvent event) { - Class cls = (Class) event.getItemId(); - if (!isAbstract(cls)) { - String url = baseUrl + cls.getName() - + "?restartApplication"; - if (event.getButton() == ItemClickEvent.BUTTON_LEFT) { - openEmbedded(url); - naviTree.setValue(event.getItemId()); - } else if (event.getButton() == ItemClickEvent.BUTTON_RIGHT) { - openInNewTab(url); - } - } - } - - }); - return naviTree; - } - - protected void openInNewTab(String url) { - getMainWindow().open(new ExternalResource(url), "_blank"); - } - - protected void openEmbedded(String url) { - applicationEmbedder.setSource(new ExternalResource(url)); - } - - private void expandAndSetChildrenAllowed(Object o) { - Collection children = naviTree.getChildren(o); - if (children == null || children.size() == 0) { - naviTree.setChildrenAllowed(o, false); - } else { - naviTree.expandItem(o); - for (Object c : children) { - expandAndSetChildrenAllowed(c); - } - } - - } - - protected boolean isAbstract(Class cls) { - return Modifier.isAbstract(cls.getModifiers()); - } - - @SuppressWarnings("unchecked") - private void addTreeItem(Class cls) { - String name = tests.get(cls); - if (name == null) { - name = cls.getSimpleName(); - } - - Class superClass = (Class) cls - .getSuperclass(); - - // This cast is needed only to make compilation through Ant work .. - if (((Class) cls) != AbstractComponentTest.class) { - addTreeItem(superClass); - } - if (naviTree.containsId(cls)) { - return; - } - - Item i = naviTree.addItem(cls); - i.getItemProperty(CAPTION).setValue(name); - naviTree.setParent(cls, superClass); - } - - protected Component createTestComponent( - Class cls) { - try { - AbstractComponentTest t = cls.newInstance(); - t.init(); - ComponentContainer c = t.getMainWindow().getContent(); - t.getMainWindow().setContent(null); - return c; - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - } - -} +package com.vaadin.tests; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.vaadin.Application; +import com.vaadin.data.Item; +import com.vaadin.data.util.DefaultItemSorter; +import com.vaadin.data.util.HierarchicalContainer; +import com.vaadin.event.ItemClickEvent; +import com.vaadin.event.ItemClickEvent.ItemClickListener; +import com.vaadin.terminal.ExternalResource; +import com.vaadin.terminal.Sizeable; +import com.vaadin.tests.components.AbstractComponentTest; +import com.vaadin.ui.AbstractComponent; +import com.vaadin.ui.Component; +import com.vaadin.ui.ComponentContainer; +import com.vaadin.ui.Embedded; +import com.vaadin.ui.HorizontalSplitPanel; +import com.vaadin.ui.Label; +import com.vaadin.ui.Tree; +import com.vaadin.ui.Tree.ItemStyleGenerator; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; + +public class Components extends Application { + + private static final Object CAPTION = "c"; + private Map, String> tests = new HashMap, String>(); + private Tree naviTree; + private HorizontalSplitPanel sp; + private Window mainWindow; + private final Embedded applicationEmbedder = new Embedded(); + private String baseUrl; + private List> componentsWithoutTests = new ArrayList>(); + + { + for (Class c : VaadinClasses.getBasicComponentTests()) { + String testClass = c.getSimpleName(); + tests.put((Class) c, testClass); + } + + List> componentsWithoutTest = VaadinClasses + .getComponents(); + Set availableTests = new HashSet(); + for (String testName : tests.values()) { + availableTests.add(testName); + } + + for (Class component : componentsWithoutTest) { + String baseName = component.getSimpleName(); + if (availableTests.contains(baseName + "es")) { + continue; + } + if (availableTests.contains(baseName + "es2")) { + continue; + } + if (availableTests.contains(baseName + "s2")) { + continue; + } + if (availableTests.contains(baseName + "s")) { + continue; + } + if (availableTests.contains(baseName + "Test")) { + continue; + } + + componentsWithoutTests.add(component); + } + + } + + class MissingTest extends AbstractComponentTest { + @Override + protected Class getTestClass() { + return null; + } + } + + @Override + public void init() { + mainWindow = new Window(); + setTheme("tests-components"); + mainWindow.getContent().setSizeFull(); + setMainWindow(mainWindow); + sp = new HorizontalSplitPanel(); + sp.setSizeFull(); + VerticalLayout naviLayout = new VerticalLayout(); + naviLayout + .addComponent(new Label( + "Click to open a test case.
Right click to open test in a new window

", + Label.CONTENT_XHTML)); + naviLayout.addComponent(createMenu()); + naviLayout.addComponent(createMissingTestsList()); + + sp.setFirstComponent(naviLayout); + sp.setSplitPosition(250, Sizeable.UNITS_PIXELS); + VerticalLayout embeddingLayout = new VerticalLayout(); + embeddingLayout.setSizeFull(); + embeddingLayout + .addComponent(new Label( + "Do not use the embedded version for creating automated tests. Open the test in a new window before recording.
", + Label.CONTENT_XHTML)); + applicationEmbedder.setSizeFull(); + embeddingLayout.addComponent(applicationEmbedder); + embeddingLayout.setExpandRatio(applicationEmbedder, 1); + sp.setSecondComponent(embeddingLayout); + mainWindow.addComponent(sp); + + applicationEmbedder.setType(Embedded.TYPE_BROWSER); + baseUrl = getURL().toString().replace(getClass().getName(), "") + .replaceAll("//$", "/"); + } + + private Component createMissingTestsList() { + String missingTests = ""; + for (Class component : componentsWithoutTests) { + String cls = "missing"; + if (component.getAnnotation(Deprecated.class) != null) { + cls = "missing-deprecated"; + } + missingTests += "" + + component.getSimpleName() + "
"; + } + return new Label("Components without a test:
" + + missingTests, Label.CONTENT_XHTML); + } + + private Component createMenu() { + naviTree = new Tree(); + naviTree.setItemStyleGenerator(new ItemStyleGenerator() { + + public String getStyle(Object itemId) { + Class cls = (Class) itemId; + if (!isAbstract(cls)) { + return "blue"; + } + return null; + } + }); + HierarchicalContainer hc = new HierarchicalContainer(); + naviTree.setContainerDataSource(hc); + DefaultItemSorter sorter = new DefaultItemSorter() { + @SuppressWarnings("rawtypes") + @Override + public int compare(Object o1, Object o2) { + if (o1 instanceof Class && o2 instanceof Class && o1 != null + && o2 != null) { + Class c1 = (Class) o1; + Class c2 = (Class) o2; + boolean a1 = isAbstract(c1); + boolean a2 = isAbstract(c2); + + if (a1 && !a2) { + return 1; + } else if (!a1 && a2) { + return -1; + } + + } + return super.compare(o1, o2); + } + }; + hc.setItemSorter(sorter); + naviTree.addContainerProperty(CAPTION, String.class, ""); + naviTree.setItemCaptionPropertyId(CAPTION); + for (Class cls : tests.keySet()) { + addTreeItem(cls); + } + hc.sort(new Object[] { CAPTION }, new boolean[] { true }); + naviTree.setSelectable(false); + for (Object o : naviTree.rootItemIds()) { + expandAndSetChildrenAllowed(o); + } + + naviTree.addListener(new ItemClickListener() { + + public void itemClick(ItemClickEvent event) { + Class cls = (Class) event.getItemId(); + if (!isAbstract(cls)) { + String url = baseUrl + cls.getName() + + "?restartApplication"; + if (event.getButton() == ItemClickEvent.BUTTON_LEFT) { + openEmbedded(url); + naviTree.setValue(event.getItemId()); + } else if (event.getButton() == ItemClickEvent.BUTTON_RIGHT) { + openInNewTab(url); + } + } + } + + }); + return naviTree; + } + + protected void openInNewTab(String url) { + getMainWindow().open(new ExternalResource(url), "_blank"); + } + + protected void openEmbedded(String url) { + applicationEmbedder.setSource(new ExternalResource(url)); + } + + private void expandAndSetChildrenAllowed(Object o) { + Collection children = naviTree.getChildren(o); + if (children == null || children.size() == 0) { + naviTree.setChildrenAllowed(o, false); + } else { + naviTree.expandItem(o); + for (Object c : children) { + expandAndSetChildrenAllowed(c); + } + } + + } + + protected boolean isAbstract(Class cls) { + return Modifier.isAbstract(cls.getModifiers()); + } + + @SuppressWarnings("unchecked") + private void addTreeItem(Class cls) { + String name = tests.get(cls); + if (name == null) { + name = cls.getSimpleName(); + } + + Class superClass = (Class) cls + .getSuperclass(); + + // This cast is needed only to make compilation through Ant work .. + if (((Class) cls) != AbstractComponentTest.class) { + addTreeItem(superClass); + } + if (naviTree.containsId(cls)) { + return; + } + + Item i = naviTree.addItem(cls); + i.getItemProperty(CAPTION).setValue(name); + naviTree.setParent(cls, superClass); + } + + protected Component createTestComponent( + Class cls) { + try { + AbstractComponentTest t = cls.newInstance(); + t.init(); + ComponentContainer c = t.getMainWindow().getContent(); + t.getMainWindow().setContent(null); + return c; + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + +} diff --git a/tests/testbench/com/vaadin/tests/StressComponentsInTable.java b/tests/testbench/com/vaadin/tests/StressComponentsInTable.java index 02662cdcbb..9c2703822e 100644 --- a/tests/testbench/com/vaadin/tests/StressComponentsInTable.java +++ b/tests/testbench/com/vaadin/tests/StressComponentsInTable.java @@ -1,75 +1,75 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.tests; - -import java.util.Date; -import java.util.Vector; - -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.Table; -import com.vaadin.ui.VerticalLayout; - -public class StressComponentsInTable extends CustomComponent { - - public StressComponentsInTable() { - final VerticalLayout main = new VerticalLayout(); - setCompositionRoot(main); - - main.addComponent(getTestTable(4, 1000)); - - } - - public static Table getTestTable(int cols, int rows) { - final Table t = new Table(); - t.setColumnCollapsingAllowed(true); - for (int i = 0; i < cols; i++) { - t.addContainerProperty(testString[i], String.class, ""); - } - t.addContainerProperty("button", Button.class, null); - for (int i = 0; i < rows; i++) { - final Vector content = new Vector(); - for (int j = 0; j < cols; j++) { - content.add(rndString()); - } - content.add(new Button("b" + i, new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - Button b = event.getButton(); - System.out.println(b.getCaption() + " click: " - + (new Date()).toString()); - System.out.println(b.getApplication()); - - } - })); - t.addItem(content.toArray(), "" + i); - } - t.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); - return t; - } - - static String[] testString = new String[] { "Jacob", "Michael", "Joshua", - "Matthew", "Ethan", "Andrew", "Daniel", "Anthony", "Christopher", - "Joseph", "William", "Alexander", "Ryan", "David", "Nicholas", - "Tyler", "James", "John", "Jonathan", "Nathan", "Samuel", - "Christian", "Noah", "Dylan", "Benjamin", "Logan", "Brandon", - "Gabriel", "Zachary", "Jose", "Elijah", "Angel", "Kevin", "Jack", - "Caleb", "Justin", "Austin", "Evan", "Robert", "Thomas", "Luke", - "Mason", "Aidan", "Jackson", "Isaiah", "Jordan", "Gavin", "Connor", - "Aiden", "Isaac", "Jason", "Cameron", "Hunter", "Jayden", "Juan", - "Charles", "Aaron", "Lucas", "Luis", "Owen", "Landon", "Diego", - "Brian", "Adam", "Adrian", "Kyle", "Eric", "Ian", "Nathaniel", - "Carlos", "Alex", "Bryan", "Jesus", "Julian", "Sean", "Carter", - "Hayden", "Jeremiah", "Cole", "Brayden", "Wyatt", "Chase", - "Steven", "Timothy", "Dominic", "Sebastian", "Xavier", "Jaden", - "Jesse", "Devin", "Seth", "Antonio", "Richard", "Miguel", "Colin", - "Cody", "Alejandro", "Caden", "Blake", "Carson" }; - - public static String rndString() { - return testString[(int) (Math.random() * testString.length)]; - } - -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.tests; + +import java.util.Date; +import java.util.Vector; + +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.Table; +import com.vaadin.ui.VerticalLayout; + +public class StressComponentsInTable extends CustomComponent { + + public StressComponentsInTable() { + final VerticalLayout main = new VerticalLayout(); + setCompositionRoot(main); + + main.addComponent(getTestTable(4, 1000)); + + } + + public static Table getTestTable(int cols, int rows) { + final Table t = new Table(); + t.setColumnCollapsingAllowed(true); + for (int i = 0; i < cols; i++) { + t.addContainerProperty(testString[i], String.class, ""); + } + t.addContainerProperty("button", Button.class, null); + for (int i = 0; i < rows; i++) { + final Vector content = new Vector(); + for (int j = 0; j < cols; j++) { + content.add(rndString()); + } + content.add(new Button("b" + i, new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + Button b = event.getButton(); + System.out.println(b.getCaption() + " click: " + + (new Date()).toString()); + System.out.println(b.getApplication()); + + } + })); + t.addItem(content.toArray(), "" + i); + } + t.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); + return t; + } + + static String[] testString = new String[] { "Jacob", "Michael", "Joshua", + "Matthew", "Ethan", "Andrew", "Daniel", "Anthony", "Christopher", + "Joseph", "William", "Alexander", "Ryan", "David", "Nicholas", + "Tyler", "James", "John", "Jonathan", "Nathan", "Samuel", + "Christian", "Noah", "Dylan", "Benjamin", "Logan", "Brandon", + "Gabriel", "Zachary", "Jose", "Elijah", "Angel", "Kevin", "Jack", + "Caleb", "Justin", "Austin", "Evan", "Robert", "Thomas", "Luke", + "Mason", "Aidan", "Jackson", "Isaiah", "Jordan", "Gavin", "Connor", + "Aiden", "Isaac", "Jason", "Cameron", "Hunter", "Jayden", "Juan", + "Charles", "Aaron", "Lucas", "Luis", "Owen", "Landon", "Diego", + "Brian", "Adam", "Adrian", "Kyle", "Eric", "Ian", "Nathaniel", + "Carlos", "Alex", "Bryan", "Jesus", "Julian", "Sean", "Carter", + "Hayden", "Jeremiah", "Cole", "Brayden", "Wyatt", "Chase", + "Steven", "Timothy", "Dominic", "Sebastian", "Xavier", "Jaden", + "Jesse", "Devin", "Seth", "Antonio", "Richard", "Miguel", "Colin", + "Cody", "Alejandro", "Caden", "Blake", "Carson" }; + + public static String rndString() { + return testString[(int) (Math.random() * testString.length)]; + } + +} diff --git a/tests/testbench/com/vaadin/tests/TableChangingDatasource.java b/tests/testbench/com/vaadin/tests/TableChangingDatasource.java index 983355a6e6..fa7edc3a45 100644 --- a/tests/testbench/com/vaadin/tests/TableChangingDatasource.java +++ b/tests/testbench/com/vaadin/tests/TableChangingDatasource.java @@ -1,53 +1,53 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.tests; - -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.Label; -import com.vaadin.ui.Table; -import com.vaadin.ui.VerticalLayout; - -public class TableChangingDatasource extends CustomComponent implements - ClickListener { - Table t; - Table[] ta = new Table[4]; - private int mode = 0; - - public TableChangingDatasource() { - final VerticalLayout main = new VerticalLayout(); - - main.addComponent(new Label( - "Table should look sane after data source changes")); - - t = new Table(); - - t.setWidth("500px"); - t.setHeight("300px"); - - ta[0] = TestForTablesInitialColumnWidthLogicRendering - .getTestTable(3, 0); - ta[1] = TestForTablesInitialColumnWidthLogicRendering - .getTestTable(3, 7); - ta[2] = TestForTablesInitialColumnWidthLogicRendering - .getTestTable(3, 5); - ta[3] = TestForTablesInitialColumnWidthLogicRendering - .getTestTable(3, 1); - - main.addComponent(t); - main.addComponent(new Button("switch DS", this)); - - setCompositionRoot(main); - - } - - public void buttonClick(ClickEvent event) { - int i = mode % 4; - t.setContainerDataSource(ta[i].getContainerDataSource()); - mode++; - } -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.tests; + +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.Label; +import com.vaadin.ui.Table; +import com.vaadin.ui.VerticalLayout; + +public class TableChangingDatasource extends CustomComponent implements + ClickListener { + Table t; + Table[] ta = new Table[4]; + private int mode = 0; + + public TableChangingDatasource() { + final VerticalLayout main = new VerticalLayout(); + + main.addComponent(new Label( + "Table should look sane after data source changes")); + + t = new Table(); + + t.setWidth("500px"); + t.setHeight("300px"); + + ta[0] = TestForTablesInitialColumnWidthLogicRendering + .getTestTable(3, 0); + ta[1] = TestForTablesInitialColumnWidthLogicRendering + .getTestTable(3, 7); + ta[2] = TestForTablesInitialColumnWidthLogicRendering + .getTestTable(3, 5); + ta[3] = TestForTablesInitialColumnWidthLogicRendering + .getTestTable(3, 1); + + main.addComponent(t); + main.addComponent(new Button("switch DS", this)); + + setCompositionRoot(main); + + } + + public void buttonClick(ClickEvent event) { + int i = mode % 4; + t.setContainerDataSource(ta[i].getContainerDataSource()); + mode++; + } +} diff --git a/tests/testbench/com/vaadin/tests/TableSelectTest.java b/tests/testbench/com/vaadin/tests/TableSelectTest.java index 6430d7bc1c..62070c4b97 100644 --- a/tests/testbench/com/vaadin/tests/TableSelectTest.java +++ b/tests/testbench/com/vaadin/tests/TableSelectTest.java @@ -1,123 +1,123 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.tests; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.Label; -import com.vaadin.ui.Table; -import com.vaadin.ui.VerticalLayout; - -public class TableSelectTest extends CustomComponent implements - Table.ValueChangeListener { - - public TableSelectTest() { - final VerticalLayout main = new VerticalLayout(); - setCompositionRoot(main); - main.addComponent(new Label("Hello World!")); - - Table t; - t = new Table("single nullsel"); - main.addComponent(t); - t(t); - t.setMultiSelect(false); - t.setNullSelectionAllowed(true); - t.addListener(this); - - t = new Table("single NO-nullsel"); - main.addComponent(t); - t(t); - t.setMultiSelect(false); - t.setNullSelectionAllowed(false); - t.addListener(this); - - t = new Table("multi nullsel"); - main.addComponent(t); - t(t); - t.setMultiSelect(true); - t.setNullSelectionAllowed(true); - t.addListener(this); - - t = new Table("multi NO-nullsel"); - main.addComponent(t); - t(t); - t.setMultiSelect(true); - t.setNullSelectionAllowed(false); - t.addListener(this); - - // -- - - t = new Table("single nullsel nullselid"); - main.addComponent(t); - Object id = t(t); - t.setNullSelectionItemId(id); - t.setMultiSelect(false); - t.setNullSelectionAllowed(true); - t.addListener(this); - - t = new Table("single NO-nullsel nullselid"); - main.addComponent(t); - id = t(t); - t.setNullSelectionItemId(id); - t.setMultiSelect(false); - t.setNullSelectionAllowed(false); - t.addListener(this); - - t = new Table("multi(fails) nullsel nullselid"); - main.addComponent(t); - id = t(t); - t.setNullSelectionItemId(id); - try { - t.setMultiSelect(true); - t.setCaption("multi(SHOLD FAIL BUT DID NOT) nullsel nullselid"); - } catch (final Exception e) { - System.err.println("failed ok"); - } - t.setNullSelectionAllowed(true); - t.addListener(this); - - t = new Table("multi(fails) NO-nullsel nullselid"); - main.addComponent(t); - id = t(t); - t.setNullSelectionItemId(id); - try { - t.setMultiSelect(true); - t.setCaption("multi(SHOLD FAIL BUT DID NOT) NO-nullsel nullselid"); - } catch (final Exception e) { - System.err.println("failed ok"); - } - t.setNullSelectionAllowed(false); - t.addListener(this); - - /* - * And that's it! The framework will display the main window and its - * contents when the application is accessed with the terminal. - */ - - } - - private Object t(Table t) { - t.setImmediate(true); - t.setSelectable(true); - - Object id = null; - for (int i = 0; i < 5; i++) { - id = t.addItem(); - } - t.addContainerProperty("asd", String.class, "the asd thing"); - t.addContainerProperty("foo", String.class, "foo stuff"); - t.addContainerProperty("Alonger column header", String.class, "short"); - - return id; - } - - public void valueChange(ValueChangeEvent event) { - final Object val = event.getProperty().getValue(); - - System.err.println("Value: " + val); - - } - -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.tests; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.Label; +import com.vaadin.ui.Table; +import com.vaadin.ui.VerticalLayout; + +public class TableSelectTest extends CustomComponent implements + Table.ValueChangeListener { + + public TableSelectTest() { + final VerticalLayout main = new VerticalLayout(); + setCompositionRoot(main); + main.addComponent(new Label("Hello World!")); + + Table t; + t = new Table("single nullsel"); + main.addComponent(t); + t(t); + t.setMultiSelect(false); + t.setNullSelectionAllowed(true); + t.addListener(this); + + t = new Table("single NO-nullsel"); + main.addComponent(t); + t(t); + t.setMultiSelect(false); + t.setNullSelectionAllowed(false); + t.addListener(this); + + t = new Table("multi nullsel"); + main.addComponent(t); + t(t); + t.setMultiSelect(true); + t.setNullSelectionAllowed(true); + t.addListener(this); + + t = new Table("multi NO-nullsel"); + main.addComponent(t); + t(t); + t.setMultiSelect(true); + t.setNullSelectionAllowed(false); + t.addListener(this); + + // -- + + t = new Table("single nullsel nullselid"); + main.addComponent(t); + Object id = t(t); + t.setNullSelectionItemId(id); + t.setMultiSelect(false); + t.setNullSelectionAllowed(true); + t.addListener(this); + + t = new Table("single NO-nullsel nullselid"); + main.addComponent(t); + id = t(t); + t.setNullSelectionItemId(id); + t.setMultiSelect(false); + t.setNullSelectionAllowed(false); + t.addListener(this); + + t = new Table("multi(fails) nullsel nullselid"); + main.addComponent(t); + id = t(t); + t.setNullSelectionItemId(id); + try { + t.setMultiSelect(true); + t.setCaption("multi(SHOLD FAIL BUT DID NOT) nullsel nullselid"); + } catch (final Exception e) { + System.err.println("failed ok"); + } + t.setNullSelectionAllowed(true); + t.addListener(this); + + t = new Table("multi(fails) NO-nullsel nullselid"); + main.addComponent(t); + id = t(t); + t.setNullSelectionItemId(id); + try { + t.setMultiSelect(true); + t.setCaption("multi(SHOLD FAIL BUT DID NOT) NO-nullsel nullselid"); + } catch (final Exception e) { + System.err.println("failed ok"); + } + t.setNullSelectionAllowed(false); + t.addListener(this); + + /* + * And that's it! The framework will display the main window and its + * contents when the application is accessed with the terminal. + */ + + } + + private Object t(Table t) { + t.setImmediate(true); + t.setSelectable(true); + + Object id = null; + for (int i = 0; i < 5; i++) { + id = t.addItem(); + } + t.addContainerProperty("asd", String.class, "the asd thing"); + t.addContainerProperty("foo", String.class, "foo stuff"); + t.addContainerProperty("Alonger column header", String.class, "short"); + + return id; + } + + public void valueChange(ValueChangeEvent event) { + final Object val = event.getProperty().getValue(); + + System.err.println("Value: " + val); + + } + +} diff --git a/tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java b/tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java index 5203a7055f..62a67cb747 100644 --- a/tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java +++ b/tests/testbench/com/vaadin/tests/TestComponentAddAndRecursion.java @@ -1,128 +1,128 @@ -/** - * - */ -package com.vaadin.tests; - -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.Panel; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.Window; - -/** - * @author marc - * - */ -public class TestComponentAddAndRecursion extends CustomComponent { - Panel p; - Panel p2; - Label l; - Label l2; - Panel p3; - - public TestComponentAddAndRecursion() { - - VerticalLayout main = new VerticalLayout(); - setCompositionRoot(main); - - l = new Label("A"); - l2 = new Label("B"); - p = new Panel("p"); - p.addComponent(l); - p.addComponent(l2); - main.addComponent(p); - p2 = new Panel("p2"); - p2.addComponent(l); - main.addComponent(p2); - p3 = new Panel("p3"); - p2.addComponent(p3); - - Button b = new Button("use gridlayout", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - p.setContent(new GridLayout()); - p2.setContent(new GridLayout()); - p3.setContent(new GridLayout()); - } - - }); - main.addComponent(b); - b = new Button("use orderedlayout", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - p.setContent(new VerticalLayout()); - p2.setContent(new VerticalLayout()); - p3.setContent(new VerticalLayout()); - } - - }); - main.addComponent(b); - b = new Button("move B", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - p2.addComponent(l2); - } - - }); - main.addComponent(b); - b = new Button("move p", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - p3.addComponent(p); - } - - }); - main.addComponent(b); - b = new Button("add to both", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - Label l = new Label("both"); - p.addComponent(l); - p2.addComponent(l); - } - - }); - main.addComponent(b); - b = new Button("recurse", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - try { - p3.addComponent(p2); - getWindow().showNotification("ERROR", - "This should have failed", - Window.Notification.TYPE_ERROR_MESSAGE); - } catch (Exception e) { - getWindow().showNotification("OK", "threw, as expected", - Window.Notification.TYPE_ERROR_MESSAGE); - } - } - - }); - main.addComponent(b); - b = new Button("recurse2", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - Panel p = new Panel("dynamic"); - p.addComponent(p2); - try { - p3.addComponent(p); - getWindow().showNotification("ERROR", - "This should have failed", - Window.Notification.TYPE_ERROR_MESSAGE); - } catch (Exception e) { - getWindow().showNotification("OK", "threw, as expected", - Window.Notification.TYPE_ERROR_MESSAGE); - } - } - - }); - main.addComponent(b); - /* - * And that's it! The framework will display the main window and its - * contents when the application is accessed with the terminal. - */ - } -} +/** + * + */ +package com.vaadin.tests; + +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Panel; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; + +/** + * @author marc + * + */ +public class TestComponentAddAndRecursion extends CustomComponent { + Panel p; + Panel p2; + Label l; + Label l2; + Panel p3; + + public TestComponentAddAndRecursion() { + + VerticalLayout main = new VerticalLayout(); + setCompositionRoot(main); + + l = new Label("A"); + l2 = new Label("B"); + p = new Panel("p"); + p.addComponent(l); + p.addComponent(l2); + main.addComponent(p); + p2 = new Panel("p2"); + p2.addComponent(l); + main.addComponent(p2); + p3 = new Panel("p3"); + p2.addComponent(p3); + + Button b = new Button("use gridlayout", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + p.setContent(new GridLayout()); + p2.setContent(new GridLayout()); + p3.setContent(new GridLayout()); + } + + }); + main.addComponent(b); + b = new Button("use orderedlayout", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + p.setContent(new VerticalLayout()); + p2.setContent(new VerticalLayout()); + p3.setContent(new VerticalLayout()); + } + + }); + main.addComponent(b); + b = new Button("move B", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + p2.addComponent(l2); + } + + }); + main.addComponent(b); + b = new Button("move p", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + p3.addComponent(p); + } + + }); + main.addComponent(b); + b = new Button("add to both", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + Label l = new Label("both"); + p.addComponent(l); + p2.addComponent(l); + } + + }); + main.addComponent(b); + b = new Button("recurse", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + try { + p3.addComponent(p2); + getWindow().showNotification("ERROR", + "This should have failed", + Window.Notification.TYPE_ERROR_MESSAGE); + } catch (Exception e) { + getWindow().showNotification("OK", "threw, as expected", + Window.Notification.TYPE_ERROR_MESSAGE); + } + } + + }); + main.addComponent(b); + b = new Button("recurse2", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + Panel p = new Panel("dynamic"); + p.addComponent(p2); + try { + p3.addComponent(p); + getWindow().showNotification("ERROR", + "This should have failed", + Window.Notification.TYPE_ERROR_MESSAGE); + } catch (Exception e) { + getWindow().showNotification("OK", "threw, as expected", + Window.Notification.TYPE_ERROR_MESSAGE); + } + } + + }); + main.addComponent(b); + /* + * And that's it! The framework will display the main window and its + * contents when the application is accessed with the terminal. + */ + } +} diff --git a/tests/testbench/com/vaadin/tests/TestContainerChanges.java b/tests/testbench/com/vaadin/tests/TestContainerChanges.java index c3a1a98665..b7f24abd8b 100644 --- a/tests/testbench/com/vaadin/tests/TestContainerChanges.java +++ b/tests/testbench/com/vaadin/tests/TestContainerChanges.java @@ -1,212 +1,212 @@ -/** - * - */ -package com.vaadin.tests; - -import com.vaadin.data.Container; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.util.ContainerHierarchicalWrapper; -import com.vaadin.data.util.ContainerOrderedWrapper; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.ComboBox; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.ListSelect; -import com.vaadin.ui.Panel; -import com.vaadin.ui.Table; -import com.vaadin.ui.Tree; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.themes.Reindeer; - -/** - * @author marc - * - */ -public class TestContainerChanges extends CustomComponent { - Container cont = new IndexedContainer(); - Container hierarchical = new ContainerHierarchicalWrapper(cont); - Container ordered = new ContainerOrderedWrapper(cont); - - int cnt = 0; - Table tbl; - - public TestContainerChanges() { - - cont.addContainerProperty("Asd", String.class, "qwe"); - cont.addContainerProperty("Bar", String.class, "foo"); - - VerticalLayout main = new VerticalLayout(); - setCompositionRoot(main); - - main.addComponent(new Label( - "The same IndexedContainer is wrapped in a ordered/hierarchical wrapper and is set as data source for all components . The buttons only affect the 'original' IndexedContainer.")); - - HorizontalLayout h = new HorizontalLayout(); - - main.addComponent(h); - - VerticalLayout v = new VerticalLayout(); - h.addComponent(v); - tbl = new Table(); - tbl.setHeight("200px"); - tbl.setWidth("300px"); - v.addComponent(tbl); - tbl.setSelectable(true); - tbl.setMultiSelect(false); - tbl.setImmediate(true); - tbl.setEditable(true); - tbl.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); - // Original container - tbl.setContainerDataSource(hierarchical); - - Table tbl2 = new Table(); - tbl2.setHeight("200px"); - tbl2.setWidth("300px"); - v.addComponent(tbl2); - tbl2.setSelectable(true); - tbl2.setMultiSelect(false); - tbl2.setImmediate(true); - tbl2.addListener(new Table.ValueChangeListener() { - public void valueChange(ValueChangeEvent event) { - System.err.println("Value now " - + event.getProperty().getValue()); - - } - }); - tbl2.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); - // non-ordered container will get wrapped - tbl2.setContainerDataSource(hierarchical); - - VerticalLayout buttons = new VerticalLayout(); - v.addComponent(buttons); - - Button b = new Button("table.commit()", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - tbl.commit(); - } - - }); - buttons.addComponent(b); - - b = new Button("indexedcontainer.addItem()", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cont.addItem(new Integer(cnt++)); - } - - }); - buttons.addComponent(b); - b = new Button("indexedcontainer.addItem(null)", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cont.addItem(null); - } - - }); - buttons.addComponent(b); - b = new Button("indexedcontainer.removeItem(table.lastItemId()", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cont.removeItem(tbl.lastItemId()); - } - - }); - buttons.addComponent(b); - - b = new Button("indexedcontainer.addContainerProperty()", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cont.addContainerProperty("prop" + cnt, String.class, - "#" + cnt++); - } - - }); - buttons.addComponent(b); - - b = new Button("indexedcontainer.clear()", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cont.removeAllItems(); - } - - }); - buttons.addComponent(b); - b = new Button("table.setContainerDataSource(indexedcontainer)", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - tbl.setContainerDataSource(cont); - } - - }); - buttons.addComponent(b); - b = new Button("table.setContainerDataSource(orderedwrapper)", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - tbl.setContainerDataSource(ordered); - } - - }); - buttons.addComponent(b); - b = new Button("table.setContainerDataSource(hierarchicalwrapper)", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - tbl.setContainerDataSource(hierarchical); - } - - }); - buttons.addComponent(b); - - Panel p = new Panel("Tree"); - p.setStyleName(Reindeer.PANEL_LIGHT); - h.addComponent(p); - Tree tree = new Tree("ITEM_CAPTION_MODE_PROPERTY"); - tree.setContainerDataSource(ordered); - tree.setItemCaptionPropertyId("Asd"); - tree.setItemCaptionMode(Tree.ITEM_CAPTION_MODE_PROPERTY); - p.addComponent(tree); - tree = new Tree("ITEM_CAPTION_MODE_ITEM"); - // nonhierarchical container will get wrapped - tree.setContainerDataSource(ordered); - tree.setItemCaptionMode(Tree.ITEM_CAPTION_MODE_ITEM); - p.addComponent(tree); - - p = new Panel("ComboBox"); - p.setStyleName(Reindeer.PANEL_LIGHT); - h.addComponent(p); - ComboBox c = new ComboBox("ITEM_CAPTION_MODE_PROPERTY"); - c.setImmediate(true); - c.setContainerDataSource(cont); - c.setItemCaptionPropertyId("Asd"); - c.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY); - p.addComponent(c); - c = new ComboBox("ITEM_CAPTION_MODE_ITEM"); - c.setImmediate(true); - c.setContainerDataSource(cont); - c.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM); - p.addComponent(c); - - p = new Panel("ListBox"); - p.setStyleName(Reindeer.PANEL_LIGHT); - h.addComponent(p); - ListSelect l = new ListSelect("ITEM_CAPTION_MODE_PROPERTY"); - l.setContainerDataSource(cont); - l.setItemCaptionPropertyId("Asd"); - l.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY); - p.addComponent(l); - l = new ListSelect("ITEM_CAPTION_MODE_ITEM"); - l.setContainerDataSource(cont); - l.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM); - p.addComponent(l); - } -} +/** + * + */ +package com.vaadin.tests; + +import com.vaadin.data.Container; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.util.ContainerHierarchicalWrapper; +import com.vaadin.data.util.ContainerOrderedWrapper; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.ComboBox; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.ListSelect; +import com.vaadin.ui.Panel; +import com.vaadin.ui.Table; +import com.vaadin.ui.Tree; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.themes.Reindeer; + +/** + * @author marc + * + */ +public class TestContainerChanges extends CustomComponent { + Container cont = new IndexedContainer(); + Container hierarchical = new ContainerHierarchicalWrapper(cont); + Container ordered = new ContainerOrderedWrapper(cont); + + int cnt = 0; + Table tbl; + + public TestContainerChanges() { + + cont.addContainerProperty("Asd", String.class, "qwe"); + cont.addContainerProperty("Bar", String.class, "foo"); + + VerticalLayout main = new VerticalLayout(); + setCompositionRoot(main); + + main.addComponent(new Label( + "The same IndexedContainer is wrapped in a ordered/hierarchical wrapper and is set as data source for all components . The buttons only affect the 'original' IndexedContainer.")); + + HorizontalLayout h = new HorizontalLayout(); + + main.addComponent(h); + + VerticalLayout v = new VerticalLayout(); + h.addComponent(v); + tbl = new Table(); + tbl.setHeight("200px"); + tbl.setWidth("300px"); + v.addComponent(tbl); + tbl.setSelectable(true); + tbl.setMultiSelect(false); + tbl.setImmediate(true); + tbl.setEditable(true); + tbl.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); + // Original container + tbl.setContainerDataSource(hierarchical); + + Table tbl2 = new Table(); + tbl2.setHeight("200px"); + tbl2.setWidth("300px"); + v.addComponent(tbl2); + tbl2.setSelectable(true); + tbl2.setMultiSelect(false); + tbl2.setImmediate(true); + tbl2.addListener(new Table.ValueChangeListener() { + public void valueChange(ValueChangeEvent event) { + System.err.println("Value now " + + event.getProperty().getValue()); + + } + }); + tbl2.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); + // non-ordered container will get wrapped + tbl2.setContainerDataSource(hierarchical); + + VerticalLayout buttons = new VerticalLayout(); + v.addComponent(buttons); + + Button b = new Button("table.commit()", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + tbl.commit(); + } + + }); + buttons.addComponent(b); + + b = new Button("indexedcontainer.addItem()", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cont.addItem(new Integer(cnt++)); + } + + }); + buttons.addComponent(b); + b = new Button("indexedcontainer.addItem(null)", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cont.addItem(null); + } + + }); + buttons.addComponent(b); + b = new Button("indexedcontainer.removeItem(table.lastItemId()", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cont.removeItem(tbl.lastItemId()); + } + + }); + buttons.addComponent(b); + + b = new Button("indexedcontainer.addContainerProperty()", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cont.addContainerProperty("prop" + cnt, String.class, + "#" + cnt++); + } + + }); + buttons.addComponent(b); + + b = new Button("indexedcontainer.clear()", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cont.removeAllItems(); + } + + }); + buttons.addComponent(b); + b = new Button("table.setContainerDataSource(indexedcontainer)", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + tbl.setContainerDataSource(cont); + } + + }); + buttons.addComponent(b); + b = new Button("table.setContainerDataSource(orderedwrapper)", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + tbl.setContainerDataSource(ordered); + } + + }); + buttons.addComponent(b); + b = new Button("table.setContainerDataSource(hierarchicalwrapper)", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + tbl.setContainerDataSource(hierarchical); + } + + }); + buttons.addComponent(b); + + Panel p = new Panel("Tree"); + p.setStyleName(Reindeer.PANEL_LIGHT); + h.addComponent(p); + Tree tree = new Tree("ITEM_CAPTION_MODE_PROPERTY"); + tree.setContainerDataSource(ordered); + tree.setItemCaptionPropertyId("Asd"); + tree.setItemCaptionMode(Tree.ITEM_CAPTION_MODE_PROPERTY); + p.addComponent(tree); + tree = new Tree("ITEM_CAPTION_MODE_ITEM"); + // nonhierarchical container will get wrapped + tree.setContainerDataSource(ordered); + tree.setItemCaptionMode(Tree.ITEM_CAPTION_MODE_ITEM); + p.addComponent(tree); + + p = new Panel("ComboBox"); + p.setStyleName(Reindeer.PANEL_LIGHT); + h.addComponent(p); + ComboBox c = new ComboBox("ITEM_CAPTION_MODE_PROPERTY"); + c.setImmediate(true); + c.setContainerDataSource(cont); + c.setItemCaptionPropertyId("Asd"); + c.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY); + p.addComponent(c); + c = new ComboBox("ITEM_CAPTION_MODE_ITEM"); + c.setImmediate(true); + c.setContainerDataSource(cont); + c.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM); + p.addComponent(c); + + p = new Panel("ListBox"); + p.setStyleName(Reindeer.PANEL_LIGHT); + h.addComponent(p); + ListSelect l = new ListSelect("ITEM_CAPTION_MODE_PROPERTY"); + l.setContainerDataSource(cont); + l.setItemCaptionPropertyId("Asd"); + l.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_PROPERTY); + p.addComponent(l); + l = new ListSelect("ITEM_CAPTION_MODE_ITEM"); + l.setContainerDataSource(cont); + l.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM); + p.addComponent(l); + } +} diff --git a/tests/testbench/com/vaadin/tests/TestDateField.java b/tests/testbench/com/vaadin/tests/TestDateField.java index 2cd47ca568..5997ee0199 100644 --- a/tests/testbench/com/vaadin/tests/TestDateField.java +++ b/tests/testbench/com/vaadin/tests/TestDateField.java @@ -1,74 +1,74 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.tests; - -import java.util.Locale; - -import com.vaadin.terminal.ClassResource; -import com.vaadin.terminal.ErrorMessage; -import com.vaadin.terminal.UserError; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.DateField; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; - -/** - * - * @author Vaadin Ltd. - */ -public class TestDateField extends CustomComponent { - - VerticalLayout main = new VerticalLayout(); - - DateField df; - - public TestDateField() { - setCompositionRoot(main); - createNewView(); - } - - public void createNewView() { - main.removeAllComponents(); - main.addComponent(new Label("DateField")); - - df = new DateField(); - main.addComponent(df); - - final ErrorMessage errorMsg = new UserError("User error " + df); - df.setCaption("DateField caption " + df); - df.setDescription("DateField description " + df); - df.setComponentError(errorMsg); - df.setImmediate(true); - // FIXME: bug #1138 this makes datefield to render with unknown - // component (UIDL tree debug) - df.addStyleName("thisShouldBeHarmless"); - - // Another test: locale - final DateField df1 = new DateField("US locale"); - main.addComponent(df1); - df1.setLocale(new Locale("en", "US")); - - final DateField df2 = new DateField("DE locale"); - main.addComponent(df2); - df2.setLocale(new Locale("de", "DE")); - - final DateField df3 = new DateField("RU locale"); - main.addComponent(df3); - df3.setLocale(new Locale("ru", "RU")); - - final DateField df4 = new DateField("FI locale"); - main.addComponent(df4); - df4.setLocale(new Locale("fi", "FI")); - } - - @Override - public void attach() { - final ClassResource res = new ClassResource("m.gif", - super.getApplication()); - df.setIcon(res); - super.attach(); - } - -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.tests; + +import java.util.Locale; + +import com.vaadin.terminal.ClassResource; +import com.vaadin.terminal.ErrorMessage; +import com.vaadin.terminal.UserError; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.DateField; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; + +/** + * + * @author Vaadin Ltd. + */ +public class TestDateField extends CustomComponent { + + VerticalLayout main = new VerticalLayout(); + + DateField df; + + public TestDateField() { + setCompositionRoot(main); + createNewView(); + } + + public void createNewView() { + main.removeAllComponents(); + main.addComponent(new Label("DateField")); + + df = new DateField(); + main.addComponent(df); + + final ErrorMessage errorMsg = new UserError("User error " + df); + df.setCaption("DateField caption " + df); + df.setDescription("DateField description " + df); + df.setComponentError(errorMsg); + df.setImmediate(true); + // FIXME: bug #1138 this makes datefield to render with unknown + // component (UIDL tree debug) + df.addStyleName("thisShouldBeHarmless"); + + // Another test: locale + final DateField df1 = new DateField("US locale"); + main.addComponent(df1); + df1.setLocale(new Locale("en", "US")); + + final DateField df2 = new DateField("DE locale"); + main.addComponent(df2); + df2.setLocale(new Locale("de", "DE")); + + final DateField df3 = new DateField("RU locale"); + main.addComponent(df3); + df3.setLocale(new Locale("ru", "RU")); + + final DateField df4 = new DateField("FI locale"); + main.addComponent(df4); + df4.setLocale(new Locale("fi", "FI")); + } + + @Override + public void attach() { + final ClassResource res = new ClassResource("m.gif", + super.getApplication()); + df.setIcon(res); + super.attach(); + } + +} diff --git a/tests/testbench/com/vaadin/tests/TestForBasicApplicationLayout.java b/tests/testbench/com/vaadin/tests/TestForBasicApplicationLayout.java index dc6bcd71a3..67370039bb 100644 --- a/tests/testbench/com/vaadin/tests/TestForBasicApplicationLayout.java +++ b/tests/testbench/com/vaadin/tests/TestForBasicApplicationLayout.java @@ -1,101 +1,101 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.tests; - -import java.util.Locale; - -import com.vaadin.terminal.Sizeable; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.DateField; -import com.vaadin.ui.HorizontalSplitPanel; -import com.vaadin.ui.Label; -import com.vaadin.ui.Panel; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.Table; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.themes.Reindeer; - -public class TestForBasicApplicationLayout extends CustomComponent { - - private final Button click; - private final Button click2; - private final TabSheet tab; - - public TestForBasicApplicationLayout() { - - click = new Button("Set height -1", new ClickListener() { - - public void buttonClick(ClickEvent event) { - tab.setHeight(null); - } - - }); - - click2 = new Button("Set height 100%", new ClickListener() { - - public void buttonClick(ClickEvent event) { - tab.setHeight(100, TabSheet.UNITS_PERCENTAGE); - } - - }); - - final HorizontalSplitPanel sp = new HorizontalSplitPanel(); - sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); - - final HorizontalSplitPanel sp2 = new HorizontalSplitPanel(); - sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); - - final Panel p = new Panel("Accordion Panel"); - p.setSizeFull(); - - tab = new TabSheet(); - tab.setSizeFull(); - - final Panel report = new Panel("Monthly Program Runs", - new VerticalLayout()); - final VerticalLayout controls = new VerticalLayout(); - controls.setMargin(true); - controls.addComponent(new Label("Report tab")); - controls.addComponent(click); - controls.addComponent(click2); - report.addComponent(controls); - final DateField cal = new DateField(); - cal.setResolution(DateField.RESOLUTION_DAY); - cal.setLocale(new Locale("en", "US")); - report.addComponent(cal); - ((VerticalLayout) report.getContent()).setExpandRatio(controls, 1); - report.addStyleName(Reindeer.PANEL_LIGHT); - report.setHeight(100, Sizeable.UNITS_PERCENTAGE); - - sp2.setFirstComponent(report); - - final Table table = TestForTablesInitialColumnWidthLogicRendering - .getTestTable(5, 200); - table.setPageLength(15); - table.setSelectable(true); - table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX); - table.setColumnCollapsingAllowed(true); - table.setColumnReorderingAllowed(true); - table.setSortDisabled(false); - table.setSizeFull(); - table.addStyleName("table-inline"); - sp2.setSecondComponent(table); - - tab.addTab(new Label("Tab1"), "Summary", null); - tab.addTab(sp2, "Reports", null); - tab.addTab(new Label("Tab 3"), "Statistics", null); - tab.addTab(new Label("Tab 4"), "Error Tracking", null); - tab.setSelectedTab(sp2); - - sp.setFirstComponent(p); - sp.setSecondComponent(tab); - - setCompositionRoot(sp); - } - -} +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.tests; + +import java.util.Locale; + +import com.vaadin.terminal.Sizeable; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.DateField; +import com.vaadin.ui.HorizontalSplitPanel; +import com.vaadin.ui.Label; +import com.vaadin.ui.Panel; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.Table; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.themes.Reindeer; + +public class TestForBasicApplicationLayout extends CustomComponent { + + private final Button click; + private final Button click2; + private final TabSheet tab; + + public TestForBasicApplicationLayout() { + + click = new Button("Set height -1", new ClickListener() { + + public void buttonClick(ClickEvent event) { + tab.setHeight(null); + } + + }); + + click2 = new Button("Set height 100%", new ClickListener() { + + public void buttonClick(ClickEvent event) { + tab.setHeight(100, TabSheet.UNITS_PERCENTAGE); + } + + }); + + final HorizontalSplitPanel sp = new HorizontalSplitPanel(); + sp.setSplitPosition(290, Sizeable.UNITS_PIXELS); + + final HorizontalSplitPanel sp2 = new HorizontalSplitPanel(); + sp2.setSplitPosition(255, Sizeable.UNITS_PIXELS); + + final Panel p = new Panel("Accordion Panel"); + p.setSizeFull(); + + tab = new TabSheet(); + tab.setSizeFull(); + + final Panel report = new Panel("Monthly Program Runs", + new VerticalLayout()); + final VerticalLayout controls = new VerticalLayout(); + controls.setMargin(true); + controls.addComponent(new Label("Report tab")); + controls.addComponent(click); + controls.addComponent(click2); + report.addComponent(controls); + final DateField cal = new DateField(); + cal.setResolution(DateField.RESOLUTION_DAY); + cal.setLocale(new Locale("en", "US")); + report.addComponent(cal); + ((VerticalLayout) report.getContent()).setExpandRatio(controls, 1); + report.addStyleName(Reindeer.PANEL_LIGHT); + report.setHeight(100, Sizeable.UNITS_PERCENTAGE); + + sp2.setFirstComponent(report); + + final Table table = TestForTablesInitialColumnWidthLogicRendering + .getTestTable(5, 200); + table.setPageLength(15); + table.setSelectable(true); + table.setRowHeaderMode(Table.ROW_HEADER_MODE_INDEX); + table.setColumnCollapsingAllowed(true); + table.setColumnReorderingAllowed(true); + table.setSortDisabled(false); + table.setSizeFull(); + table.addStyleName("table-inline"); + sp2.setSecondComponent(table); + + tab.addTab(new Label("Tab1"), "Summary", null); + tab.addTab(sp2, "Reports", null); + tab.addTab(new Label("Tab 3"), "Statistics", null); + tab.addTab(new Label("Tab 4"), "Error Tracking", null); + tab.setSelectedTab(sp2); + + sp.setFirstComponent(p); + sp.setSecondComponent(tab); + + setCompositionRoot(sp); + } + +} diff --git a/tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java b/tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java index b10752d26c..3d767eb016 100644 --- a/tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java +++ b/tests/testbench/com/vaadin/tests/application/ApplicationCloseTest.java @@ -1,70 +1,70 @@ -package com.vaadin.tests.application; - -import com.vaadin.Application; -import com.vaadin.terminal.gwt.server.WebApplicationContext; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Label; - -public class ApplicationCloseTest extends TestBase { - - private String memoryConsumer; - - @Override - protected void setup() { - Label applications = new Label("Applications in session:
", - Label.CONTENT_XHTML); - for (Application a : ((WebApplicationContext) getContext()) - .getApplications()) { - applications.setValue(applications.getValue() + "App: " + a - + "
"); - } - applications.setValue(applications.getValue() + "

"); - - addComponent(applications); - Label thisApp = new Label("This applications: " + this); - Button close = new Button("Close this", new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - event.getButton().getApplication().close(); - } - }); - - StringBuilder sb = new StringBuilder(); - - // 100 bytes - String str = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; - - int MB = 5; - for (int i = 0; i < MB * 10000; i++) { - sb.append(str); - } - - memoryConsumer = sb.toString(); - long totalUsage = Runtime.getRuntime().totalMemory(); - String totalUsageString = totalUsage / 1000 / 1000 + "MiB"; - Label memoryUsage = new Label( - "Using about " - + memoryConsumer.length() - / 1000 - / 1000 - + "MiB memory for this application.
Total memory usage reported as " - + totalUsageString + "
", Label.CONTENT_XHTML); - - addComponent(thisApp); - addComponent(memoryUsage); - addComponent(close); - } - - @Override - protected String getDescription() { - return "Click close to close the application and open a new one"; - } - - @Override - protected Integer getTicketNumber() { - return 3732; - } - -} +package com.vaadin.tests.application; + +import com.vaadin.Application; +import com.vaadin.terminal.gwt.server.WebApplicationContext; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Label; + +public class ApplicationCloseTest extends TestBase { + + private String memoryConsumer; + + @Override + protected void setup() { + Label applications = new Label("Applications in session:
", + Label.CONTENT_XHTML); + for (Application a : ((WebApplicationContext) getContext()) + .getApplications()) { + applications.setValue(applications.getValue() + "App: " + a + + "
"); + } + applications.setValue(applications.getValue() + "

"); + + addComponent(applications); + Label thisApp = new Label("This applications: " + this); + Button close = new Button("Close this", new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + event.getButton().getApplication().close(); + } + }); + + StringBuilder sb = new StringBuilder(); + + // 100 bytes + String str = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; + + int MB = 5; + for (int i = 0; i < MB * 10000; i++) { + sb.append(str); + } + + memoryConsumer = sb.toString(); + long totalUsage = Runtime.getRuntime().totalMemory(); + String totalUsageString = totalUsage / 1000 / 1000 + "MiB"; + Label memoryUsage = new Label( + "Using about " + + memoryConsumer.length() + / 1000 + / 1000 + + "MiB memory for this application.
Total memory usage reported as " + + totalUsageString + "
", Label.CONTENT_XHTML); + + addComponent(thisApp); + addComponent(memoryUsage); + addComponent(close); + } + + @Override + protected String getDescription() { + return "Click close to close the application and open a new one"; + } + + @Override + protected Integer getTicketNumber() { + return 3732; + } + +} diff --git a/tests/testbench/com/vaadin/tests/application/WebBrowserTest.java b/tests/testbench/com/vaadin/tests/application/WebBrowserTest.java index 31e7534042..4508e4ef90 100644 --- a/tests/testbench/com/vaadin/tests/application/WebBrowserTest.java +++ b/tests/testbench/com/vaadin/tests/application/WebBrowserTest.java @@ -1,98 +1,98 @@ -package com.vaadin.tests.application; - -import java.util.Arrays; -import java.util.Date; -import java.util.TimeZone; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Label; - -public class WebBrowserTest extends TestBase { - - @Override - protected void setup() { - - final Label offsetLabel = new Label("n/a"); - offsetLabel.setCaption("Browser offset"); - - final Label rawOffsetLabel = new Label("n/a"); - rawOffsetLabel.setCaption("Browser raw offset"); - - final Label dstDiffLabel = new Label("n/a"); - dstDiffLabel.setCaption("Difference between raw offset and DST"); - - final Label dstInEffectLabel = new Label("n/a"); - dstInEffectLabel.setCaption("Is DST currently active?"); - - final Label curDateLabel = new Label("n/a"); - curDateLabel.setCaption("Current date in the browser"); - - final Label diffLabel = new Label("n/a"); - diffLabel.setCaption("Browser to Europe/Helsinki offset difference"); - - final Label containsLabel = new Label("n/a"); - containsLabel.setCaption("Browser could be in Helsinki"); - - final Button update = new Button("Get TimeZone from browser", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - TimeZone hkiTZ = TimeZone - .getTimeZone("Europe/Helsinki"); - int hkiOffset = hkiTZ.getOffset(new Date().getTime()); - - int browserOffset = getBrowser().getTimezoneOffset(); - int browserRawOffset = getBrowser() - .getRawTimezoneOffset(); - String[] tzs = TimeZone - .getAvailableIDs(browserRawOffset); - - boolean contains = Arrays.asList(tzs).contains( - hkiTZ.getID()); - - offsetLabel.setValue(String.valueOf(browserOffset)); - - rawOffsetLabel.setValue(String - .valueOf(browserRawOffset)); - - diffLabel.setValue(String.valueOf(browserOffset - - hkiOffset)); - - containsLabel.setValue(contains ? "Yes" : "No"); - - dstDiffLabel.setValue(String.valueOf(getBrowser() - .getDSTSavings())); - - dstInEffectLabel - .setValue(getBrowser().isDSTInEffect() ? "Yes" - : "No"); - - curDateLabel.setValue(getBrowser().getCurrentDate() - .toString()); - - } - }); - - addComponent(update); - addComponent(offsetLabel); - addComponent(rawOffsetLabel); - addComponent(dstDiffLabel); - addComponent(dstInEffectLabel); - addComponent(curDateLabel); - addComponent(diffLabel); - addComponent(containsLabel); - } - - @Override - protected String getDescription() { - return "Verifies that browser TimeZone offset works - should be same as server in our case (NOTE assumes server+browser in same TZ)"; - } - - @Override - protected Integer getTicketNumber() { - return 6691; - } - -} +package com.vaadin.tests.application; + +import java.util.Arrays; +import java.util.Date; +import java.util.TimeZone; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Label; + +public class WebBrowserTest extends TestBase { + + @Override + protected void setup() { + + final Label offsetLabel = new Label("n/a"); + offsetLabel.setCaption("Browser offset"); + + final Label rawOffsetLabel = new Label("n/a"); + rawOffsetLabel.setCaption("Browser raw offset"); + + final Label dstDiffLabel = new Label("n/a"); + dstDiffLabel.setCaption("Difference between raw offset and DST"); + + final Label dstInEffectLabel = new Label("n/a"); + dstInEffectLabel.setCaption("Is DST currently active?"); + + final Label curDateLabel = new Label("n/a"); + curDateLabel.setCaption("Current date in the browser"); + + final Label diffLabel = new Label("n/a"); + diffLabel.setCaption("Browser to Europe/Helsinki offset difference"); + + final Label containsLabel = new Label("n/a"); + containsLabel.setCaption("Browser could be in Helsinki"); + + final Button update = new Button("Get TimeZone from browser", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + TimeZone hkiTZ = TimeZone + .getTimeZone("Europe/Helsinki"); + int hkiOffset = hkiTZ.getOffset(new Date().getTime()); + + int browserOffset = getBrowser().getTimezoneOffset(); + int browserRawOffset = getBrowser() + .getRawTimezoneOffset(); + String[] tzs = TimeZone + .getAvailableIDs(browserRawOffset); + + boolean contains = Arrays.asList(tzs).contains( + hkiTZ.getID()); + + offsetLabel.setValue(String.valueOf(browserOffset)); + + rawOffsetLabel.setValue(String + .valueOf(browserRawOffset)); + + diffLabel.setValue(String.valueOf(browserOffset + - hkiOffset)); + + containsLabel.setValue(contains ? "Yes" : "No"); + + dstDiffLabel.setValue(String.valueOf(getBrowser() + .getDSTSavings())); + + dstInEffectLabel + .setValue(getBrowser().isDSTInEffect() ? "Yes" + : "No"); + + curDateLabel.setValue(getBrowser().getCurrentDate() + .toString()); + } + }); + + addComponent(update); + addComponent(offsetLabel); + addComponent(rawOffsetLabel); + addComponent(dstDiffLabel); + addComponent(dstInEffectLabel); + addComponent(curDateLabel); + addComponent(diffLabel); + addComponent(containsLabel); + + } + + @Override + protected String getDescription() { + return "Verifies that browser TimeZone offset works - should be same as server in our case (NOTE assumes server+browser in same TZ)"; + } + + @Override + protected Integer getTicketNumber() { + return 6691; + } + +} diff --git a/tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java b/tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java index ddbbc49e68..c0141a72d5 100644 --- a/tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java +++ b/tests/testbench/com/vaadin/tests/applicationcontext/ChangeSessionId.java @@ -1,69 +1,69 @@ -package com.vaadin.tests.applicationcontext; - -import com.vaadin.terminal.gwt.server.WebApplicationContext; -import com.vaadin.tests.components.AbstractTestCase; -import com.vaadin.tests.util.Log; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.Window; - -public class ChangeSessionId extends AbstractTestCase { - - private Log log = new Log(5); - Button loginButton = new Button("Change session"); - boolean requestSessionSwitch = false; - - @Override - public void init() { - Window mainWindow = new Window("Sestest Application"); - mainWindow.addComponent(log); - mainWindow.addComponent(loginButton); - mainWindow.addComponent(new Button("Show session id", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - logSessionId(); - } - })); - setMainWindow(mainWindow); - - loginButton.addListener(new ClickListener() { - public void buttonClick(ClickEvent event) { - WebApplicationContext context = ((WebApplicationContext) getContext()); - - String oldSessionId = context.getHttpSession().getId(); - context.reinitializeSession(); - String newSessionId = context.getHttpSession().getId(); - if (oldSessionId.equals(newSessionId)) { - log.log("FAILED! Both old and new session id is " - + newSessionId); - } else { - log.log("Session id changed successfully from " - + oldSessionId + " to " + newSessionId); - } - - } - }); - logSessionId(); - } - - private void logSessionId() { - log.log("Session id: " + getSessionId()); - } - - protected String getSessionId() { - return ((WebApplicationContext) getContext()).getHttpSession().getId(); - } - - @Override - protected String getDescription() { - return "Tests that the session id can be changed to prevent session fixation attacks"; - } - - @Override - protected Integer getTicketNumber() { - return 6094; - } - +package com.vaadin.tests.applicationcontext; + +import com.vaadin.terminal.gwt.server.WebApplicationContext; +import com.vaadin.tests.components.AbstractTestCase; +import com.vaadin.tests.util.Log; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.Window; + +public class ChangeSessionId extends AbstractTestCase { + + private Log log = new Log(5); + Button loginButton = new Button("Change session"); + boolean requestSessionSwitch = false; + + @Override + public void init() { + Window mainWindow = new Window("Sestest Application"); + mainWindow.addComponent(log); + mainWindow.addComponent(loginButton); + mainWindow.addComponent(new Button("Show session id", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + logSessionId(); + } + })); + setMainWindow(mainWindow); + + loginButton.addListener(new ClickListener() { + public void buttonClick(ClickEvent event) { + WebApplicationContext context = ((WebApplicationContext) getContext()); + + String oldSessionId = context.getHttpSession().getId(); + context.reinitializeSession(); + String newSessionId = context.getHttpSession().getId(); + if (oldSessionId.equals(newSessionId)) { + log.log("FAILED! Both old and new session id is " + + newSessionId); + } else { + log.log("Session id changed successfully from " + + oldSessionId + " to " + newSessionId); + } + + } + }); + logSessionId(); + } + + private void logSessionId() { + log.log("Session id: " + getSessionId()); + } + + protected String getSessionId() { + return ((WebApplicationContext) getContext()).getHttpSession().getId(); + } + + @Override + protected String getDescription() { + return "Tests that the session id can be changed to prevent session fixation attacks"; + } + + @Override + protected Integer getTicketNumber() { + return 6094; + } + } \ No newline at end of file diff --git a/tests/testbench/com/vaadin/tests/applicationservlet/NoMainWindow.java b/tests/testbench/com/vaadin/tests/applicationservlet/NoMainWindow.java index 9097274236..fc72b86a34 100644 --- a/tests/testbench/com/vaadin/tests/applicationservlet/NoMainWindow.java +++ b/tests/testbench/com/vaadin/tests/applicationservlet/NoMainWindow.java @@ -1,22 +1,22 @@ -package com.vaadin.tests.applicationservlet; - -import com.vaadin.tests.components.AbstractTestCase; - -public class NoMainWindow extends AbstractTestCase { - - @Override - protected String getDescription() { - return "This should produce an stack trace with \"No window found. Did you remember to setMainWindow()?\""; - } - - @Override - protected Integer getTicketNumber() { - return 3349; - } - - @Override - public void init() { - - } - -} +package com.vaadin.tests.applicationservlet; + +import com.vaadin.tests.components.AbstractTestCase; + +public class NoMainWindow extends AbstractTestCase { + + @Override + protected String getDescription() { + return "This should produce an stack trace with \"No window found. Did you remember to setMainWindow()?\""; + } + + @Override + protected Integer getTicketNumber() { + return 3349; + } + + @Override + public void init() { + + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java b/tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java index 0c9c9c4ae2..2a98988487 100644 --- a/tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractComponentContainerTest.java @@ -1,356 +1,356 @@ -package com.vaadin.tests.components; - -import java.util.Iterator; -import java.util.LinkedHashMap; - -import com.vaadin.ui.AbstractComponentContainer; -import com.vaadin.ui.Button; -import com.vaadin.ui.Component; -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.HorizontalSplitPanel; -import com.vaadin.ui.InlineDateField; -import com.vaadin.ui.NativeButton; -import com.vaadin.ui.PopupDateField; -import com.vaadin.ui.RichTextArea; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.Table; -import com.vaadin.ui.TextArea; -import com.vaadin.ui.TextField; -import com.vaadin.ui.VerticalSplitPanel; - -public abstract class AbstractComponentContainerTest - extends AbstractComponentTest implements ComponentAttachListener, - ComponentDetachListener { - - private String CATEGORY_COMPONENT_CONTAINER_FEATURES = "Component container features"; - private Command addButtonCommand = new Command() { - - public void execute(T c, ComponentSize size, Object data) { - Button b = new Button("A button"); - c.addComponent(b); - size.apply(b); - } - }; - - private Command addNativeButtonCommand = new Command() { - - public void execute(T c, ComponentSize size, Object data) { - NativeButton b = new NativeButton("Native button"); - c.addComponent(b); - size.apply(b); - } - }; - - private Command addTextAreaCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - TextArea ta = new TextArea(); - c.addComponent(ta); - size.apply(ta); - } - }; - - private Command addRichTextAreaCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - RichTextArea ta = new RichTextArea(); - c.addComponent(ta); - size.apply(ta); - } - }; - - private Command addTextFieldCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - TextField tf = new TextField(); - c.addComponent(tf); - size.apply(tf); - } - }; - - private Command addInlineDateFieldCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - InlineDateField tf = new InlineDateField(); - c.addComponent(tf); - size.apply(tf); - } - }; - private Command addPopupDateFieldCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - PopupDateField tf = new PopupDateField(); - c.addComponent(tf); - size.apply(tf); - } - }; - - private Command addVerticalSplitPanelCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - VerticalSplitPanel vsp = new VerticalSplitPanel(); - c.addComponent(vsp); - size.apply(vsp); - } - }; - - private Command addHorizontalSplitPanelCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - HorizontalSplitPanel vsp = new HorizontalSplitPanel(); - c.addComponent(vsp); - size.apply(vsp); - } - }; - - private Command addTabSheetCommand = new Command() { - public void execute(T c, ComponentSize size, Object data) { - TabSheet ts = createTabSheet(); - c.addComponent(ts); - size.apply(ts); - } - }; - - private Command addTableCommand = new Command() { - - public void execute(T c, ComponentSize size, Object data) { - Table t = createTable(); - c.addComponent(t); - size.apply(t); - } - }; - private Command removeAllComponentsCommand = new Command() { - public void execute(T c, Object value, Object data) { - c.removeAllComponents(); - } - }; - private Command removeComponentByIndexCommand = new Command() { - - public void execute(T c, Integer value, Object data) { - Component child = getComponentAtIndex(c, value); - c.removeComponent(child); - - } - }; - private Command componentAttachListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ComponentAttachListener) AbstractComponentContainerTest.this); - } else { - c.removeListener((ComponentAttachListener) AbstractComponentContainerTest.this); - } - } - }; - - private Command componentDetachListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ComponentDetachListener) AbstractComponentContainerTest.this); - } else { - c.removeListener((ComponentDetachListener) AbstractComponentContainerTest.this); - } - } - }; - - private Command setComponentHeight = new Command() { - - public void execute(T c, Integer value, Object data) { - Component child = getComponentAtIndex(c, value); - child.setHeight((String) data); - - } - }; - - private Command setComponentWidth = new Command() { - - public void execute(T c, Integer value, Object data) { - Component child = getComponentAtIndex(c, value); - child.setWidth((String) data); - - } - }; - - protected static class ComponentSize { - private String width, height; - - public ComponentSize(String width, String height) { - this.width = width; - this.height = height; - } - - public void apply(Component target) { - target.setWidth(width); - target.setHeight(height); - } - - public String getWidth() { - return width; - } - - public String getHeight() { - return height; - } - - @Override - public String toString() { - String s = ""; - s += width == null ? "auto" : width; - s += " x "; - s += height == null ? "auto" : height; - return s; - } - } - - @Override - protected void createActions() { - super.createActions(); - - createAddComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES); - createRemoveComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES); - createChangeComponentSizeActions(CATEGORY_COMPONENT_CONTAINER_FEATURES); - createComponentAttachListener(CATEGORY_LISTENERS); - createComponentDetachListener(CATEGORY_LISTENERS); - } - - protected Component getComponentAtIndex(T container, int value) { - Iterator iter = container.getComponentIterator(); - for (int i = 0; i < value; i++) { - iter.next(); - } - - return iter.next(); - } - - protected Table createTable() { - Table t = new Table(); - t.addContainerProperty("property 1", String.class, ""); - t.addContainerProperty("property 2", String.class, ""); - t.addContainerProperty("property 3", String.class, ""); - for (int i = 1; i < 10; i++) { - t.addItem(new Object[] { "row/col " + i + "/1", - "row/col " + i + "/2", "row/col " + i + "/3" }, - String.valueOf(i)); - } - return t; - } - - protected TabSheet createTabSheet() { - TabSheet ts = new TabSheet(); - Table t = createTable(); - t.setSizeFull(); - ts.addTab(t, "Size full Table", ICON_16_USER_PNG_UNCACHEABLE); - ts.addTab(new Button("A button"), "Button", null); - return ts; - } - - private void createComponentAttachListener(String category) { - createBooleanAction("Component attach listener", category, false, - componentAttachListenerCommand); - - } - - private void createComponentDetachListener(String category) { - createBooleanAction("Component detach listener", category, false, - componentDetachListenerCommand); - - } - - private void createRemoveComponentActions(String category) { - String subCategory = "Remove component"; - String byIndexCategory = "By index"; - - createCategory(subCategory, category); - createCategory(byIndexCategory, subCategory); - createClickAction("Remove all components", subCategory, - removeAllComponentsCommand, null); - for (int i = 0; i < 20; i++) { - createClickAction("Remove component " + i, byIndexCategory, - removeComponentByIndexCommand, Integer.valueOf(i)); - } - - } - - private void createAddComponentActions(String category) { - String subCategory = "Add component"; - createCategory(subCategory, category); - - LinkedHashMap> addCommands = new LinkedHashMap>(); - addCommands.put("Button", addButtonCommand); - addCommands.put("NativeButton", addNativeButtonCommand); - addCommands.put("TextField", addTextFieldCommand); - addCommands.put("TextArea", addTextAreaCommand); - addCommands.put("RichTextArea", addRichTextAreaCommand); - addCommands.put("TabSheet", addTabSheetCommand); - addCommands.put("Table", addTableCommand); - addCommands.put("InlineDateField", addInlineDateFieldCommand); - addCommands.put("PopupDateField", addPopupDateFieldCommand); - addCommands.put("VerticalSplitPanel", addVerticalSplitPanelCommand); - addCommands.put("HorizontalSplitPanel", addHorizontalSplitPanelCommand); - // addCommands.put("AbsoluteLayout", addAbsoluteLayoutCommand); - // addCommands.put("HorizontalLayout", addHorizontalLayoutCommand); - // addCommands.put("VerticalLayout", addVerticalLayoutCommand); - - ComponentSize[] sizes = new ComponentSize[] { - new ComponentSize(null, null), - new ComponentSize("200px", null), - new ComponentSize("100%", null), - new ComponentSize(null, "200px"), - new ComponentSize(null, "100%"), - new ComponentSize("300px", "300px"), - new ComponentSize("100%", "100%"), - - }; - - for (String componentCategory : addCommands.keySet()) { - createCategory(componentCategory, subCategory); - - for (ComponentSize size : sizes) { - createClickAction(size.toString(), componentCategory, - addCommands.get(componentCategory), size); - } - } - - } - - private void createChangeComponentSizeActions(String category) { - String widthCategory = "Change component width"; - createCategory(widthCategory, category); - String heightCategory = "Change component height"; - createCategory(heightCategory, category); - - String[] options = new String[] { "100px", "200px", "50%", "100%" }; - for (int i = 0; i < 20; i++) { - String componentWidthCategory = "Component " + i + " width"; - String componentHeightCategory = "Component " + i + " height"; - createCategory(componentWidthCategory, widthCategory); - createCategory(componentHeightCategory, heightCategory); - - createClickAction("auto", componentHeightCategory, - setComponentHeight, Integer.valueOf(i), null); - createClickAction("auto", componentWidthCategory, - setComponentWidth, Integer.valueOf(i), null); - for (String option : options) { - createClickAction(option, componentHeightCategory, - setComponentHeight, Integer.valueOf(i), option); - createClickAction(option, componentWidthCategory, - setComponentWidth, Integer.valueOf(i), option); - } - - } - - } - - public void componentDetachedFromContainer(ComponentDetachEvent event) { - log(event.getClass().getSimpleName() + ": " - + event.getDetachedComponent().getClass().getSimpleName() - + " detached from " - + event.getContainer().getClass().getSimpleName()); - } - - public void componentAttachedToContainer(ComponentAttachEvent event) { - log(event.getClass().getSimpleName() + ": " - + event.getAttachedComponent().getClass().getSimpleName() - + " attached to " - + event.getContainer().getClass().getSimpleName()); - - } - -} +package com.vaadin.tests.components; + +import java.util.Iterator; +import java.util.LinkedHashMap; + +import com.vaadin.ui.AbstractComponentContainer; +import com.vaadin.ui.Button; +import com.vaadin.ui.Component; +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.HorizontalSplitPanel; +import com.vaadin.ui.InlineDateField; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.PopupDateField; +import com.vaadin.ui.RichTextArea; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.Table; +import com.vaadin.ui.TextArea; +import com.vaadin.ui.TextField; +import com.vaadin.ui.VerticalSplitPanel; + +public abstract class AbstractComponentContainerTest + extends AbstractComponentTest implements ComponentAttachListener, + ComponentDetachListener { + + private String CATEGORY_COMPONENT_CONTAINER_FEATURES = "Component container features"; + private Command addButtonCommand = new Command() { + + public void execute(T c, ComponentSize size, Object data) { + Button b = new Button("A button"); + c.addComponent(b); + size.apply(b); + } + }; + + private Command addNativeButtonCommand = new Command() { + + public void execute(T c, ComponentSize size, Object data) { + NativeButton b = new NativeButton("Native button"); + c.addComponent(b); + size.apply(b); + } + }; + + private Command addTextAreaCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + TextArea ta = new TextArea(); + c.addComponent(ta); + size.apply(ta); + } + }; + + private Command addRichTextAreaCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + RichTextArea ta = new RichTextArea(); + c.addComponent(ta); + size.apply(ta); + } + }; + + private Command addTextFieldCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + TextField tf = new TextField(); + c.addComponent(tf); + size.apply(tf); + } + }; + + private Command addInlineDateFieldCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + InlineDateField tf = new InlineDateField(); + c.addComponent(tf); + size.apply(tf); + } + }; + private Command addPopupDateFieldCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + PopupDateField tf = new PopupDateField(); + c.addComponent(tf); + size.apply(tf); + } + }; + + private Command addVerticalSplitPanelCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + VerticalSplitPanel vsp = new VerticalSplitPanel(); + c.addComponent(vsp); + size.apply(vsp); + } + }; + + private Command addHorizontalSplitPanelCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + HorizontalSplitPanel vsp = new HorizontalSplitPanel(); + c.addComponent(vsp); + size.apply(vsp); + } + }; + + private Command addTabSheetCommand = new Command() { + public void execute(T c, ComponentSize size, Object data) { + TabSheet ts = createTabSheet(); + c.addComponent(ts); + size.apply(ts); + } + }; + + private Command addTableCommand = new Command() { + + public void execute(T c, ComponentSize size, Object data) { + Table t = createTable(); + c.addComponent(t); + size.apply(t); + } + }; + private Command removeAllComponentsCommand = new Command() { + public void execute(T c, Object value, Object data) { + c.removeAllComponents(); + } + }; + private Command removeComponentByIndexCommand = new Command() { + + public void execute(T c, Integer value, Object data) { + Component child = getComponentAtIndex(c, value); + c.removeComponent(child); + + } + }; + private Command componentAttachListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ComponentAttachListener) AbstractComponentContainerTest.this); + } else { + c.removeListener((ComponentAttachListener) AbstractComponentContainerTest.this); + } + } + }; + + private Command componentDetachListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ComponentDetachListener) AbstractComponentContainerTest.this); + } else { + c.removeListener((ComponentDetachListener) AbstractComponentContainerTest.this); + } + } + }; + + private Command setComponentHeight = new Command() { + + public void execute(T c, Integer value, Object data) { + Component child = getComponentAtIndex(c, value); + child.setHeight((String) data); + + } + }; + + private Command setComponentWidth = new Command() { + + public void execute(T c, Integer value, Object data) { + Component child = getComponentAtIndex(c, value); + child.setWidth((String) data); + + } + }; + + protected static class ComponentSize { + private String width, height; + + public ComponentSize(String width, String height) { + this.width = width; + this.height = height; + } + + public void apply(Component target) { + target.setWidth(width); + target.setHeight(height); + } + + public String getWidth() { + return width; + } + + public String getHeight() { + return height; + } + + @Override + public String toString() { + String s = ""; + s += width == null ? "auto" : width; + s += " x "; + s += height == null ? "auto" : height; + return s; + } + } + + @Override + protected void createActions() { + super.createActions(); + + createAddComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES); + createRemoveComponentActions(CATEGORY_COMPONENT_CONTAINER_FEATURES); + createChangeComponentSizeActions(CATEGORY_COMPONENT_CONTAINER_FEATURES); + createComponentAttachListener(CATEGORY_LISTENERS); + createComponentDetachListener(CATEGORY_LISTENERS); + } + + protected Component getComponentAtIndex(T container, int value) { + Iterator iter = container.getComponentIterator(); + for (int i = 0; i < value; i++) { + iter.next(); + } + + return iter.next(); + } + + protected Table createTable() { + Table t = new Table(); + t.addContainerProperty("property 1", String.class, ""); + t.addContainerProperty("property 2", String.class, ""); + t.addContainerProperty("property 3", String.class, ""); + for (int i = 1; i < 10; i++) { + t.addItem(new Object[] { "row/col " + i + "/1", + "row/col " + i + "/2", "row/col " + i + "/3" }, + String.valueOf(i)); + } + return t; + } + + protected TabSheet createTabSheet() { + TabSheet ts = new TabSheet(); + Table t = createTable(); + t.setSizeFull(); + ts.addTab(t, "Size full Table", ICON_16_USER_PNG_UNCACHEABLE); + ts.addTab(new Button("A button"), "Button", null); + return ts; + } + + private void createComponentAttachListener(String category) { + createBooleanAction("Component attach listener", category, false, + componentAttachListenerCommand); + + } + + private void createComponentDetachListener(String category) { + createBooleanAction("Component detach listener", category, false, + componentDetachListenerCommand); + + } + + private void createRemoveComponentActions(String category) { + String subCategory = "Remove component"; + String byIndexCategory = "By index"; + + createCategory(subCategory, category); + createCategory(byIndexCategory, subCategory); + createClickAction("Remove all components", subCategory, + removeAllComponentsCommand, null); + for (int i = 0; i < 20; i++) { + createClickAction("Remove component " + i, byIndexCategory, + removeComponentByIndexCommand, Integer.valueOf(i)); + } + + } + + private void createAddComponentActions(String category) { + String subCategory = "Add component"; + createCategory(subCategory, category); + + LinkedHashMap> addCommands = new LinkedHashMap>(); + addCommands.put("Button", addButtonCommand); + addCommands.put("NativeButton", addNativeButtonCommand); + addCommands.put("TextField", addTextFieldCommand); + addCommands.put("TextArea", addTextAreaCommand); + addCommands.put("RichTextArea", addRichTextAreaCommand); + addCommands.put("TabSheet", addTabSheetCommand); + addCommands.put("Table", addTableCommand); + addCommands.put("InlineDateField", addInlineDateFieldCommand); + addCommands.put("PopupDateField", addPopupDateFieldCommand); + addCommands.put("VerticalSplitPanel", addVerticalSplitPanelCommand); + addCommands.put("HorizontalSplitPanel", addHorizontalSplitPanelCommand); + // addCommands.put("AbsoluteLayout", addAbsoluteLayoutCommand); + // addCommands.put("HorizontalLayout", addHorizontalLayoutCommand); + // addCommands.put("VerticalLayout", addVerticalLayoutCommand); + + ComponentSize[] sizes = new ComponentSize[] { + new ComponentSize(null, null), + new ComponentSize("200px", null), + new ComponentSize("100%", null), + new ComponentSize(null, "200px"), + new ComponentSize(null, "100%"), + new ComponentSize("300px", "300px"), + new ComponentSize("100%", "100%"), + + }; + + for (String componentCategory : addCommands.keySet()) { + createCategory(componentCategory, subCategory); + + for (ComponentSize size : sizes) { + createClickAction(size.toString(), componentCategory, + addCommands.get(componentCategory), size); + } + } + + } + + private void createChangeComponentSizeActions(String category) { + String widthCategory = "Change component width"; + createCategory(widthCategory, category); + String heightCategory = "Change component height"; + createCategory(heightCategory, category); + + String[] options = new String[] { "100px", "200px", "50%", "100%" }; + for (int i = 0; i < 20; i++) { + String componentWidthCategory = "Component " + i + " width"; + String componentHeightCategory = "Component " + i + " height"; + createCategory(componentWidthCategory, widthCategory); + createCategory(componentHeightCategory, heightCategory); + + createClickAction("auto", componentHeightCategory, + setComponentHeight, Integer.valueOf(i), null); + createClickAction("auto", componentWidthCategory, + setComponentWidth, Integer.valueOf(i), null); + for (String option : options) { + createClickAction(option, componentHeightCategory, + setComponentHeight, Integer.valueOf(i), option); + createClickAction(option, componentWidthCategory, + setComponentWidth, Integer.valueOf(i), option); + } + + } + + } + + public void componentDetachedFromContainer(ComponentDetachEvent event) { + log(event.getClass().getSimpleName() + ": " + + event.getDetachedComponent().getClass().getSimpleName() + + " detached from " + + event.getContainer().getClass().getSimpleName()); + } + + public void componentAttachedToContainer(ComponentAttachEvent event) { + log(event.getClass().getSimpleName() + ": " + + event.getAttachedComponent().getClass().getSimpleName() + + " attached to " + + event.getContainer().getClass().getSimpleName()); + + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java b/tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java index 8344ed216a..fe61df8913 100644 --- a/tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractComponentTest.java @@ -1,671 +1,671 @@ -package com.vaadin.tests.components; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import com.vaadin.terminal.Resource; -import com.vaadin.terminal.ThemeResource; -import com.vaadin.tests.util.Log; -import com.vaadin.tests.util.LoremIpsum; -import com.vaadin.ui.AbstractComponent; -import com.vaadin.ui.MenuBar; -import com.vaadin.ui.MenuBar.MenuItem; - -public abstract class AbstractComponentTest - extends AbstractComponentTestCase { - - protected static final String TEXT_SHORT = "Short"; - protected static final String TEXT_MEDIUM = "This is a semi-long text that might wrap."; - protected static final String TEXT_LONG = "This is a long text. " - + LoremIpsum.get(500); - protected static final String TEXT_VERY_LONG = "This is a very, very long text. " - + LoremIpsum.get(5000); - - private static final Resource SELECTED_ICON = new ThemeResource( - "../runo/icons/16/ok.png"); - - private static final LinkedHashMap sizeOptions = new LinkedHashMap(); - static { - sizeOptions.put("auto", null); - sizeOptions.put("50%", "50%"); - sizeOptions.put("100%", "100%"); - for (int w = 200; w < 1000; w += 100) { - sizeOptions.put(w + "px", w + "px"); - } - } - - // Menu related - - private MenuItem mainMenu; - - private MenuBar menu; - - private MenuItem settingsMenu; - - private T component; - - // Used to determine if a menuItem should be selected and the other - // unselected on click - private Set parentOfSelectableMenuItem = new HashSet(); - - /** - * Maps the category name to a menu item - */ - private Map categoryToMenuItem = new HashMap(); - private Map menuItemToCategory = new HashMap(); - - // Logging - private Log log; - - protected static final String CATEGORY_STATE = "State"; - protected static final String CATEGORY_SIZE = "Size"; - protected static final String CATEGORY_SELECTION = "Selection"; - protected static final String CATEGORY_LISTENERS = "Listeners"; - protected static final String CATEGORY_FEATURES = "Features"; - protected static final String CATEGORY_ACTIONS = "Actions"; - protected static final String CATEGORY_DECORATIONS = "Decorations"; - - @Override - protected final void setup() { - setTheme("tests-components"); - - // Create menu here so it appears before the components - addComponent(createMainMenu()); - - getLayout().setSizeFull(); - createLog(); - super.setup(); - - // Create menu actions and trigger default actions - createActions(); - - // Clear initialization log messages - log.clear(); - } - - private MenuBar createMainMenu() { - menu = new MenuBar(); - menu.setDebugId("menu"); - mainMenu = menu.addItem("Component", null); - settingsMenu = menu.addItem("Settings", null); - populateSettingsMenu(settingsMenu); - - return menu; - } - - /** - * Override to add items to the "settings" menu. - * - * NOTE, Call super class first to preserve current order. If you override - * this in a class and another class overrides it you might break tests - * because the wrong items will be selected. - * - * @param settingsMenu - */ - protected void populateSettingsMenu(MenuItem settingsMenu) { - - MenuItem showEventLog = settingsMenu.addItem("Show event log", - new MenuBar.Command() { - - public void menuSelected(MenuItem selectedItem) { - boolean selected = !isSelected(selectedItem); - setLogVisible(selected); - setSelected(selectedItem, selected); - } - - }); - setSelected(showEventLog, true); - - settingsMenu.addItem("Clear log", new MenuBar.Command() { - - public void menuSelected(MenuItem selectedItem) { - log.clear(); - } - }); - MenuItem layoutSize = settingsMenu.addItem("Parent layout size", null); - MenuItem layoutWidth = layoutSize.addItem("Width", null); - MenuItem layoutHeight = layoutSize.addItem("Height", null); - for (final String name : sizeOptions.keySet()) { - layoutWidth.addItem(name, new MenuBar.Command() { - public void menuSelected(MenuItem selectedItem) { - getTestComponents().get(0).getParent() - .setWidth(sizeOptions.get(name)); - log("Parent layout width set to " + name); - } - }); - layoutHeight.addItem(name, new MenuBar.Command() { - public void menuSelected(MenuItem selectedItem) { - getTestComponents().get(0).getParent() - .setHeight(sizeOptions.get(name)); - log("Parent layout height set to " + name); - } - }); - } - - } - - protected void setLogVisible(boolean visible) { - log.setVisible(visible); - } - - private void createLog() { - log = new Log(5).setNumberLogRows(true); - getLayout().addComponent(log, 1); - } - - /** - * By default initializes just one instance of {@link #getTestClass()} using - * {@link #constructComponent()}. - */ - @Override - protected void initializeComponents() { - component = constructComponent(); - component.setDebugId("testComponent"); - addTestComponent(component); - } - - public T getComponent() { - return component; - } - - @Override - protected void addTestComponent(T c) { - super.addTestComponent(c); - getLayout().setExpandRatio(c, 1); - - }; - - /** - * Construct the component that is to be tested. This method uses a no-arg - * constructor by default. Override to customize. - * - * @return Instance of the component that is to be tested. - * @throws IllegalAccessException - * @throws InstantiationException - */ - protected T constructComponent() { - try { - return getTestClass().newInstance(); - } catch (Exception e) { - throw new RuntimeException("Failed to instantiate " - + getTestClass(), e); - } - } - - /** - * Create actions for the component. Remember to call super.createActions() - * when overriding. - */ - protected void createActions() { - createBooleanAction("Immediate", CATEGORY_STATE, true, immediateCommand); - createBooleanAction("Enabled", CATEGORY_STATE, true, enabledCommand); - createBooleanAction("Readonly", CATEGORY_STATE, false, readonlyCommand); - createBooleanAction("Visible", CATEGORY_STATE, true, visibleCommand); - createBooleanAction("Error indicator", CATEGORY_STATE, false, - errorIndicatorCommand); - createLocaleSelect(CATEGORY_STATE); - createErrorMessageSelect(CATEGORY_DECORATIONS); - - createDescriptionSelect(CATEGORY_DECORATIONS); - createCaptionSelect(CATEGORY_DECORATIONS); - createIconSelect(CATEGORY_DECORATIONS); - - createWidthAndHeightActions(CATEGORY_SIZE); - - createStyleNameSelect(CATEGORY_DECORATIONS); - - } - - private void createStyleNameSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put("Light blue background (background-lightblue)", - "background-lightblue"); - options.put("1px red border (border-red-1px)", "border-red-1px"); - options.put("2px blue border (border-blue-2px)", "border-blue-2px"); - createComponentStyleNames(options); - createSelectAction("Style name", category, options, "-", - styleNameCommand); - - } - - protected void createComponentStyleNames( - LinkedHashMap options) { - - } - - private void createErrorMessageSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put(TEXT_SHORT, TEXT_SHORT); - options.put("Medium", TEXT_MEDIUM); - options.put("Long", TEXT_LONG); - options.put("Very long", TEXT_VERY_LONG); - createSelectAction("Error message", category, options, "-", - errorMessageCommand); - - } - - private void createDescriptionSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put(TEXT_SHORT, TEXT_SHORT); - options.put("Medium", TEXT_MEDIUM); - options.put("Long", TEXT_LONG); - options.put("Very long", TEXT_VERY_LONG); - createSelectAction("Description / tooltip", category, options, "-", - descriptionCommand); - - } - - private void createCaptionSelect(String category) { - createSelectAction("Caption", category, createCaptionOptions(), - "Short", captionCommand); - - } - - protected LinkedHashMap createCaptionOptions() { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put("Short", TEXT_SHORT); - options.put("Medium", TEXT_MEDIUM); - options.put("Long", TEXT_LONG); - options.put("Very long", TEXT_VERY_LONG); - return options; - } - - private void createWidthAndHeightActions(String category) { - String widthCategory = "Width"; - String heightCategory = "Height"; - - createCategory(widthCategory, category); - createCategory(heightCategory, category); - - for (String name : sizeOptions.keySet()) { - createClickAction(name, widthCategory, widthCommand, - sizeOptions.get(name)); - createClickAction(name, heightCategory, heightCommand, - sizeOptions.get(name)); - } - - // Default to undefined size - for (T c : getTestComponents()) { - c.setWidth(null); - c.setHeight(null); - } - } - - private void createIconSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put("16x16", ICON_16_USER_PNG_CACHEABLE); - options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE); - options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE); - - createSelectAction("Icon", category, options, "-", iconCommand, null); - } - - private void createLocaleSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put("fi_FI", new Locale("fi", "FI")); - options.put("en_US", Locale.US); - options.put("zh_CN", Locale.SIMPLIFIED_CHINESE); - options.put("fr_FR", Locale.FRANCE); - - createSelectAction("Locale", category, options, "en_US", localeCommand, - null); - } - - protected void createBooleanAction(String caption, String category, - boolean initialState, final Command command) { - createBooleanAction(caption, category, initialState, command, null); - } - - protected void createBooleanAction(String caption, - String category, boolean initialState, - final Command command, Object data) { - MenuItem categoryItem = getCategoryMenuItem(category); - MenuItem item = categoryItem.addItem(caption, - menuBooleanCommand(command, data)); - setSelected(item, initialState); - doCommand(caption, command, initialState, data); - } - - protected void createClickAction(String caption, - String category, final Command command, DATATYPE value) { - createClickAction(caption, category, command, value, null); - } - - protected void createClickAction(String caption, - String category, final Command command, - DATATYPE value, Object data) { - MenuItem categoryItem = getCategoryMenuItem(category); - categoryItem.addItem(caption, menuClickCommand(command, value, data)); - } - - private MenuItem getCategoryMenuItem(String category) { - if (category == null) { - return getCategoryMenuItem("Misc"); - } - - MenuItem item = categoryToMenuItem.get(category); - if (item != null) { - return item; - } - - return createCategory(category, null); - } - - /** - * Creates category named "category" with id "categoryId" in parent category - * "parentCategory". Each categoryId must be globally unique. - * - * @param category - * @param categoryId - * @param parentCategory - * @return - */ - protected MenuItem createCategory(String category, String parentCategory) { - if (hasCategory(category)) { - return categoryToMenuItem.get(category); - } - MenuItem item; - if (parentCategory == null) { - item = mainMenu.addItem(category, null); - } else { - item = getCategoryMenuItem(parentCategory).addItem(category, null); - } - categoryToMenuItem.put(category, item); - menuItemToCategory.put(item, category); - return item; - } - - protected boolean hasCategory(String categoryId) { - return categoryToMenuItem.containsKey(categoryId); - } - - protected void removeCategory(String categoryId) { - if (!hasCategory(categoryId)) { - throw new IllegalArgumentException("Category '" + categoryId - + "' does not exist"); - } - - MenuItem item = getCategoryMenuItem(categoryId); - Object[] children = item.getChildren().toArray(); - for (Object child : children) { - if (menuItemToCategory.containsKey(child)) { - removeCategory(menuItemToCategory.get(child)); - } - } - // Detach from parent - item.getParent().removeChild(item); - // Clean mappings - categoryToMenuItem.remove(categoryId); - menuItemToCategory.remove(item); - - } - - private MenuBar.Command menuBooleanCommand( - final com.vaadin.tests.components.ComponentTestCase.Command booleanCommand, - final Object data) { - - return new MenuBar.Command() { - public void menuSelected(MenuItem selectedItem) { - boolean selected = !isSelected(selectedItem); - doCommand(getText(selectedItem), booleanCommand, selected, data); - setSelected(selectedItem, selected); - } - - }; - } - - private MenuBar.Command menuClickCommand( - final com.vaadin.tests.components.ComponentTestCase.Command command, - final DATATYPE value, final Object data) { - - return new MenuBar.Command() { - public void menuSelected(MenuItem selectedItem) { - doCommand(getText(selectedItem), command, value, data); - } - - }; - } - - protected void setSelected(MenuItem item, boolean selected) { - if (selected) { - item.setIcon(SELECTED_ICON); - } else { - item.setIcon(null); - } - } - - protected boolean isSelected(MenuItem item) { - return (item.getIcon() != null); - } - - private MenuBar.Command singleSelectMenuCommand( - final com.vaadin.tests.components.ComponentTestCase.Command cmd, - final VALUETYPE object, final Object data) { - return new MenuBar.Command() { - public void menuSelected(MenuItem selectedItem) { - doCommand(getText(selectedItem), cmd, object, data); - - if (parentOfSelectableMenuItem.contains(selectedItem - .getParent())) { - unselectChildren(selectedItem.getParent()); - setSelected(selectedItem, true); - } - } - - }; - - } - - /** - * Unselect all child menu items - * - * @param parent - */ - protected void unselectChildren(MenuItem parent) { - List children = parent.getChildren(); - if (children == null) { - return; - } - - for (MenuItem child : children) { - setSelected(child, false); - } - } - - protected String getText(MenuItem item) { - String path = ""; - MenuItem parent = item.getParent(); - while (!isCategory(parent)) { - path = parent.getText() + "/" + path; - parent = parent.getParent(); - } - - return path + "/" + item.getText(); - } - - private boolean isCategory(MenuItem item) { - return item.getParent() == mainMenu; - } - - protected void createSelectAction( - String caption, - String category, - LinkedHashMap options, - String initialValue, - com.vaadin.tests.components.ComponentTestCase.Command command) { - createSelectAction(caption, category, options, initialValue, command, - null); - - } - - protected void createMultiClickAction( - String caption, - String category, - LinkedHashMap options, - com.vaadin.tests.components.ComponentTestCase.Command command, - Object data) { - - MenuItem categoryItem = getCategoryMenuItem(category); - MenuItem mainItem = categoryItem.addItem(caption, null); - - for (String option : options.keySet()) { - MenuBar.Command cmd = menuClickCommand(command, - options.get(option), data); - mainItem.addItem(option, cmd); - } - } - - protected void createMultiToggleAction( - String caption, - String category, - LinkedHashMap options, - com.vaadin.tests.components.ComponentTestCase.Command command, - boolean defaultValue) { - - LinkedHashMap defaultValues = new LinkedHashMap(); - - for (String option : options.keySet()) { - defaultValues.put(option, defaultValue); - } - - createMultiToggleAction(caption, category, options, command, - defaultValues); - } - - protected void createMultiToggleAction( - String caption, - String category, - LinkedHashMap options, - com.vaadin.tests.components.ComponentTestCase.Command command, - LinkedHashMap defaultValues) { - - createCategory(caption, category); - - for (String option : options.keySet()) { - createBooleanAction(option, caption, defaultValues.get(option), - command, options.get(option)); - - } - } - - protected void createSelectAction( - String caption, - String category, - LinkedHashMap options, - String initialValue, - com.vaadin.tests.components.ComponentTestCase.Command command, - Object data) { - - MenuItem parentItem = getCategoryMenuItem(category); - MenuItem mainItem = parentItem.addItem(caption, null); - - parentOfSelectableMenuItem.add(mainItem); - for (String option : options.keySet()) { - MenuBar.Command cmd = singleSelectMenuCommand(command, - options.get(option), data); - MenuItem item = mainItem.addItem(option, cmd); - if (option.equals(initialValue)) { - cmd.menuSelected(item); - } - } - } - - protected LinkedHashMap createIntegerOptions(int max) { - LinkedHashMap options = new LinkedHashMap(); - for (int i = 0; i <= 9 && i <= max; i++) { - options.put(String.valueOf(i), i); - } - for (int i = 10; i <= max; i *= 10) { - options.put(String.valueOf(i), i); - if (2 * i <= max) { - options.put(String.valueOf(2 * i), 2 * i); - } - if (5 * i <= max) { - options.put(String.valueOf(5 * i), 5 * i); - } - } - - return options; - } - - protected LinkedHashMap createDoubleOptions(double max) { - LinkedHashMap options = new LinkedHashMap(); - for (double d = 0; d <= max && d < 10; d += 0.5) { - options.put(String.valueOf(d), d); - } - for (double d = 10; d <= max; d *= 10) { - options.put(String.valueOf(d), d); - if (2.5 * d <= max) { - options.put(String.valueOf(2 * d), 2 * d); - } - if (5 * d <= max) { - options.put(String.valueOf(5 * d), 5 * d); - } - } - - return options; - } - - protected LinkedHashMap createIconOptions( - boolean cacheable) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - if (cacheable) { - options.put("16x16", ICON_16_USER_PNG_CACHEABLE); - options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE); - options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE); - } else { - options.put("16x16", ICON_16_USER_PNG_UNCACHEABLE); - options.put("32x32", ICON_32_ATTENTION_PNG_UNCACHEABLE); - options.put("64x64", ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE); - - } - return options; - } - - protected void log(String msg) { - log.log(msg); - } - - protected boolean hasLog() { - return log != null; - } - - @Override - protected void doCommand(String commandName, - AbstractComponentTestCase.Command command, VALUET value, - Object data) { - if (hasLog()) { - log("Command: " + commandName + "(" + value + ")"); - } - super.doCommand(commandName, command, value, data); - } - - @Override - public void terminalError(com.vaadin.terminal.Terminal.ErrorEvent event) { - String logMsg = "Exception occured, " - + event.getThrowable().getClass().getName(); - - String exceptionMsg = event.getThrowable().getMessage(); - if (exceptionMsg != null && exceptionMsg.length() > 0) { - logMsg += exceptionMsg; - } - log.log(logMsg); - final Throwable t = event.getThrowable(); - if (t != null) { - t.printStackTrace(); - } - - } -} +package com.vaadin.tests.components; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import com.vaadin.terminal.Resource; +import com.vaadin.terminal.ThemeResource; +import com.vaadin.tests.util.Log; +import com.vaadin.tests.util.LoremIpsum; +import com.vaadin.ui.AbstractComponent; +import com.vaadin.ui.MenuBar; +import com.vaadin.ui.MenuBar.MenuItem; + +public abstract class AbstractComponentTest + extends AbstractComponentTestCase { + + protected static final String TEXT_SHORT = "Short"; + protected static final String TEXT_MEDIUM = "This is a semi-long text that might wrap."; + protected static final String TEXT_LONG = "This is a long text. " + + LoremIpsum.get(500); + protected static final String TEXT_VERY_LONG = "This is a very, very long text. " + + LoremIpsum.get(5000); + + private static final Resource SELECTED_ICON = new ThemeResource( + "../runo/icons/16/ok.png"); + + private static final LinkedHashMap sizeOptions = new LinkedHashMap(); + static { + sizeOptions.put("auto", null); + sizeOptions.put("50%", "50%"); + sizeOptions.put("100%", "100%"); + for (int w = 200; w < 1000; w += 100) { + sizeOptions.put(w + "px", w + "px"); + } + } + + // Menu related + + private MenuItem mainMenu; + + private MenuBar menu; + + private MenuItem settingsMenu; + + private T component; + + // Used to determine if a menuItem should be selected and the other + // unselected on click + private Set parentOfSelectableMenuItem = new HashSet(); + + /** + * Maps the category name to a menu item + */ + private Map categoryToMenuItem = new HashMap(); + private Map menuItemToCategory = new HashMap(); + + // Logging + private Log log; + + protected static final String CATEGORY_STATE = "State"; + protected static final String CATEGORY_SIZE = "Size"; + protected static final String CATEGORY_SELECTION = "Selection"; + protected static final String CATEGORY_LISTENERS = "Listeners"; + protected static final String CATEGORY_FEATURES = "Features"; + protected static final String CATEGORY_ACTIONS = "Actions"; + protected static final String CATEGORY_DECORATIONS = "Decorations"; + + @Override + protected final void setup() { + setTheme("tests-components"); + + // Create menu here so it appears before the components + addComponent(createMainMenu()); + + getLayout().setSizeFull(); + createLog(); + super.setup(); + + // Create menu actions and trigger default actions + createActions(); + + // Clear initialization log messages + log.clear(); + } + + private MenuBar createMainMenu() { + menu = new MenuBar(); + menu.setDebugId("menu"); + mainMenu = menu.addItem("Component", null); + settingsMenu = menu.addItem("Settings", null); + populateSettingsMenu(settingsMenu); + + return menu; + } + + /** + * Override to add items to the "settings" menu. + * + * NOTE, Call super class first to preserve current order. If you override + * this in a class and another class overrides it you might break tests + * because the wrong items will be selected. + * + * @param settingsMenu + */ + protected void populateSettingsMenu(MenuItem settingsMenu) { + + MenuItem showEventLog = settingsMenu.addItem("Show event log", + new MenuBar.Command() { + + public void menuSelected(MenuItem selectedItem) { + boolean selected = !isSelected(selectedItem); + setLogVisible(selected); + setSelected(selectedItem, selected); + } + + }); + setSelected(showEventLog, true); + + settingsMenu.addItem("Clear log", new MenuBar.Command() { + + public void menuSelected(MenuItem selectedItem) { + log.clear(); + } + }); + MenuItem layoutSize = settingsMenu.addItem("Parent layout size", null); + MenuItem layoutWidth = layoutSize.addItem("Width", null); + MenuItem layoutHeight = layoutSize.addItem("Height", null); + for (final String name : sizeOptions.keySet()) { + layoutWidth.addItem(name, new MenuBar.Command() { + public void menuSelected(MenuItem selectedItem) { + getTestComponents().get(0).getParent() + .setWidth(sizeOptions.get(name)); + log("Parent layout width set to " + name); + } + }); + layoutHeight.addItem(name, new MenuBar.Command() { + public void menuSelected(MenuItem selectedItem) { + getTestComponents().get(0).getParent() + .setHeight(sizeOptions.get(name)); + log("Parent layout height set to " + name); + } + }); + } + + } + + protected void setLogVisible(boolean visible) { + log.setVisible(visible); + } + + private void createLog() { + log = new Log(5).setNumberLogRows(true); + getLayout().addComponent(log, 1); + } + + /** + * By default initializes just one instance of {@link #getTestClass()} using + * {@link #constructComponent()}. + */ + @Override + protected void initializeComponents() { + component = constructComponent(); + component.setDebugId("testComponent"); + addTestComponent(component); + } + + public T getComponent() { + return component; + } + + @Override + protected void addTestComponent(T c) { + super.addTestComponent(c); + getLayout().setExpandRatio(c, 1); + + }; + + /** + * Construct the component that is to be tested. This method uses a no-arg + * constructor by default. Override to customize. + * + * @return Instance of the component that is to be tested. + * @throws IllegalAccessException + * @throws InstantiationException + */ + protected T constructComponent() { + try { + return getTestClass().newInstance(); + } catch (Exception e) { + throw new RuntimeException("Failed to instantiate " + + getTestClass(), e); + } + } + + /** + * Create actions for the component. Remember to call super.createActions() + * when overriding. + */ + protected void createActions() { + createBooleanAction("Immediate", CATEGORY_STATE, true, immediateCommand); + createBooleanAction("Enabled", CATEGORY_STATE, true, enabledCommand); + createBooleanAction("Readonly", CATEGORY_STATE, false, readonlyCommand); + createBooleanAction("Visible", CATEGORY_STATE, true, visibleCommand); + createBooleanAction("Error indicator", CATEGORY_STATE, false, + errorIndicatorCommand); + createLocaleSelect(CATEGORY_STATE); + createErrorMessageSelect(CATEGORY_DECORATIONS); + + createDescriptionSelect(CATEGORY_DECORATIONS); + createCaptionSelect(CATEGORY_DECORATIONS); + createIconSelect(CATEGORY_DECORATIONS); + + createWidthAndHeightActions(CATEGORY_SIZE); + + createStyleNameSelect(CATEGORY_DECORATIONS); + + } + + private void createStyleNameSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put("Light blue background (background-lightblue)", + "background-lightblue"); + options.put("1px red border (border-red-1px)", "border-red-1px"); + options.put("2px blue border (border-blue-2px)", "border-blue-2px"); + createComponentStyleNames(options); + createSelectAction("Style name", category, options, "-", + styleNameCommand); + + } + + protected void createComponentStyleNames( + LinkedHashMap options) { + + } + + private void createErrorMessageSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put(TEXT_SHORT, TEXT_SHORT); + options.put("Medium", TEXT_MEDIUM); + options.put("Long", TEXT_LONG); + options.put("Very long", TEXT_VERY_LONG); + createSelectAction("Error message", category, options, "-", + errorMessageCommand); + + } + + private void createDescriptionSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put(TEXT_SHORT, TEXT_SHORT); + options.put("Medium", TEXT_MEDIUM); + options.put("Long", TEXT_LONG); + options.put("Very long", TEXT_VERY_LONG); + createSelectAction("Description / tooltip", category, options, "-", + descriptionCommand); + + } + + private void createCaptionSelect(String category) { + createSelectAction("Caption", category, createCaptionOptions(), + "Short", captionCommand); + + } + + protected LinkedHashMap createCaptionOptions() { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put("Short", TEXT_SHORT); + options.put("Medium", TEXT_MEDIUM); + options.put("Long", TEXT_LONG); + options.put("Very long", TEXT_VERY_LONG); + return options; + } + + private void createWidthAndHeightActions(String category) { + String widthCategory = "Width"; + String heightCategory = "Height"; + + createCategory(widthCategory, category); + createCategory(heightCategory, category); + + for (String name : sizeOptions.keySet()) { + createClickAction(name, widthCategory, widthCommand, + sizeOptions.get(name)); + createClickAction(name, heightCategory, heightCommand, + sizeOptions.get(name)); + } + + // Default to undefined size + for (T c : getTestComponents()) { + c.setWidth(null); + c.setHeight(null); + } + } + + private void createIconSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put("16x16", ICON_16_USER_PNG_CACHEABLE); + options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE); + options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE); + + createSelectAction("Icon", category, options, "-", iconCommand, null); + } + + private void createLocaleSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put("fi_FI", new Locale("fi", "FI")); + options.put("en_US", Locale.US); + options.put("zh_CN", Locale.SIMPLIFIED_CHINESE); + options.put("fr_FR", Locale.FRANCE); + + createSelectAction("Locale", category, options, "en_US", localeCommand, + null); + } + + protected void createBooleanAction(String caption, String category, + boolean initialState, final Command command) { + createBooleanAction(caption, category, initialState, command, null); + } + + protected void createBooleanAction(String caption, + String category, boolean initialState, + final Command command, Object data) { + MenuItem categoryItem = getCategoryMenuItem(category); + MenuItem item = categoryItem.addItem(caption, + menuBooleanCommand(command, data)); + setSelected(item, initialState); + doCommand(caption, command, initialState, data); + } + + protected void createClickAction(String caption, + String category, final Command command, DATATYPE value) { + createClickAction(caption, category, command, value, null); + } + + protected void createClickAction(String caption, + String category, final Command command, + DATATYPE value, Object data) { + MenuItem categoryItem = getCategoryMenuItem(category); + categoryItem.addItem(caption, menuClickCommand(command, value, data)); + } + + private MenuItem getCategoryMenuItem(String category) { + if (category == null) { + return getCategoryMenuItem("Misc"); + } + + MenuItem item = categoryToMenuItem.get(category); + if (item != null) { + return item; + } + + return createCategory(category, null); + } + + /** + * Creates category named "category" with id "categoryId" in parent category + * "parentCategory". Each categoryId must be globally unique. + * + * @param category + * @param categoryId + * @param parentCategory + * @return + */ + protected MenuItem createCategory(String category, String parentCategory) { + if (hasCategory(category)) { + return categoryToMenuItem.get(category); + } + MenuItem item; + if (parentCategory == null) { + item = mainMenu.addItem(category, null); + } else { + item = getCategoryMenuItem(parentCategory).addItem(category, null); + } + categoryToMenuItem.put(category, item); + menuItemToCategory.put(item, category); + return item; + } + + protected boolean hasCategory(String categoryId) { + return categoryToMenuItem.containsKey(categoryId); + } + + protected void removeCategory(String categoryId) { + if (!hasCategory(categoryId)) { + throw new IllegalArgumentException("Category '" + categoryId + + "' does not exist"); + } + + MenuItem item = getCategoryMenuItem(categoryId); + Object[] children = item.getChildren().toArray(); + for (Object child : children) { + if (menuItemToCategory.containsKey(child)) { + removeCategory(menuItemToCategory.get(child)); + } + } + // Detach from parent + item.getParent().removeChild(item); + // Clean mappings + categoryToMenuItem.remove(categoryId); + menuItemToCategory.remove(item); + + } + + private MenuBar.Command menuBooleanCommand( + final com.vaadin.tests.components.ComponentTestCase.Command booleanCommand, + final Object data) { + + return new MenuBar.Command() { + public void menuSelected(MenuItem selectedItem) { + boolean selected = !isSelected(selectedItem); + doCommand(getText(selectedItem), booleanCommand, selected, data); + setSelected(selectedItem, selected); + } + + }; + } + + private MenuBar.Command menuClickCommand( + final com.vaadin.tests.components.ComponentTestCase.Command command, + final DATATYPE value, final Object data) { + + return new MenuBar.Command() { + public void menuSelected(MenuItem selectedItem) { + doCommand(getText(selectedItem), command, value, data); + } + + }; + } + + protected void setSelected(MenuItem item, boolean selected) { + if (selected) { + item.setIcon(SELECTED_ICON); + } else { + item.setIcon(null); + } + } + + protected boolean isSelected(MenuItem item) { + return (item.getIcon() != null); + } + + private MenuBar.Command singleSelectMenuCommand( + final com.vaadin.tests.components.ComponentTestCase.Command cmd, + final VALUETYPE object, final Object data) { + return new MenuBar.Command() { + public void menuSelected(MenuItem selectedItem) { + doCommand(getText(selectedItem), cmd, object, data); + + if (parentOfSelectableMenuItem.contains(selectedItem + .getParent())) { + unselectChildren(selectedItem.getParent()); + setSelected(selectedItem, true); + } + } + + }; + + } + + /** + * Unselect all child menu items + * + * @param parent + */ + protected void unselectChildren(MenuItem parent) { + List children = parent.getChildren(); + if (children == null) { + return; + } + + for (MenuItem child : children) { + setSelected(child, false); + } + } + + protected String getText(MenuItem item) { + String path = ""; + MenuItem parent = item.getParent(); + while (!isCategory(parent)) { + path = parent.getText() + "/" + path; + parent = parent.getParent(); + } + + return path + "/" + item.getText(); + } + + private boolean isCategory(MenuItem item) { + return item.getParent() == mainMenu; + } + + protected void createSelectAction( + String caption, + String category, + LinkedHashMap options, + String initialValue, + com.vaadin.tests.components.ComponentTestCase.Command command) { + createSelectAction(caption, category, options, initialValue, command, + null); + + } + + protected void createMultiClickAction( + String caption, + String category, + LinkedHashMap options, + com.vaadin.tests.components.ComponentTestCase.Command command, + Object data) { + + MenuItem categoryItem = getCategoryMenuItem(category); + MenuItem mainItem = categoryItem.addItem(caption, null); + + for (String option : options.keySet()) { + MenuBar.Command cmd = menuClickCommand(command, + options.get(option), data); + mainItem.addItem(option, cmd); + } + } + + protected void createMultiToggleAction( + String caption, + String category, + LinkedHashMap options, + com.vaadin.tests.components.ComponentTestCase.Command command, + boolean defaultValue) { + + LinkedHashMap defaultValues = new LinkedHashMap(); + + for (String option : options.keySet()) { + defaultValues.put(option, defaultValue); + } + + createMultiToggleAction(caption, category, options, command, + defaultValues); + } + + protected void createMultiToggleAction( + String caption, + String category, + LinkedHashMap options, + com.vaadin.tests.components.ComponentTestCase.Command command, + LinkedHashMap defaultValues) { + + createCategory(caption, category); + + for (String option : options.keySet()) { + createBooleanAction(option, caption, defaultValues.get(option), + command, options.get(option)); + + } + } + + protected void createSelectAction( + String caption, + String category, + LinkedHashMap options, + String initialValue, + com.vaadin.tests.components.ComponentTestCase.Command command, + Object data) { + + MenuItem parentItem = getCategoryMenuItem(category); + MenuItem mainItem = parentItem.addItem(caption, null); + + parentOfSelectableMenuItem.add(mainItem); + for (String option : options.keySet()) { + MenuBar.Command cmd = singleSelectMenuCommand(command, + options.get(option), data); + MenuItem item = mainItem.addItem(option, cmd); + if (option.equals(initialValue)) { + cmd.menuSelected(item); + } + } + } + + protected LinkedHashMap createIntegerOptions(int max) { + LinkedHashMap options = new LinkedHashMap(); + for (int i = 0; i <= 9 && i <= max; i++) { + options.put(String.valueOf(i), i); + } + for (int i = 10; i <= max; i *= 10) { + options.put(String.valueOf(i), i); + if (2 * i <= max) { + options.put(String.valueOf(2 * i), 2 * i); + } + if (5 * i <= max) { + options.put(String.valueOf(5 * i), 5 * i); + } + } + + return options; + } + + protected LinkedHashMap createDoubleOptions(double max) { + LinkedHashMap options = new LinkedHashMap(); + for (double d = 0; d <= max && d < 10; d += 0.5) { + options.put(String.valueOf(d), d); + } + for (double d = 10; d <= max; d *= 10) { + options.put(String.valueOf(d), d); + if (2.5 * d <= max) { + options.put(String.valueOf(2 * d), 2 * d); + } + if (5 * d <= max) { + options.put(String.valueOf(5 * d), 5 * d); + } + } + + return options; + } + + protected LinkedHashMap createIconOptions( + boolean cacheable) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + if (cacheable) { + options.put("16x16", ICON_16_USER_PNG_CACHEABLE); + options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE); + options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE); + } else { + options.put("16x16", ICON_16_USER_PNG_UNCACHEABLE); + options.put("32x32", ICON_32_ATTENTION_PNG_UNCACHEABLE); + options.put("64x64", ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE); + + } + return options; + } + + protected void log(String msg) { + log.log(msg); + } + + protected boolean hasLog() { + return log != null; + } + + @Override + protected void doCommand(String commandName, + AbstractComponentTestCase.Command command, VALUET value, + Object data) { + if (hasLog()) { + log("Command: " + commandName + "(" + value + ")"); + } + super.doCommand(commandName, command, value, data); + } + + @Override + public void terminalError(com.vaadin.terminal.Terminal.ErrorEvent event) { + String logMsg = "Exception occured, " + + event.getThrowable().getClass().getName(); + + String exceptionMsg = event.getThrowable().getMessage(); + if (exceptionMsg != null && exceptionMsg.length() > 0) { + logMsg += exceptionMsg; + } + log.log(logMsg); + final Throwable t = event.getThrowable(); + if (t != null) { + t.printStackTrace(); + } + + } +} diff --git a/tests/testbench/com/vaadin/tests/components/AbstractLayoutTest.java b/tests/testbench/com/vaadin/tests/components/AbstractLayoutTest.java index f6b979c698..5c25359e28 100644 --- a/tests/testbench/com/vaadin/tests/components/AbstractLayoutTest.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractLayoutTest.java @@ -1,100 +1,100 @@ -package com.vaadin.tests.components; - -import java.util.LinkedHashMap; - -import com.vaadin.ui.AbstractLayout; -import com.vaadin.ui.Alignment; -import com.vaadin.ui.Component; -import com.vaadin.ui.Layout.AlignmentHandler; -import com.vaadin.ui.Layout.MarginInfo; -import com.vaadin.ui.Layout.SpacingHandler; - -public abstract class AbstractLayoutTest extends - AbstractComponentContainerTest { - - protected static final String CATEGORY_LAYOUT_FEATURES = "Layout features"; - private Command marginCommand = new Command() { - - public void execute(T c, MarginInfo value, Object data) { - c.setMargin(value); - - } - }; - - protected Command spacingCommand = new Command() { - public void execute(T c, Boolean value, Object data) { - ((SpacingHandler) c).setSpacing(value); - } - }; - - private Command setComponentAlignment = new Command() { - - public void execute(T c, Integer value, Object alignment) { - Component child = getComponentAtIndex(c, value); - ((AlignmentHandler) c).setComponentAlignment(child, - (Alignment) alignment); - } - }; - - @Override - protected void createActions() { - super.createActions(); - createMarginsSelect(CATEGORY_LAYOUT_FEATURES); - if (SpacingHandler.class.isAssignableFrom(getTestClass())) { - createSpacingSelect(CATEGORY_LAYOUT_FEATURES); - } - if (AlignmentHandler.class.isAssignableFrom(getTestClass())) { - createChangeComponentAlignmentAction(CATEGORY_LAYOUT_FEATURES); - } - - } - - private void createMarginsSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("off", new MarginInfo(false)); - options.put("all", new MarginInfo(true)); - options.put("left", new MarginInfo(false, false, false, true)); - options.put("right", new MarginInfo(false, true, false, false)); - options.put("top", new MarginInfo(true, false, false, false)); - options.put("bottom", new MarginInfo(false, false, true, false)); - options.put("left-right", new MarginInfo(false, true, false, true)); - options.put("top-bottom", new MarginInfo(true, false, true, false)); - - createSelectAction("Margins", category, options, "off", marginCommand); - } - - private void createSpacingSelect(String category) { - createBooleanAction("Spacing", category, false, spacingCommand); - } - - private void createChangeComponentAlignmentAction(String category) { - String alignmentCategory = "Component alignment"; - createCategory(alignmentCategory, category); - - LinkedHashMap options = new LinkedHashMap(); - options.put("Top left", Alignment.TOP_LEFT); - options.put("Top center", Alignment.TOP_CENTER); - options.put("Top right", Alignment.TOP_RIGHT); - - options.put("Middle left", Alignment.MIDDLE_LEFT); - options.put("Middle center", Alignment.MIDDLE_CENTER); - options.put("Middle right", Alignment.MIDDLE_RIGHT); - - options.put("Bottom left", Alignment.BOTTOM_LEFT); - options.put("Bottom center", Alignment.BOTTOM_CENTER); - options.put("Bottom right", Alignment.BOTTOM_RIGHT); - - for (int i = 0; i < 20; i++) { - String componentAlignmentCategory = "Component " + i + " alignment"; - createCategory(componentAlignmentCategory, alignmentCategory); - - for (String option : options.keySet()) { - createClickAction(option, componentAlignmentCategory, - setComponentAlignment, Integer.valueOf(i), - options.get(option)); - } - - } - - } -} +package com.vaadin.tests.components; + +import java.util.LinkedHashMap; + +import com.vaadin.ui.AbstractLayout; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.Component; +import com.vaadin.ui.Layout.AlignmentHandler; +import com.vaadin.ui.Layout.MarginInfo; +import com.vaadin.ui.Layout.SpacingHandler; + +public abstract class AbstractLayoutTest extends + AbstractComponentContainerTest { + + protected static final String CATEGORY_LAYOUT_FEATURES = "Layout features"; + private Command marginCommand = new Command() { + + public void execute(T c, MarginInfo value, Object data) { + c.setMargin(value); + + } + }; + + protected Command spacingCommand = new Command() { + public void execute(T c, Boolean value, Object data) { + ((SpacingHandler) c).setSpacing(value); + } + }; + + private Command setComponentAlignment = new Command() { + + public void execute(T c, Integer value, Object alignment) { + Component child = getComponentAtIndex(c, value); + ((AlignmentHandler) c).setComponentAlignment(child, + (Alignment) alignment); + } + }; + + @Override + protected void createActions() { + super.createActions(); + createMarginsSelect(CATEGORY_LAYOUT_FEATURES); + if (SpacingHandler.class.isAssignableFrom(getTestClass())) { + createSpacingSelect(CATEGORY_LAYOUT_FEATURES); + } + if (AlignmentHandler.class.isAssignableFrom(getTestClass())) { + createChangeComponentAlignmentAction(CATEGORY_LAYOUT_FEATURES); + } + + } + + private void createMarginsSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("off", new MarginInfo(false)); + options.put("all", new MarginInfo(true)); + options.put("left", new MarginInfo(false, false, false, true)); + options.put("right", new MarginInfo(false, true, false, false)); + options.put("top", new MarginInfo(true, false, false, false)); + options.put("bottom", new MarginInfo(false, false, true, false)); + options.put("left-right", new MarginInfo(false, true, false, true)); + options.put("top-bottom", new MarginInfo(true, false, true, false)); + + createSelectAction("Margins", category, options, "off", marginCommand); + } + + private void createSpacingSelect(String category) { + createBooleanAction("Spacing", category, false, spacingCommand); + } + + private void createChangeComponentAlignmentAction(String category) { + String alignmentCategory = "Component alignment"; + createCategory(alignmentCategory, category); + + LinkedHashMap options = new LinkedHashMap(); + options.put("Top left", Alignment.TOP_LEFT); + options.put("Top center", Alignment.TOP_CENTER); + options.put("Top right", Alignment.TOP_RIGHT); + + options.put("Middle left", Alignment.MIDDLE_LEFT); + options.put("Middle center", Alignment.MIDDLE_CENTER); + options.put("Middle right", Alignment.MIDDLE_RIGHT); + + options.put("Bottom left", Alignment.BOTTOM_LEFT); + options.put("Bottom center", Alignment.BOTTOM_CENTER); + options.put("Bottom right", Alignment.BOTTOM_RIGHT); + + for (int i = 0; i < 20; i++) { + String componentAlignmentCategory = "Component " + i + " alignment"; + createCategory(componentAlignmentCategory, alignmentCategory); + + for (String option : options.keySet()) { + createClickAction(option, componentAlignmentCategory, + setComponentAlignment, Integer.valueOf(i), + options.get(option)); + } + + } + + } +} diff --git a/tests/testbench/com/vaadin/tests/components/AbstractOrderedLayoutTest.java b/tests/testbench/com/vaadin/tests/components/AbstractOrderedLayoutTest.java index d6cbe8590d..fd323d2156 100644 --- a/tests/testbench/com/vaadin/tests/components/AbstractOrderedLayoutTest.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractOrderedLayoutTest.java @@ -1,85 +1,85 @@ -package com.vaadin.tests.components; - -import java.util.LinkedHashMap; - -import com.vaadin.event.LayoutEvents.LayoutClickEvent; -import com.vaadin.event.LayoutEvents.LayoutClickListener; -import com.vaadin.ui.AbstractOrderedLayout; -import com.vaadin.ui.Component; - -public abstract class AbstractOrderedLayoutTest - extends AbstractLayoutTest implements LayoutClickListener { - - private Command layoutClickListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((LayoutClickListener) AbstractOrderedLayoutTest.this); - } else { - - } - - } - }; - - private Command setComponentExpandRatio = new Command() { - - public void execute(T c, Integer value, Object ratio) { - Component child = getComponentAtIndex(c, value); - c.setExpandRatio(child, (Float) ratio); - } - }; - - @Override - protected void createActions() { - super.createActions(); - - createLayoutClickListenerAction(CATEGORY_LISTENERS); - createChangeComponentExpandRatioAction(CATEGORY_LAYOUT_FEATURES); - // Set a root style so we can see the component. Can be overridden by - // setting the style name in the UI - for (T c : getTestComponents()) { - c.setStyleName("background-lightblue"); - } - } - - private void createLayoutClickListenerAction(String category) { - createBooleanAction("Layout click listener", category, false, - layoutClickListenerCommand); - } - - private void createChangeComponentExpandRatioAction(String category) { - String expandRatioCategory = "Component expand ratio"; - createCategory(expandRatioCategory, category); - - LinkedHashMap options = new LinkedHashMap(); - options.put("0", 0f); - options.put("0.5", 0.5f); - for (float f = 1; f <= 5; f++) { - options.put(String.valueOf(f), f); - } - - for (int i = 0; i < 20; i++) { - String componentExpandRatioCategory = "Component " + i - + " expand ratio"; - createCategory(componentExpandRatioCategory, expandRatioCategory); - - for (String option : options.keySet()) { - createClickAction(option, componentExpandRatioCategory, - setComponentExpandRatio, Integer.valueOf(i), - options.get(option)); - } - - } - - } - - public void layoutClick(LayoutClickEvent event) { - log(event.getClass().getSimpleName() + ": button=" - + event.getButtonName() + ", childComponent=" - + event.getChildComponent().getClass().getSimpleName() - + ", relativeX=" + event.getRelativeX() + ", relativeY=" - + event.getRelativeY()); - - } -} +package com.vaadin.tests.components; + +import java.util.LinkedHashMap; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.ui.AbstractOrderedLayout; +import com.vaadin.ui.Component; + +public abstract class AbstractOrderedLayoutTest + extends AbstractLayoutTest implements LayoutClickListener { + + private Command layoutClickListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((LayoutClickListener) AbstractOrderedLayoutTest.this); + } else { + + } + + } + }; + + private Command setComponentExpandRatio = new Command() { + + public void execute(T c, Integer value, Object ratio) { + Component child = getComponentAtIndex(c, value); + c.setExpandRatio(child, (Float) ratio); + } + }; + + @Override + protected void createActions() { + super.createActions(); + + createLayoutClickListenerAction(CATEGORY_LISTENERS); + createChangeComponentExpandRatioAction(CATEGORY_LAYOUT_FEATURES); + // Set a root style so we can see the component. Can be overridden by + // setting the style name in the UI + for (T c : getTestComponents()) { + c.setStyleName("background-lightblue"); + } + } + + private void createLayoutClickListenerAction(String category) { + createBooleanAction("Layout click listener", category, false, + layoutClickListenerCommand); + } + + private void createChangeComponentExpandRatioAction(String category) { + String expandRatioCategory = "Component expand ratio"; + createCategory(expandRatioCategory, category); + + LinkedHashMap options = new LinkedHashMap(); + options.put("0", 0f); + options.put("0.5", 0.5f); + for (float f = 1; f <= 5; f++) { + options.put(String.valueOf(f), f); + } + + for (int i = 0; i < 20; i++) { + String componentExpandRatioCategory = "Component " + i + + " expand ratio"; + createCategory(componentExpandRatioCategory, expandRatioCategory); + + for (String option : options.keySet()) { + createClickAction(option, componentExpandRatioCategory, + setComponentExpandRatio, Integer.valueOf(i), + options.get(option)); + } + + } + + } + + public void layoutClick(LayoutClickEvent event) { + log(event.getClass().getSimpleName() + ": button=" + + event.getButtonName() + ", childComponent=" + + event.getChildComponent().getClass().getSimpleName() + + ", relativeX=" + event.getRelativeX() + ", relativeY=" + + event.getRelativeY()); + + } +} diff --git a/tests/testbench/com/vaadin/tests/components/AbstractTestCase.java b/tests/testbench/com/vaadin/tests/components/AbstractTestCase.java index ded579f58c..e2b3ad0fe1 100644 --- a/tests/testbench/com/vaadin/tests/components/AbstractTestCase.java +++ b/tests/testbench/com/vaadin/tests/components/AbstractTestCase.java @@ -1,24 +1,24 @@ -package com.vaadin.tests.components; - -import com.vaadin.Application; -import com.vaadin.service.ApplicationContext; -import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext; -import com.vaadin.terminal.gwt.server.WebBrowser; - -public abstract class AbstractTestCase extends Application { - - protected abstract String getDescription(); - - protected abstract Integer getTicketNumber(); - - protected WebBrowser getBrowser() { - ApplicationContext context = getContext(); - if (context instanceof AbstractWebApplicationContext) { - WebBrowser webBrowser = ((AbstractWebApplicationContext) context) - .getBrowser(); - return webBrowser; - } - - return null; - } -} +package com.vaadin.tests.components; + +import com.vaadin.Application; +import com.vaadin.service.ApplicationContext; +import com.vaadin.terminal.gwt.server.AbstractWebApplicationContext; +import com.vaadin.terminal.gwt.server.WebBrowser; + +public abstract class AbstractTestCase extends Application { + + protected abstract String getDescription(); + + protected abstract Integer getTicketNumber(); + + protected WebBrowser getBrowser() { + ApplicationContext context = getContext(); + if (context instanceof AbstractWebApplicationContext) { + WebBrowser webBrowser = ((AbstractWebApplicationContext) context) + .getBrowser(); + return webBrowser; + } + + return null; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/HierarchicalContainerSorting.java b/tests/testbench/com/vaadin/tests/components/HierarchicalContainerSorting.java index 1f0f1bd923..d0638be54c 100644 --- a/tests/testbench/com/vaadin/tests/components/HierarchicalContainerSorting.java +++ b/tests/testbench/com/vaadin/tests/components/HierarchicalContainerSorting.java @@ -1,109 +1,109 @@ -package com.vaadin.tests.components; - -import java.util.HashMap; -import java.util.Map; - -import com.vaadin.data.Item; -import com.vaadin.data.util.HierarchicalContainer; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Tree; - -public class HierarchicalContainerSorting extends TestBase { - IndexedContainer hierarchicalContainer = new HierarchicalContainer(); - - IndexedContainer indexedContainer = new IndexedContainer(); - - @Override - public void setup() { - - populateContainer(indexedContainer); - populateContainer(hierarchicalContainer); - - sort(indexedContainer); - sort(hierarchicalContainer); - - HorizontalLayout hl = new HorizontalLayout(); - - Tree tree1 = new Tree("Tree with IndexedContainer"); - tree1.setContainerDataSource(indexedContainer); - tree1.setItemCaptionPropertyId("name"); - hl.addComponent(tree1); - - Tree tree2 = new Tree("Tree with HierarchicalContainer"); - tree2.setContainerDataSource(hierarchicalContainer); - tree2.setItemCaptionPropertyId("name"); - for (Object id : tree2.rootItemIds()) { - tree2.expandItemsRecursively(id); - } - hl.addComponent(tree2); - - addComponent(hl); - } - - private static void sort(IndexedContainer container) { - Object[] properties = new Object[1]; - properties[0] = "name"; - - boolean[] ascending = new boolean[1]; - ascending[0] = true; - - container.sort(properties, ascending); - } - - private static void populateContainer(IndexedContainer 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 nameToId = new HashMap(); - - public static void addItem(IndexedContainer container, String string, - String parent) { - nameToId.put(string, index); - Item item = container.addItem(index); - item.getItemProperty("name").setValue(string); - - if (parent != null && container instanceof HierarchicalContainer) { - ((HierarchicalContainer) container).setParent(index, - nameToId.get(parent)); - } - - index++; - } - - @Override - protected String getDescription() { - return "The two trees contain the same data, one uses IndexedContainer, one uses HierarchicalContainer. Both should be sorted, both the root nodes and the children."; - } - - @Override - protected Integer getTicketNumber() { - return 3095; - } - +package com.vaadin.tests.components; + +import java.util.HashMap; +import java.util.Map; + +import com.vaadin.data.Item; +import com.vaadin.data.util.HierarchicalContainer; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Tree; + +public class HierarchicalContainerSorting extends TestBase { + IndexedContainer hierarchicalContainer = new HierarchicalContainer(); + + IndexedContainer indexedContainer = new IndexedContainer(); + + @Override + public void setup() { + + populateContainer(indexedContainer); + populateContainer(hierarchicalContainer); + + sort(indexedContainer); + sort(hierarchicalContainer); + + HorizontalLayout hl = new HorizontalLayout(); + + Tree tree1 = new Tree("Tree with IndexedContainer"); + tree1.setContainerDataSource(indexedContainer); + tree1.setItemCaptionPropertyId("name"); + hl.addComponent(tree1); + + Tree tree2 = new Tree("Tree with HierarchicalContainer"); + tree2.setContainerDataSource(hierarchicalContainer); + tree2.setItemCaptionPropertyId("name"); + for (Object id : tree2.rootItemIds()) { + tree2.expandItemsRecursively(id); + } + hl.addComponent(tree2); + + addComponent(hl); + } + + private static void sort(IndexedContainer container) { + Object[] properties = new Object[1]; + properties[0] = "name"; + + boolean[] ascending = new boolean[1]; + ascending[0] = true; + + container.sort(properties, ascending); + } + + private static void populateContainer(IndexedContainer 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 nameToId = new HashMap(); + + public static void addItem(IndexedContainer container, String string, + String parent) { + nameToId.put(string, index); + Item item = container.addItem(index); + item.getItemProperty("name").setValue(string); + + if (parent != null && container instanceof HierarchicalContainer) { + ((HierarchicalContainer) container).setParent(index, + nameToId.get(parent)); + } + + index++; + } + + @Override + protected String getDescription() { + return "The two trees contain the same data, one uses IndexedContainer, one uses HierarchicalContainer. Both should be sorted, both the root nodes and the children."; + } + + @Override + protected Integer getTicketNumber() { + return 3095; + } + } \ No newline at end of file diff --git a/tests/testbench/com/vaadin/tests/components/LongTooltip.java b/tests/testbench/com/vaadin/tests/components/LongTooltip.java index 87adaa673b..acb498bcee 100644 --- a/tests/testbench/com/vaadin/tests/components/LongTooltip.java +++ b/tests/testbench/com/vaadin/tests/components/LongTooltip.java @@ -1,49 +1,49 @@ -package com.vaadin.tests.components; - -import com.vaadin.tests.util.LoremIpsum; -import com.vaadin.ui.Alignment; -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.TextField; - -public class LongTooltip extends TestBase { - - @Override - public void setup() { - - GridLayout gl = new GridLayout(2, 2); - gl.setSizeFull(); - TextField f1 = createField(); - TextField f2 = createField(); - TextField f3 = createField(); - TextField f4 = createField(); - gl.addComponent(f1); - gl.addComponent(f2); - gl.addComponent(f3); - gl.addComponent(f4); - - gl.setComponentAlignment(f1, Alignment.TOP_LEFT); - gl.setComponentAlignment(f2, Alignment.TOP_RIGHT); - gl.setComponentAlignment(f3, Alignment.BOTTOM_LEFT); - gl.setComponentAlignment(f4, Alignment.BOTTOM_RIGHT); - - getLayout().setSizeFull(); - getLayout().addComponent(gl); - - } - - private TextField createField() { - final TextField field = new TextField(); - field.setDescription(LoremIpsum.get(1000)); - return field; - } - - @Override - protected String getDescription() { - return "For a given cursor position the tooltip should always appear with the same size in the same position. The tooltip should also always be completely on screen and not cause any scrollbars to appear."; - } - - @Override - protected Integer getTicketNumber() { - return 7100; - } -} +package com.vaadin.tests.components; + +import com.vaadin.tests.util.LoremIpsum; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.TextField; + +public class LongTooltip extends TestBase { + + @Override + public void setup() { + + GridLayout gl = new GridLayout(2, 2); + gl.setSizeFull(); + TextField f1 = createField(); + TextField f2 = createField(); + TextField f3 = createField(); + TextField f4 = createField(); + gl.addComponent(f1); + gl.addComponent(f2); + gl.addComponent(f3); + gl.addComponent(f4); + + gl.setComponentAlignment(f1, Alignment.TOP_LEFT); + gl.setComponentAlignment(f2, Alignment.TOP_RIGHT); + gl.setComponentAlignment(f3, Alignment.BOTTOM_LEFT); + gl.setComponentAlignment(f4, Alignment.BOTTOM_RIGHT); + + getLayout().setSizeFull(); + getLayout().addComponent(gl); + + } + + private TextField createField() { + final TextField field = new TextField(); + field.setDescription(LoremIpsum.get(1000)); + return field; + } + + @Override + protected String getDescription() { + return "For a given cursor position the tooltip should always appear with the same size in the same position. The tooltip should also always be completely on screen and not cause any scrollbars to appear."; + } + + @Override + protected Integer getTicketNumber() { + return 7100; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/TestBase.java b/tests/testbench/com/vaadin/tests/components/TestBase.java index 2156c512ce..c7380d3d7c 100644 --- a/tests/testbench/com/vaadin/tests/components/TestBase.java +++ b/tests/testbench/com/vaadin/tests/components/TestBase.java @@ -1,53 +1,53 @@ -package com.vaadin.tests.components; - -import com.vaadin.ui.Component; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.Window; - -public abstract class TestBase extends AbstractTestCase { - - @Override - public final void init() { - window = new Window(getClass().getName()); - setMainWindow(window); - window.getContent().setSizeFull(); - - Label label = new Label(getDescription(), Label.CONTENT_XHTML); - label.setWidth("100%"); - window.getContent().addComponent(label); - - layout = new VerticalLayout(); - window.getContent().addComponent(layout); - ((VerticalLayout) window.getContent()).setExpandRatio(layout, 1); - - setup(); - } - - private Window window; - private VerticalLayout layout; - - public TestBase() { - - } - - protected VerticalLayout getLayout() { - return layout; - } - - protected abstract void setup(); - - protected void addComponent(Component c) { - getLayout().addComponent(c); - } - - protected void removeComponent(Component c) { - getLayout().removeComponent(c); - } - - protected void replaceComponent(Component oldComponent, - Component newComponent) { - getLayout().replaceComponent(oldComponent, newComponent); - } - -} +package com.vaadin.tests.components; + +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; + +public abstract class TestBase extends AbstractTestCase { + + @Override + public final void init() { + window = new Window(getClass().getName()); + setMainWindow(window); + window.getContent().setSizeFull(); + + Label label = new Label(getDescription(), Label.CONTENT_XHTML); + label.setWidth("100%"); + window.getContent().addComponent(label); + + layout = new VerticalLayout(); + window.getContent().addComponent(layout); + ((VerticalLayout) window.getContent()).setExpandRatio(layout, 1); + + setup(); + } + + private Window window; + private VerticalLayout layout; + + public TestBase() { + + } + + protected VerticalLayout getLayout() { + return layout; + } + + protected abstract void setup(); + + protected void addComponent(Component c) { + getLayout().addComponent(c); + } + + protected void removeComponent(Component c) { + getLayout().removeComponent(c); + } + + protected void replaceComponent(Component oldComponent, + Component newComponent) { + getLayout().replaceComponent(oldComponent, newComponent); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/absolutelayout/MoveComponentsFromAbsoluteLayoutToInnerLayout.java b/tests/testbench/com/vaadin/tests/components/absolutelayout/MoveComponentsFromAbsoluteLayoutToInnerLayout.java index 9082842b1c..139ed5bb0b 100644 --- a/tests/testbench/com/vaadin/tests/components/absolutelayout/MoveComponentsFromAbsoluteLayoutToInnerLayout.java +++ b/tests/testbench/com/vaadin/tests/components/absolutelayout/MoveComponentsFromAbsoluteLayoutToInnerLayout.java @@ -1,58 +1,58 @@ -package com.vaadin.tests.components.absolutelayout; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.AbsoluteLayout; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.ComponentContainer; -import com.vaadin.ui.VerticalLayout; - -public class MoveComponentsFromAbsoluteLayoutToInnerLayout extends TestBase { - - protected Button testButton; - private AbsoluteLayout al; - protected ComponentContainer vl; - - @Override - protected void setup() { - al = new AbsoluteLayout(); - al.setWidth("200px"); - al.setHeight("200px"); - - testButton = new Button("Click to move to inner layout", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - vl.addComponent(testButton); - } - }); - - al.addComponent(testButton); - - vl = new VerticalLayout(); - al.addComponent(vl, "top: 100px"); - - addComponent(al); - - Button b = new Button("Repaint inner layout", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - vl.requestRepaint(); - } - }); - - addComponent(b); - } - - @Override - protected String getDescription() { - return "Click the first button to move it from an outer layout to an inner. Then click the second button to repaint the inner layout."; - } - - @Override - protected Integer getTicketNumber() { - return 6061; - } - -} +package com.vaadin.tests.components.absolutelayout; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.AbsoluteLayout; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.ComponentContainer; +import com.vaadin.ui.VerticalLayout; + +public class MoveComponentsFromAbsoluteLayoutToInnerLayout extends TestBase { + + protected Button testButton; + private AbsoluteLayout al; + protected ComponentContainer vl; + + @Override + protected void setup() { + al = new AbsoluteLayout(); + al.setWidth("200px"); + al.setHeight("200px"); + + testButton = new Button("Click to move to inner layout", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + vl.addComponent(testButton); + } + }); + + al.addComponent(testButton); + + vl = new VerticalLayout(); + al.addComponent(vl, "top: 100px"); + + addComponent(al); + + Button b = new Button("Repaint inner layout", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + vl.requestRepaint(); + } + }); + + addComponent(b); + } + + @Override + protected String getDescription() { + return "Click the first button to move it from an outer layout to an inner. Then click the second button to repaint the inner layout."; + } + + @Override + protected Integer getTicketNumber() { + return 6061; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java b/tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java index 5d4f0f2acf..a5498660be 100644 --- a/tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java +++ b/tests/testbench/com/vaadin/tests/components/abstractcomponent/EnableState.java @@ -1,77 +1,77 @@ -package com.vaadin.tests.components.abstractcomponent; - -import com.vaadin.tests.components.AbstractTestCase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.CheckBox; -import com.vaadin.ui.Panel; -import com.vaadin.ui.Window; - -public class EnableState extends AbstractTestCase { - @Override - public void init() { - Window mainWindow = new Window("Helloworld Application"); - - final Panel panel = new Panel("Test"); - final Button button = new Button("ablebutton"); - panel.addComponent(button); - - CheckBox enable = new CheckBox("Toggle button enabled", true); - enable.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - boolean enabled = (Boolean) event.getButton().getValue(); - button.setEnabled(enabled); - // button.requestRepaint(); - } - }); - enable.setImmediate(true); - - CheckBox caption = new CheckBox("Toggle button caption", true); - caption.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - button.setCaption(button.getCaption() + "+"); - } - }); - caption.setImmediate(true); - - CheckBox visible = new CheckBox("Toggle panel visibility", true); - visible.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - boolean visible = (Boolean) event.getButton().getValue(); - - panel.setVisible(visible); - } - }); - visible.setImmediate(true); - - CheckBox panelEnable = new CheckBox("Toggle panel enabled", true); - panelEnable.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - boolean enabled = (Boolean) event.getButton().getValue(); - panel.setEnabled(enabled); - } - }); - panelEnable.setImmediate(true); - - mainWindow.addComponent(enable); - mainWindow.addComponent(caption); - mainWindow.addComponent(visible); - mainWindow.addComponent(panelEnable); - mainWindow.addComponent(panel); - - setMainWindow(mainWindow); - } - - @Override - protected String getDescription() { - return "This tests the enabled/disabled propagation and that enabled/disabled state is updated" - + " properly even when the parent is invisible. Disabling the Button while the panel is" - + " invisible should be reflected on the screen when the panel is set visible" - + " again."; - } - - @Override - protected Integer getTicketNumber() { - return 3609; - } -} +package com.vaadin.tests.components.abstractcomponent; + +import com.vaadin.tests.components.AbstractTestCase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.Panel; +import com.vaadin.ui.Window; + +public class EnableState extends AbstractTestCase { + @Override + public void init() { + Window mainWindow = new Window("Helloworld Application"); + + final Panel panel = new Panel("Test"); + final Button button = new Button("ablebutton"); + panel.addComponent(button); + + CheckBox enable = new CheckBox("Toggle button enabled", true); + enable.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + boolean enabled = (Boolean) event.getButton().getValue(); + button.setEnabled(enabled); + // button.requestRepaint(); + } + }); + enable.setImmediate(true); + + CheckBox caption = new CheckBox("Toggle button caption", true); + caption.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + button.setCaption(button.getCaption() + "+"); + } + }); + caption.setImmediate(true); + + CheckBox visible = new CheckBox("Toggle panel visibility", true); + visible.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + boolean visible = (Boolean) event.getButton().getValue(); + + panel.setVisible(visible); + } + }); + visible.setImmediate(true); + + CheckBox panelEnable = new CheckBox("Toggle panel enabled", true); + panelEnable.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + boolean enabled = (Boolean) event.getButton().getValue(); + panel.setEnabled(enabled); + } + }); + panelEnable.setImmediate(true); + + mainWindow.addComponent(enable); + mainWindow.addComponent(caption); + mainWindow.addComponent(visible); + mainWindow.addComponent(panelEnable); + mainWindow.addComponent(panel); + + setMainWindow(mainWindow); + } + + @Override + protected String getDescription() { + return "This tests the enabled/disabled propagation and that enabled/disabled state is updated" + + " properly even when the parent is invisible. Disabling the Button while the panel is" + + " invisible should be reflected on the screen when the panel is set visible" + + " again."; + } + + @Override + protected Integer getTicketNumber() { + return 3609; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldDataSourceReadOnly.java b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldDataSourceReadOnly.java index 2a2fc0153a..780130847a 100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldDataSourceReadOnly.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldDataSourceReadOnly.java @@ -1,60 +1,60 @@ -package com.vaadin.tests.components.abstractfield; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Component.Event; -import com.vaadin.ui.Component.Listener; -import com.vaadin.ui.TextField; - -public class AbstractFieldDataSourceReadOnly extends TestBase { - - private static class StateHolder { - private ObjectProperty textField = new ObjectProperty( - ""); - - public ObjectProperty getTextField() { - return textField; - } - - @SuppressWarnings("unused") - public void setTextField(ObjectProperty textField) { - this.textField = textField; - } - - public void buttonClicked() { - textField.setReadOnly(true); - } - } - - @Override - protected void setup() { - final StateHolder stateHolder = new StateHolder(); - - // Button - Button button = new Button("Make data source read-only"); - button.addListener(new Listener() { - public void componentEvent(Event event) { - stateHolder.buttonClicked(); - } - }); - - // Input field - TextField input = new TextField("Field"); - input.setPropertyDataSource(stateHolder.getTextField()); - - addComponent(button); - addComponent(input); - } - - @Override - protected String getDescription() { - return "Read-only status changes in data sources are not rendered immediately"; - } - - @Override - protected Integer getTicketNumber() { - return 5013; - } - -} +package com.vaadin.tests.components.abstractfield; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Component.Event; +import com.vaadin.ui.Component.Listener; +import com.vaadin.ui.TextField; + +public class AbstractFieldDataSourceReadOnly extends TestBase { + + private static class StateHolder { + private ObjectProperty textField = new ObjectProperty( + ""); + + public ObjectProperty getTextField() { + return textField; + } + + @SuppressWarnings("unused") + public void setTextField(ObjectProperty textField) { + this.textField = textField; + } + + public void buttonClicked() { + textField.setReadOnly(true); + } + } + + @Override + protected void setup() { + final StateHolder stateHolder = new StateHolder(); + + // Button + Button button = new Button("Make data source read-only"); + button.addListener(new Listener() { + public void componentEvent(Event event) { + stateHolder.buttonClicked(); + } + }); + + // Input field + TextField input = new TextField("Field"); + input.setPropertyDataSource(stateHolder.getTextField()); + + addComponent(button); + addComponent(input); + } + + @Override + protected String getDescription() { + return "Read-only status changes in data sources are not rendered immediately"; + } + + @Override + protected Integer getTicketNumber() { + return 5013; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java index 1c8e728908..40cc2948ee 100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractFieldTest.java @@ -1,234 +1,234 @@ -package com.vaadin.tests.components.abstractfield; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; - -import com.vaadin.data.Property; -import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; -import com.vaadin.data.Property.ReadOnlyStatusChangeListener; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.BlurNotifier; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.event.FieldEvents.FocusNotifier; -import com.vaadin.tests.components.AbstractComponentTest; -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.MenuBar; -import com.vaadin.ui.MenuBar.MenuItem; - -public abstract class AbstractFieldTest extends - AbstractComponentTest implements ValueChangeListener, - ReadOnlyStatusChangeListener, FocusListener, BlurListener { - - @Override - protected void createActions() { - super.createActions(); - createBooleanAction("Required", CATEGORY_STATE, false, requiredCommand); - createRequiredErrorSelect(CATEGORY_DECORATIONS); - - createValueChangeListener(CATEGORY_LISTENERS); - createReadOnlyStatusChangeListener(CATEGORY_LISTENERS); - - // * invalidcommitted - // * commit() - // * discard() - // * writethrough - // * readthrough - // * addvalidator - // * isvalid - // * invalidallowed - // * error indicator - // - // * tabindex - // * validation visible - // * ShortcutListener - - } - - @Override - protected void populateSettingsMenu(MenuItem settingsMenu) { - super.populateSettingsMenu(settingsMenu); - - if (AbstractField.class.isAssignableFrom(getTestClass())) { - MenuItem abstractField = settingsMenu - .addItem("AbstractField", null); - abstractField.addItem("Show value", new MenuBar.Command() { - - public void menuSelected(MenuItem selectedItem) { - for (T a : getTestComponents()) { - log(a.getClass().getSimpleName() + " value: " - + getValue(a)); - } - } - }); - } - } - - private void createRequiredErrorSelect(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put(TEXT_SHORT, TEXT_SHORT); - options.put("Medium", TEXT_MEDIUM); - options.put("Long", TEXT_LONG); - options.put("Very long", TEXT_VERY_LONG); - createSelectAction("Required error message", category, options, "-", - requiredErrorMessageCommand); - - if (FocusNotifier.class.isAssignableFrom(getTestClass())) { - createFocusListener(CATEGORY_LISTENERS); - } - - if (BlurNotifier.class.isAssignableFrom(getTestClass())) { - createBlurListener(CATEGORY_LISTENERS); - } - - } - - private void createValueChangeListener(String category) { - - createBooleanAction("Value change listener", category, false, - valueChangeListenerCommand); - } - - private void createReadOnlyStatusChangeListener(String category) { - - createBooleanAction("Read only status change listener", category, - false, readonlyStatusChangeListenerCommand); - } - - private void createFocusListener(String category) { - createBooleanAction("Focus listener", category, false, - focusListenerCommand); - - } - - private void createBlurListener(String category) { - createBooleanAction("Blur listener", category, false, - blurListenerCommand); - - } - - protected Command valueChangeListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ValueChangeListener) AbstractFieldTest.this); - } else { - c.removeListener((ValueChangeListener) AbstractFieldTest.this); - } - } - }; - protected Command readonlyStatusChangeListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); - } else { - c.removeListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); - } - } - }; - protected Command focusListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - ((FocusNotifier) c).addListener(AbstractFieldTest.this); - } else { - ((FocusNotifier) c).removeListener(AbstractFieldTest.this); - } - } - }; - protected Command blurListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - ((BlurNotifier) c).addListener(AbstractFieldTest.this); - } else { - ((BlurNotifier) c).removeListener(AbstractFieldTest.this); - } - } - }; - protected Command setValueCommand = new Command() { - - public void execute(T c, Object value, Object data) { - c.setValue(value); - } - }; - - public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) { - log(event.getClass().getSimpleName() + ", new value: " - + getValue(event.getProperty())); - }; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getValue(Property property) { - Object o = property.getValue(); - if (o instanceof Collection) { - // Sort collections to avoid problems with values printed in - // different order - try { - ArrayList c = new ArrayList( - (Collection) o); - Collections.sort(c); - o = c; - } catch (Exception e) { - // continue with unsorted if sorting fails for some reason - log("Exception while sorting value: " + e.getMessage()); - } - } - - // Distinguish between null and 'null' - String value = "null"; - if (o != null) { - if (o instanceof Date) { - Date d = (Date) o; - // Dec 31, 2068 23:09:26.531 - String pattern = "MMM d, yyyy HH:mm:ss.SSS"; - SimpleDateFormat format = new SimpleDateFormat(pattern, - new Locale("en", "US")); - value = format.format(d); - } else { - value = "'" + o.toString() + "'"; - } - } - - return value; - - } - - public void readOnlyStatusChange(ReadOnlyStatusChangeEvent event) { - log(event.getClass().getSimpleName()); - } - - public void focus(FocusEvent event) { - log(event.getClass().getSimpleName()); - } - - public void blur(BlurEvent event) { - log(event.getClass().getSimpleName()); - } - - protected void createSetTextValueAction(String category) { - String subCategory = "Set text value"; - createCategory(subCategory, category); - List values = new ArrayList(); - values.add("Test"); - values.add("A little longer value"); - values.add("A very long value with very much text. All in all it is 74 characters long"); - - createClickAction("(empty string)", subCategory, setValueCommand, ""); - createClickAction("(null)", subCategory, setValueCommand, null); - for (String value : values) { - createClickAction(value, subCategory, setValueCommand, value); - } - } - -} +package com.vaadin.tests.components.abstractfield; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; + +import com.vaadin.data.Property; +import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; +import com.vaadin.data.Property.ReadOnlyStatusChangeListener; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.BlurNotifier; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.event.FieldEvents.FocusNotifier; +import com.vaadin.tests.components.AbstractComponentTest; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.MenuBar; +import com.vaadin.ui.MenuBar.MenuItem; + +public abstract class AbstractFieldTest extends + AbstractComponentTest implements ValueChangeListener, + ReadOnlyStatusChangeListener, FocusListener, BlurListener { + + @Override + protected void createActions() { + super.createActions(); + createBooleanAction("Required", CATEGORY_STATE, false, requiredCommand); + createRequiredErrorSelect(CATEGORY_DECORATIONS); + + createValueChangeListener(CATEGORY_LISTENERS); + createReadOnlyStatusChangeListener(CATEGORY_LISTENERS); + + // * invalidcommitted + // * commit() + // * discard() + // * writethrough + // * readthrough + // * addvalidator + // * isvalid + // * invalidallowed + // * error indicator + // + // * tabindex + // * validation visible + // * ShortcutListener + + } + + @Override + protected void populateSettingsMenu(MenuItem settingsMenu) { + super.populateSettingsMenu(settingsMenu); + + if (AbstractField.class.isAssignableFrom(getTestClass())) { + MenuItem abstractField = settingsMenu + .addItem("AbstractField", null); + abstractField.addItem("Show value", new MenuBar.Command() { + + public void menuSelected(MenuItem selectedItem) { + for (T a : getTestComponents()) { + log(a.getClass().getSimpleName() + " value: " + + getValue(a)); + } + } + }); + } + } + + private void createRequiredErrorSelect(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put(TEXT_SHORT, TEXT_SHORT); + options.put("Medium", TEXT_MEDIUM); + options.put("Long", TEXT_LONG); + options.put("Very long", TEXT_VERY_LONG); + createSelectAction("Required error message", category, options, "-", + requiredErrorMessageCommand); + + if (FocusNotifier.class.isAssignableFrom(getTestClass())) { + createFocusListener(CATEGORY_LISTENERS); + } + + if (BlurNotifier.class.isAssignableFrom(getTestClass())) { + createBlurListener(CATEGORY_LISTENERS); + } + + } + + private void createValueChangeListener(String category) { + + createBooleanAction("Value change listener", category, false, + valueChangeListenerCommand); + } + + private void createReadOnlyStatusChangeListener(String category) { + + createBooleanAction("Read only status change listener", category, + false, readonlyStatusChangeListenerCommand); + } + + private void createFocusListener(String category) { + createBooleanAction("Focus listener", category, false, + focusListenerCommand); + + } + + private void createBlurListener(String category) { + createBooleanAction("Blur listener", category, false, + blurListenerCommand); + + } + + protected Command valueChangeListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ValueChangeListener) AbstractFieldTest.this); + } else { + c.removeListener((ValueChangeListener) AbstractFieldTest.this); + } + } + }; + protected Command readonlyStatusChangeListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); + } else { + c.removeListener((ReadOnlyStatusChangeListener) AbstractFieldTest.this); + } + } + }; + protected Command focusListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + ((FocusNotifier) c).addListener(AbstractFieldTest.this); + } else { + ((FocusNotifier) c).removeListener(AbstractFieldTest.this); + } + } + }; + protected Command blurListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + ((BlurNotifier) c).addListener(AbstractFieldTest.this); + } else { + ((BlurNotifier) c).removeListener(AbstractFieldTest.this); + } + } + }; + protected Command setValueCommand = new Command() { + + public void execute(T c, Object value, Object data) { + c.setValue(value); + } + }; + + public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) { + log(event.getClass().getSimpleName() + ", new value: " + + getValue(event.getProperty())); + }; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getValue(Property property) { + Object o = property.getValue(); + if (o instanceof Collection) { + // Sort collections to avoid problems with values printed in + // different order + try { + ArrayList c = new ArrayList( + (Collection) o); + Collections.sort(c); + o = c; + } catch (Exception e) { + // continue with unsorted if sorting fails for some reason + log("Exception while sorting value: " + e.getMessage()); + } + } + + // Distinguish between null and 'null' + String value = "null"; + if (o != null) { + if (o instanceof Date) { + Date d = (Date) o; + // Dec 31, 2068 23:09:26.531 + String pattern = "MMM d, yyyy HH:mm:ss.SSS"; + SimpleDateFormat format = new SimpleDateFormat(pattern, + new Locale("en", "US")); + value = format.format(d); + } else { + value = "'" + o.toString() + "'"; + } + } + + return value; + + } + + public void readOnlyStatusChange(ReadOnlyStatusChangeEvent event) { + log(event.getClass().getSimpleName()); + } + + public void focus(FocusEvent event) { + log(event.getClass().getSimpleName()); + } + + public void blur(BlurEvent event) { + log(event.getClass().getSimpleName()); + } + + protected void createSetTextValueAction(String category) { + String subCategory = "Set text value"; + createCategory(subCategory, category); + List values = new ArrayList(); + values.add("Test"); + values.add("A little longer value"); + values.add("A very long value with very much text. All in all it is 74 characters long"); + + createClickAction("(empty string)", subCategory, setValueCommand, ""); + createClickAction("(null)", subCategory, setValueCommand, null); + for (String value : values) { + createClickAction(value, subCategory, setValueCommand, value); + } + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractTextFieldTest.java b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractTextFieldTest.java index eb9adef8d2..b68134f379 100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractTextFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/AbstractTextFieldTest.java @@ -1,241 +1,241 @@ -package com.vaadin.tests.components.abstractfield; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; - -import com.vaadin.event.FieldEvents.TextChangeEvent; -import com.vaadin.event.FieldEvents.TextChangeListener; -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.AbstractTextField.TextChangeEventMode; - -public abstract class AbstractTextFieldTest - extends AbstractFieldTest implements TextChangeListener { - - private Command maxlengthCommand = new Command() { - - public void execute(T c, Integer value, Object data) { - c.setMaxLength(value); - } - }; - private Command nullSelectionAllowedCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setNullSettingAllowed(value); - - } - }; - private Command nullRepresentationCommand = new Command() { - - public void execute(T c, String value, Object data) { - c.setNullRepresentation(value); - } - }; - - private Command inputPromptCommand = new Command() { - public void execute(T c, String value, Object data) { - c.setInputPrompt(value); - } - }; - - private Command textChangeListenerCommand = new Command() { - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((TextChangeListener) AbstractTextFieldTest.this); - } else { - c.removeListener((TextChangeListener) AbstractTextFieldTest.this); - } - } - }; - - private Command colsCommand = new Command() { - public void execute(T c, Integer value, Object data) { - c.setColumns(value); - } - }; - - private Command textChangeEventModeCommand = new Command() { - public void execute(T c, TextChangeEventMode value, Object data) { - c.setTextChangeEventMode(value); - } - }; - - private Command textChangeTimeoutCommand = new Command() { - public void execute(T c, Integer value, Object data) { - c.setTextChangeTimeout(value); - } - }; - - private Command selectionRangeCommand = new Command() { - public void execute(T c, Range value, Object data) { - c.setSelectionRange(value.getStart(), - value.getEnd() - value.getStart()); - - } - }; - private Command selectAllCommand = new Command() { - public void execute(T c, Object value, Object data) { - c.selectAll(); - } - }; - - private Command setCursorPositionCommand = new Command() { - - public void execute(T c, Integer value, Object data) { - c.setCursorPosition(value); - } - }; - - @Override - protected void createActions() { - super.createActions(); - - createSetTextValueAction(CATEGORY_ACTIONS); - - createNullSettingAllowedAction(CATEGORY_FEATURES); - createNullRepresentationAction(CATEGORY_FEATURES); - createMaxLengthAction(CATEGORY_FEATURES); - - createInputPromptAction(CATEGORY_FEATURES); - createColsAction(CATEGORY_STATE); - - createTextChangeListener(CATEGORY_LISTENERS); - createTextChangeEventModeAction(CATEGORY_FEATURES); - createTextChangeEventTimeoutAction(CATEGORY_FEATURES); - - createSetTextValueAction(CATEGORY_ACTIONS); - createCursorPositionAction(CATEGORY_ACTIONS); - createSelectionRangeAction(CATEGORY_ACTIONS); - - } - - private void createNullSettingAllowedAction(String category) { - createBooleanAction("Null selection allowed", category, true, - nullSelectionAllowedCommand); - } - - private void createNullRepresentationAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put("null", "null"); - options.put("This is empty", "This is empty"); - options.put("- Nothing -", "- Nothing -"); - createSelectAction("Null representation", category, options, "null", - nullRepresentationCommand); - } - - private void createMaxLengthAction(String category) { - LinkedHashMap options = createIntegerOptions(100); - options.put("-", -1); - createSelectAction("Max length", category, options, "-", - maxlengthCommand); - - } - - public class Range { - private int start; - private int end; - - public Range(int start, int end) { - this.start = start; - this.end = end; - } - - public int getStart() { - return start; - } - - public int getEnd() { - return end; - } - - @Override - public String toString() { - return start + "-" + end; - } - } - - private void createSelectionRangeAction(String category) { - List options = new ArrayList(); - options.add(new Range(0, 10)); - options.add(new Range(0, 1)); - options.add(new Range(0, 2)); - options.add(new Range(1, 2)); - options.add(new Range(2, 5)); - options.add(new Range(5, 10)); - - createCategory("Select range", category); - - createClickAction("All", "Select range", selectAllCommand, null); - for (Range range : options) { - createClickAction(range.toString(), "Select range", - selectionRangeCommand, range); - } - - } - - private void createCursorPositionAction(String category) { - String subCategory = "Set cursor position"; - createCategory(subCategory, category); - for (int i = 0; i < 20; i++) { - createClickAction(String.valueOf(i), subCategory, - setCursorPositionCommand, Integer.valueOf(i)); - } - - } - - private void createTextChangeEventTimeoutAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("0", 0); - options.put("100ms", 100); - options.put("500ms", 500); - options.put("1s", 1000); - options.put("2s", 2000); - options.put("5s", 5000); - - createSelectAction("TextChange timeout", category, options, "0", - textChangeTimeoutCommand); - } - - private void createTextChangeEventModeAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - for (TextChangeEventMode m : TextChangeEventMode.values()) { - options.put(m.toString(), m); - } - - createSelectAction("TextChange event mode", category, options, - TextChangeEventMode.EAGER.toString(), - textChangeEventModeCommand); - - } - - private void createTextChangeListener(String category) { - createBooleanAction("Text change listener", category, false, - textChangeListenerCommand); - - } - - private void createColsAction(String category) { - LinkedHashMap options = createIntegerOptions(20); - createSelectAction("Columns", category, options, "0", colsCommand); - } - - private void createInputPromptAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("-", null); - options.put("Enter a value", "Enter a value"); - options.put("- Click here -", "- Click here -"); - createSelectAction("Input prompt", category, options, "-", - inputPromptCommand); - - } - - public void textChange(TextChangeEvent event) { - AbstractTextField tf = (AbstractTextField) event.getComponent(); - log("TextChangeEvent: text='" + event.getText() + "', cursor position=" - + event.getCursorPosition() + " (field cursor pos: " - + tf.getCursorPosition() + ")"); - - } - -} +package com.vaadin.tests.components.abstractfield; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +import com.vaadin.event.FieldEvents.TextChangeEvent; +import com.vaadin.event.FieldEvents.TextChangeListener; +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.AbstractTextField.TextChangeEventMode; + +public abstract class AbstractTextFieldTest + extends AbstractFieldTest implements TextChangeListener { + + private Command maxlengthCommand = new Command() { + + public void execute(T c, Integer value, Object data) { + c.setMaxLength(value); + } + }; + private Command nullSelectionAllowedCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setNullSettingAllowed(value); + + } + }; + private Command nullRepresentationCommand = new Command() { + + public void execute(T c, String value, Object data) { + c.setNullRepresentation(value); + } + }; + + private Command inputPromptCommand = new Command() { + public void execute(T c, String value, Object data) { + c.setInputPrompt(value); + } + }; + + private Command textChangeListenerCommand = new Command() { + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((TextChangeListener) AbstractTextFieldTest.this); + } else { + c.removeListener((TextChangeListener) AbstractTextFieldTest.this); + } + } + }; + + private Command colsCommand = new Command() { + public void execute(T c, Integer value, Object data) { + c.setColumns(value); + } + }; + + private Command textChangeEventModeCommand = new Command() { + public void execute(T c, TextChangeEventMode value, Object data) { + c.setTextChangeEventMode(value); + } + }; + + private Command textChangeTimeoutCommand = new Command() { + public void execute(T c, Integer value, Object data) { + c.setTextChangeTimeout(value); + } + }; + + private Command selectionRangeCommand = new Command() { + public void execute(T c, Range value, Object data) { + c.setSelectionRange(value.getStart(), + value.getEnd() - value.getStart()); + + } + }; + private Command selectAllCommand = new Command() { + public void execute(T c, Object value, Object data) { + c.selectAll(); + } + }; + + private Command setCursorPositionCommand = new Command() { + + public void execute(T c, Integer value, Object data) { + c.setCursorPosition(value); + } + }; + + @Override + protected void createActions() { + super.createActions(); + + createSetTextValueAction(CATEGORY_ACTIONS); + + createNullSettingAllowedAction(CATEGORY_FEATURES); + createNullRepresentationAction(CATEGORY_FEATURES); + createMaxLengthAction(CATEGORY_FEATURES); + + createInputPromptAction(CATEGORY_FEATURES); + createColsAction(CATEGORY_STATE); + + createTextChangeListener(CATEGORY_LISTENERS); + createTextChangeEventModeAction(CATEGORY_FEATURES); + createTextChangeEventTimeoutAction(CATEGORY_FEATURES); + + createSetTextValueAction(CATEGORY_ACTIONS); + createCursorPositionAction(CATEGORY_ACTIONS); + createSelectionRangeAction(CATEGORY_ACTIONS); + + } + + private void createNullSettingAllowedAction(String category) { + createBooleanAction("Null selection allowed", category, true, + nullSelectionAllowedCommand); + } + + private void createNullRepresentationAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put("null", "null"); + options.put("This is empty", "This is empty"); + options.put("- Nothing -", "- Nothing -"); + createSelectAction("Null representation", category, options, "null", + nullRepresentationCommand); + } + + private void createMaxLengthAction(String category) { + LinkedHashMap options = createIntegerOptions(100); + options.put("-", -1); + createSelectAction("Max length", category, options, "-", + maxlengthCommand); + + } + + public class Range { + private int start; + private int end; + + public Range(int start, int end) { + this.start = start; + this.end = end; + } + + public int getStart() { + return start; + } + + public int getEnd() { + return end; + } + + @Override + public String toString() { + return start + "-" + end; + } + } + + private void createSelectionRangeAction(String category) { + List options = new ArrayList(); + options.add(new Range(0, 10)); + options.add(new Range(0, 1)); + options.add(new Range(0, 2)); + options.add(new Range(1, 2)); + options.add(new Range(2, 5)); + options.add(new Range(5, 10)); + + createCategory("Select range", category); + + createClickAction("All", "Select range", selectAllCommand, null); + for (Range range : options) { + createClickAction(range.toString(), "Select range", + selectionRangeCommand, range); + } + + } + + private void createCursorPositionAction(String category) { + String subCategory = "Set cursor position"; + createCategory(subCategory, category); + for (int i = 0; i < 20; i++) { + createClickAction(String.valueOf(i), subCategory, + setCursorPositionCommand, Integer.valueOf(i)); + } + + } + + private void createTextChangeEventTimeoutAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("0", 0); + options.put("100ms", 100); + options.put("500ms", 500); + options.put("1s", 1000); + options.put("2s", 2000); + options.put("5s", 5000); + + createSelectAction("TextChange timeout", category, options, "0", + textChangeTimeoutCommand); + } + + private void createTextChangeEventModeAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + for (TextChangeEventMode m : TextChangeEventMode.values()) { + options.put(m.toString(), m); + } + + createSelectAction("TextChange event mode", category, options, + TextChangeEventMode.EAGER.toString(), + textChangeEventModeCommand); + + } + + private void createTextChangeListener(String category) { + createBooleanAction("Text change listener", category, false, + textChangeListenerCommand); + + } + + private void createColsAction(String category) { + LinkedHashMap options = createIntegerOptions(20); + createSelectAction("Columns", category, options, "0", colsCommand); + } + + private void createInputPromptAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("-", null); + options.put("Enter a value", "Enter a value"); + options.put("- Click here -", "- Click here -"); + createSelectAction("Input prompt", category, options, "-", + inputPromptCommand); + + } + + public void textChange(TextChangeEvent event) { + AbstractTextField tf = (AbstractTextField) event.getComponent(); + log("TextChangeEvent: text='" + event.getText() + "', cursor position=" + + event.getCursorPosition() + " (field cursor pos: " + + tf.getCursorPosition() + ")"); + + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/abstractfield/ShortcutAddAndRemove.java b/tests/testbench/com/vaadin/tests/components/abstractfield/ShortcutAddAndRemove.java index 837256ff65..26720d67f3 100644 --- a/tests/testbench/com/vaadin/tests/components/abstractfield/ShortcutAddAndRemove.java +++ b/tests/testbench/com/vaadin/tests/components/abstractfield/ShortcutAddAndRemove.java @@ -1,64 +1,64 @@ -package com.vaadin.tests.components.abstractfield; - -import com.vaadin.event.ShortcutAction.KeyCode; -import com.vaadin.tests.components.TestBase; -import com.vaadin.tests.util.Log; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.TextArea; - -public class ShortcutAddAndRemove extends TestBase { - - private Log log; - private TextArea textArea; - - @Override - protected void setup() { - log = new Log(4); - - final Button logButton = new Button("Log a row (enter shortcut)"); - logButton.setClickShortcut(KeyCode.ENTER); - logButton.addListener(new ClickListener() { - public void buttonClick(ClickEvent event) { - log.log("Log button was clicked"); - } - }); - - final Button removeShortcut = new Button("Remove shortcut"); - removeShortcut.addListener(new ClickListener() { - public void buttonClick(ClickEvent event) { - logButton.removeClickShortcut(); - logButton.setCaption("Log a row (no shortcut)"); - } - }); - final Button addShortcut = new Button("Add shortcut"); - addShortcut.addListener(new ClickListener() { - public void buttonClick(ClickEvent event) { - logButton.setClickShortcut(KeyCode.ENTER); - logButton.setCaption("Log a row (enter shortcut)"); - } - }); - addComponent(log); - addComponent(logButton); - textArea = new TextArea("Enter key does not break lines ..."); - textArea.setRows(5); - textArea.setColumns(20); - addComponent(textArea); - addComponent(removeShortcut); - addComponent(addShortcut); - - } - - @Override - protected String getDescription() { - return null; - } - - @Override - protected Integer getTicketNumber() { - // TODO Auto-generated method stub - return null; - } - -} +package com.vaadin.tests.components.abstractfield; + +import com.vaadin.event.ShortcutAction.KeyCode; +import com.vaadin.tests.components.TestBase; +import com.vaadin.tests.util.Log; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.TextArea; + +public class ShortcutAddAndRemove extends TestBase { + + private Log log; + private TextArea textArea; + + @Override + protected void setup() { + log = new Log(4); + + final Button logButton = new Button("Log a row (enter shortcut)"); + logButton.setClickShortcut(KeyCode.ENTER); + logButton.addListener(new ClickListener() { + public void buttonClick(ClickEvent event) { + log.log("Log button was clicked"); + } + }); + + final Button removeShortcut = new Button("Remove shortcut"); + removeShortcut.addListener(new ClickListener() { + public void buttonClick(ClickEvent event) { + logButton.removeClickShortcut(); + logButton.setCaption("Log a row (no shortcut)"); + } + }); + final Button addShortcut = new Button("Add shortcut"); + addShortcut.addListener(new ClickListener() { + public void buttonClick(ClickEvent event) { + logButton.setClickShortcut(KeyCode.ENTER); + logButton.setCaption("Log a row (enter shortcut)"); + } + }); + addComponent(log); + addComponent(logButton); + textArea = new TextArea("Enter key does not break lines ..."); + textArea.setRows(5); + textArea.setColumns(20); + addComponent(textArea); + addComponent(removeShortcut); + addComponent(addShortcut); + + } + + @Override + protected String getDescription() { + return null; + } + + @Override + protected Integer getTicketNumber() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/accordion/RemoveTabs.java b/tests/testbench/com/vaadin/tests/components/accordion/RemoveTabs.java index bc8bea1c56..a048cf04a8 100644 --- a/tests/testbench/com/vaadin/tests/components/accordion/RemoveTabs.java +++ b/tests/testbench/com/vaadin/tests/components/accordion/RemoveTabs.java @@ -1,127 +1,127 @@ -package com.vaadin.tests.components.accordion; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.AbstractComponentContainer; -import com.vaadin.ui.Accordion; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Component; -import com.vaadin.ui.Label; - -public class RemoveTabs extends TestBase { - - private Accordion accordion; - - protected Component[] tab = new Component[5]; - - private Button closeCurrent; - private Button closeFirst; - private Button closeLast; - private Button reorderTabs; - - @Override - protected Integer getTicketNumber() { - return 2425; - } - - @Override - protected String getDescription() { - return "Tests the removal of individual tabs from an Accordion. No matter what is done in this test the tab caption \"Tab X\" should always match the content \"Tab X\". Use \"remove first\" and \"remove active\" buttons to remove the first or the active tab. The \"reorder\" button reverses the order by adding and removing all components."; - } - - @Override - protected void setup() { - accordion = new Accordion(); - for (int i = 1; i <= tab.length; i++) { - tab[i - 1] = new Label("This is the contents of tab " + i); - tab[i - 1].setCaption("Tab " + i); - - accordion.addComponent(tab[i - 1]); - } - - getLayout().addComponent(accordion); - - closeCurrent = new Button("Close current tab"); - closeCurrent.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - closeCurrentTab(); - - } - }); - - closeFirst = new Button("close first tab"); - closeFirst.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - closeFirstTab(); - - } - }); - - closeLast = new Button("close last tab"); - closeLast.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - closeLastTab(); - - } - }); - - reorderTabs = new Button("reorder"); - reorderTabs.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - reorder(); - - } - }); - - getLayout().addComponent(closeFirst); - getLayout().addComponent(closeLast); - getLayout().addComponent(closeCurrent); - getLayout().addComponent(reorderTabs); - - } - - private void closeCurrentTab() { - Component c = accordion.getSelectedTab(); - if (c != null) { - accordion.removeComponent(c); - } - } - - private void closeFirstTab() { - accordion.removeComponent(accordion.getComponentIterator().next()); - } - - private void closeLastTab() { - Iterator i = accordion.getComponentIterator(); - Component last = null; - while (i.hasNext()) { - last = i.next(); - - } - accordion.removeComponent(last); - } - - private void reorder() { - AbstractComponentContainer container = accordion; - - if (container != null) { - List c = new ArrayList(); - Iterator i = container.getComponentIterator(); - while (i.hasNext()) { - Component comp = i.next(); - c.add(comp); - } - container.removeAllComponents(); - - for (int j = c.size() - 1; j >= 0; j--) { - container.addComponent(c.get(j)); - } - - } - } - -} +package com.vaadin.tests.components.accordion; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.AbstractComponentContainer; +import com.vaadin.ui.Accordion; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; + +public class RemoveTabs extends TestBase { + + private Accordion accordion; + + protected Component[] tab = new Component[5]; + + private Button closeCurrent; + private Button closeFirst; + private Button closeLast; + private Button reorderTabs; + + @Override + protected Integer getTicketNumber() { + return 2425; + } + + @Override + protected String getDescription() { + return "Tests the removal of individual tabs from an Accordion. No matter what is done in this test the tab caption \"Tab X\" should always match the content \"Tab X\". Use \"remove first\" and \"remove active\" buttons to remove the first or the active tab. The \"reorder\" button reverses the order by adding and removing all components."; + } + + @Override + protected void setup() { + accordion = new Accordion(); + for (int i = 1; i <= tab.length; i++) { + tab[i - 1] = new Label("This is the contents of tab " + i); + tab[i - 1].setCaption("Tab " + i); + + accordion.addComponent(tab[i - 1]); + } + + getLayout().addComponent(accordion); + + closeCurrent = new Button("Close current tab"); + closeCurrent.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + closeCurrentTab(); + + } + }); + + closeFirst = new Button("close first tab"); + closeFirst.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + closeFirstTab(); + + } + }); + + closeLast = new Button("close last tab"); + closeLast.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + closeLastTab(); + + } + }); + + reorderTabs = new Button("reorder"); + reorderTabs.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + reorder(); + + } + }); + + getLayout().addComponent(closeFirst); + getLayout().addComponent(closeLast); + getLayout().addComponent(closeCurrent); + getLayout().addComponent(reorderTabs); + + } + + private void closeCurrentTab() { + Component c = accordion.getSelectedTab(); + if (c != null) { + accordion.removeComponent(c); + } + } + + private void closeFirstTab() { + accordion.removeComponent(accordion.getComponentIterator().next()); + } + + private void closeLastTab() { + Iterator i = accordion.getComponentIterator(); + Component last = null; + while (i.hasNext()) { + last = i.next(); + + } + accordion.removeComponent(last); + } + + private void reorder() { + AbstractComponentContainer container = accordion; + + if (container != null) { + List c = new ArrayList(); + Iterator i = container.getComponentIterator(); + while (i.hasNext()) { + Component comp = i.next(); + c.add(comp); + } + container.removeAllComponents(); + + for (int j = c.size() - 1; j >= 0; j--) { + container.addComponent(c.get(j)); + } + + } + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/button/ButtonErrorMessage.java b/tests/testbench/com/vaadin/tests/components/button/ButtonErrorMessage.java index b543c69c51..aca85d4efe 100644 --- a/tests/testbench/com/vaadin/tests/components/button/ButtonErrorMessage.java +++ b/tests/testbench/com/vaadin/tests/components/button/ButtonErrorMessage.java @@ -1,31 +1,31 @@ -package com.vaadin.tests.components.button; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; - -public class ButtonErrorMessage extends TestBase { - - @Override - protected void setup() { - Button b = new Button("Click for error"); - b.addListener(new ClickListener() { - public void buttonClick(ClickEvent event) { - throw new NullPointerException(); - } - }); - addComponent(b); - } - - @Override - protected String getDescription() { - return "Click the button for an exception. The exception should not contain any extra ',' characters"; - } - - @Override - protected Integer getTicketNumber() { - return 3303; - } - -} +package com.vaadin.tests.components.button; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; + +public class ButtonErrorMessage extends TestBase { + + @Override + protected void setup() { + Button b = new Button("Click for error"); + b.addListener(new ClickListener() { + public void buttonClick(ClickEvent event) { + throw new NullPointerException(); + } + }); + addComponent(b); + } + + @Override + protected String getDescription() { + return "Click the button for an exception. The exception should not contain any extra ',' characters"; + } + + @Override + protected Integer getTicketNumber() { + return 3303; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/button/ButtonUndefinedWidth.java b/tests/testbench/com/vaadin/tests/components/button/ButtonUndefinedWidth.java index 852e41bd05..89b03df92a 100644 --- a/tests/testbench/com/vaadin/tests/components/button/ButtonUndefinedWidth.java +++ b/tests/testbench/com/vaadin/tests/components/button/ButtonUndefinedWidth.java @@ -1,40 +1,40 @@ -package com.vaadin.tests.components.button; - -import com.vaadin.data.Item; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.NativeButton; -import com.vaadin.ui.Table; - -public class ButtonUndefinedWidth extends TestBase { - - @Override - protected String getDescription() { - return "Both the button outside the table and inside the table should be only as wide as necessary. There should be empty space in the table to the right of the button."; - } - - @Override - protected Integer getTicketNumber() { - return 3257; - } - - @Override - protected void setup() { - Button b = new Button("Undefined wide"); - addComponent(b); - NativeButton b2 = new NativeButton("Undefined wide"); - addComponent(b2); - - Table t = new Table(); - t.addContainerProperty("A", Button.class, null); - t.setWidth("500px"); - - Item i = t.addItem("1"); - i.getItemProperty("A").setValue(new Button("Undef wide")); - Item i2 = t.addItem("2"); - i2.getItemProperty("A").setValue(new NativeButton("Undef wide")); - - addComponent(t); - } - -} +package com.vaadin.tests.components.button; + +import com.vaadin.data.Item; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.Table; + +public class ButtonUndefinedWidth extends TestBase { + + @Override + protected String getDescription() { + return "Both the button outside the table and inside the table should be only as wide as necessary. There should be empty space in the table to the right of the button."; + } + + @Override + protected Integer getTicketNumber() { + return 3257; + } + + @Override + protected void setup() { + Button b = new Button("Undefined wide"); + addComponent(b); + NativeButton b2 = new NativeButton("Undefined wide"); + addComponent(b2); + + Table t = new Table(); + t.addContainerProperty("A", Button.class, null); + t.setWidth("500px"); + + Item i = t.addItem("1"); + i.getItemProperty("A").setValue(new Button("Undef wide")); + Item i2 = t.addItem("2"); + i2.getItemProperty("A").setValue(new NativeButton("Undef wide")); + + addComponent(t); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/button/Buttons2.java b/tests/testbench/com/vaadin/tests/components/button/Buttons2.java index c18e736082..b65a9fc0cd 100644 --- a/tests/testbench/com/vaadin/tests/components/button/Buttons2.java +++ b/tests/testbench/com/vaadin/tests/components/button/Buttons2.java @@ -1,74 +1,74 @@ -package com.vaadin.tests.components.button; - -import java.util.LinkedHashMap; - -import com.vaadin.tests.components.abstractfield.AbstractFieldTest; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.themes.Reindeer; - -public class Buttons2 extends AbstractFieldTest implements - ClickListener { - - private Command switchModeCommand = new Command() { - - @SuppressWarnings("deprecation") - public void execute(T c, Boolean value, Object data) { - c.setSwitchMode(value); - } - }; - - private Command disableOnClickCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setDisableOnClick(value); - } - }; - - private Command clickListenerCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - if (value) { - c.addListener((Button.ClickListener) Buttons2.this); - } else { - c.removeListener((Button.ClickListener) Buttons2.this); - } - - } - }; - - @Override - protected Class getTestClass() { - return (Class) Button.class; - } - - @Override - protected void createActions() { - super.createActions(); - - createBooleanAction("Switch mode", CATEGORY_FEATURES, false, - switchModeCommand); - createBooleanAction("Disable on click", CATEGORY_FEATURES, false, - disableOnClickCommand); - addClickListener(CATEGORY_LISTENERS); - } - - @Override - protected void createComponentStyleNames( - LinkedHashMap options) { - options.put("Reindeer default", Reindeer.BUTTON_DEFAULT); - options.put("Reindeer small", Reindeer.BUTTON_SMALL); - options.put("Reindeer link", Reindeer.BUTTON_LINK); - } - - private void addClickListener(String category) { - createBooleanAction("Click listener", category, false, - clickListenerCommand); - - } - - public void buttonClick(ClickEvent event) { - log(event.getClass().getSimpleName()); - } -} +package com.vaadin.tests.components.button; + +import java.util.LinkedHashMap; + +import com.vaadin.tests.components.abstractfield.AbstractFieldTest; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.themes.Reindeer; + +public class Buttons2 extends AbstractFieldTest implements + ClickListener { + + private Command switchModeCommand = new Command() { + + @SuppressWarnings("deprecation") + public void execute(T c, Boolean value, Object data) { + c.setSwitchMode(value); + } + }; + + private Command disableOnClickCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setDisableOnClick(value); + } + }; + + private Command clickListenerCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + if (value) { + c.addListener((Button.ClickListener) Buttons2.this); + } else { + c.removeListener((Button.ClickListener) Buttons2.this); + } + + } + }; + + @Override + protected Class getTestClass() { + return (Class) Button.class; + } + + @Override + protected void createActions() { + super.createActions(); + + createBooleanAction("Switch mode", CATEGORY_FEATURES, false, + switchModeCommand); + createBooleanAction("Disable on click", CATEGORY_FEATURES, false, + disableOnClickCommand); + addClickListener(CATEGORY_LISTENERS); + } + + @Override + protected void createComponentStyleNames( + LinkedHashMap options) { + options.put("Reindeer default", Reindeer.BUTTON_DEFAULT); + options.put("Reindeer small", Reindeer.BUTTON_SMALL); + options.put("Reindeer link", Reindeer.BUTTON_LINK); + } + + private void addClickListener(String category) { + createBooleanAction("Click listener", category, false, + clickListenerCommand); + + } + + public void buttonClick(ClickEvent event) { + log(event.getClass().getSimpleName()); + } +} diff --git a/tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java b/tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java index cca76ce418..46d92c3a03 100644 --- a/tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java +++ b/tests/testbench/com/vaadin/tests/components/button/ButtonsInHorizontalLayout.java @@ -1,52 +1,52 @@ -package com.vaadin.tests.components.button; - -import com.vaadin.tests.components.AbstractTestCase; -import com.vaadin.ui.Button; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.Window; -import com.vaadin.ui.themes.BaseTheme; - -public class ButtonsInHorizontalLayout extends AbstractTestCase { - - @Override - public void init() { - VerticalLayout content = new VerticalLayout(); - content.setMargin(true); - content.setSpacing(true); - - content.addComponent(createButtonLayout(null)); - content.addComponent(createButtonLayout(BaseTheme.BUTTON_LINK)); - - setMainWindow(new Window("", content)); - } - - private HorizontalLayout createButtonLayout(String style) { - HorizontalLayout layout = new HorizontalLayout(); - layout.setSpacing(true); - layout.addComponent(createButton(style)); - layout.addComponent(createButton(style)); - layout.addComponent(createButton(style)); - return layout; - } - - private Button createButton(String style) { - Button button = new Button( - "Look at me in IE7 or IE8 in compatibility mode"); - if (style != null && style.length() != 0) { - button.setStyleName(style); - } - return button; - } - - @Override - protected String getDescription() { - return "Tests for rendering of buttons in a HorizontalLayout"; - } - - @Override - protected Integer getTicketNumber() { - return 7978; - } - -} +package com.vaadin.tests.components.button; + +import com.vaadin.tests.components.AbstractTestCase; +import com.vaadin.ui.Button; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; +import com.vaadin.ui.themes.BaseTheme; + +public class ButtonsInHorizontalLayout extends AbstractTestCase { + + @Override + public void init() { + VerticalLayout content = new VerticalLayout(); + content.setMargin(true); + content.setSpacing(true); + + content.addComponent(createButtonLayout(null)); + content.addComponent(createButtonLayout(BaseTheme.BUTTON_LINK)); + + setMainWindow(new Window("", content)); + } + + private HorizontalLayout createButtonLayout(String style) { + HorizontalLayout layout = new HorizontalLayout(); + layout.setSpacing(true); + layout.addComponent(createButton(style)); + layout.addComponent(createButton(style)); + layout.addComponent(createButton(style)); + return layout; + } + + private Button createButton(String style) { + Button button = new Button( + "Look at me in IE7 or IE8 in compatibility mode"); + if (style != null && style.length() != 0) { + button.setStyleName(style); + } + return button; + } + + @Override + protected String getDescription() { + return "Tests for rendering of buttons in a HorizontalLayout"; + } + + @Override + protected Integer getTicketNumber() { + return 7978; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/button/TooltipForDisabledButton.java b/tests/testbench/com/vaadin/tests/components/button/TooltipForDisabledButton.java index 3fed5b9c02..4952b4bc50 100644 --- a/tests/testbench/com/vaadin/tests/components/button/TooltipForDisabledButton.java +++ b/tests/testbench/com/vaadin/tests/components/button/TooltipForDisabledButton.java @@ -1,48 +1,48 @@ -package com.vaadin.tests.components.button; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; - -public class TooltipForDisabledButton extends TestBase { - - @Override - protected String getDescription() { - return "A disabled button should show a tooltip when hovering it"; - } - - @Override - protected Integer getTicketNumber() { - return 2085; - } - - @Override - protected void setup() { - Button buttonEnabled = new Button("This is an enabled button"); - Button buttonDisabled = new Button("This is an disabled button"); - buttonDisabled.setEnabled(false); - - buttonEnabled.setDescription("Tooltip for enabled"); - buttonDisabled.setDescription("Tooltip for disabled"); - - buttonDisabled.addListener(new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - getMainWindow().showNotification("Clicked Disabled"); - } - - }); - - buttonEnabled.addListener(new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - getMainWindow().showNotification("Clicked Enabled"); - } - - }); - - addComponent(buttonEnabled); - addComponent(buttonDisabled); - } - -} +package com.vaadin.tests.components.button; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; + +public class TooltipForDisabledButton extends TestBase { + + @Override + protected String getDescription() { + return "A disabled button should show a tooltip when hovering it"; + } + + @Override + protected Integer getTicketNumber() { + return 2085; + } + + @Override + protected void setup() { + Button buttonEnabled = new Button("This is an enabled button"); + Button buttonDisabled = new Button("This is an disabled button"); + buttonDisabled.setEnabled(false); + + buttonEnabled.setDescription("Tooltip for enabled"); + buttonDisabled.setDescription("Tooltip for disabled"); + + buttonDisabled.addListener(new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + getMainWindow().showNotification("Clicked Disabled"); + } + + }); + + buttonEnabled.addListener(new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + getMainWindow().showNotification("Clicked Enabled"); + } + + }); + + addComponent(buttonEnabled); + addComponent(buttonDisabled); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/caption/EmptyCaptions.java b/tests/testbench/com/vaadin/tests/components/caption/EmptyCaptions.java index 86f0bd6b9d..8e0e8d1071 100644 --- a/tests/testbench/com/vaadin/tests/components/caption/EmptyCaptions.java +++ b/tests/testbench/com/vaadin/tests/components/caption/EmptyCaptions.java @@ -1,56 +1,56 @@ -package com.vaadin.tests.components.caption; - -import com.vaadin.terminal.UserError; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.TextField; - -public class EmptyCaptions extends TestBase { - - @Override - protected void setup() { - TextField tf; - - tf = new TextField(null, "Null caption"); - addComponent(tf); - - tf = new TextField("", "Empty caption"); - addComponent(tf); - - tf = new TextField(" ", "Space as caption"); - addComponent(tf); - - tf = new TextField(null, "Null caption, required"); - tf.setRequired(true); - addComponent(tf); - tf = new TextField("", "Empty caption, required"); - tf.setRequired(true); - addComponent(tf); - tf = new TextField(" ", "Space as caption, required"); - tf.setRequired(true); - addComponent(tf); - - tf = new TextField(null, "Null caption, error"); - tf.setComponentError(new UserError("error")); - addComponent(tf); - - tf = new TextField("", "Empty caption, error"); - tf.setComponentError(new UserError("error")); - addComponent(tf); - - tf = new TextField(" ", "Space as caption, error"); - tf.setComponentError(new UserError("error")); - addComponent(tf); - - } - - @Override - protected String getDescription() { - return "Null caption should never use space while a non-null caption always should use space."; - } - - @Override - protected Integer getTicketNumber() { - return 3846; - } - -} +package com.vaadin.tests.components.caption; + +import com.vaadin.terminal.UserError; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.TextField; + +public class EmptyCaptions extends TestBase { + + @Override + protected void setup() { + TextField tf; + + tf = new TextField(null, "Null caption"); + addComponent(tf); + + tf = new TextField("", "Empty caption"); + addComponent(tf); + + tf = new TextField(" ", "Space as caption"); + addComponent(tf); + + tf = new TextField(null, "Null caption, required"); + tf.setRequired(true); + addComponent(tf); + tf = new TextField("", "Empty caption, required"); + tf.setRequired(true); + addComponent(tf); + tf = new TextField(" ", "Space as caption, required"); + tf.setRequired(true); + addComponent(tf); + + tf = new TextField(null, "Null caption, error"); + tf.setComponentError(new UserError("error")); + addComponent(tf); + + tf = new TextField("", "Empty caption, error"); + tf.setComponentError(new UserError("error")); + addComponent(tf); + + tf = new TextField(" ", "Space as caption, error"); + tf.setComponentError(new UserError("error")); + addComponent(tf); + + } + + @Override + protected String getDescription() { + return "Null caption should never use space while a non-null caption always should use space."; + } + + @Override + protected Integer getTicketNumber() { + return 3846; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes.java b/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes.java index 0efa8bc818..f4d65b8d53 100644 --- a/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes.java +++ b/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes.java @@ -1,76 +1,76 @@ -package com.vaadin.tests.components.checkbox; - -import java.util.Date; - -import com.vaadin.terminal.Resource; -import com.vaadin.terminal.ThemeResource; -import com.vaadin.tests.components.ComponentTestCase; -import com.vaadin.ui.CheckBox; - -public class CheckBoxes extends ComponentTestCase { - - private ThemeResource SMALL_ICON = new ThemeResource( - "../runo/icons/16/ok.png"); - private ThemeResource LARGE_ICON = new ThemeResource( - "../runo/icons/64/document.png"); - private ThemeResource LARGE_ICON_NOCACHE = new ThemeResource( - "../runo/icons/64/document.png?" + new Date().getTime()); - - @Override - protected Class getTestClass() { - return CheckBox.class; - } - - @Override - protected void initializeComponents() { - - setTheme("tests-tickets"); - CheckBox cb; - - cb = createCheckBox("CheckBox with normal text"); - addTestComponent(cb); - - cb = createCheckBox("CheckBox with large text"); - cb.setStyleName("large"); - addTestComponent(cb); - - cb = createCheckBox("CheckBox with normal text and small icon", - SMALL_ICON); - addTestComponent(cb); - cb = createCheckBox("CheckBox with large text and small icon", - SMALL_ICON); - cb.setStyleName("large"); - addTestComponent(cb); - - cb = createCheckBox("CheckBox with normal text and large icon", - LARGE_ICON); - addTestComponent(cb); - cb = createCheckBox("CheckBox with large text and large icon", - LARGE_ICON_NOCACHE); - cb.setStyleName("large"); - addTestComponent(cb); - - } - - private CheckBox createCheckBox(String caption, Resource icon) { - CheckBox cb = createCheckBox(caption); - cb.setIcon(icon); - - return cb; - } - - private CheckBox createCheckBox(String caption) { - return new CheckBox(caption); - } - - @Override - protected String getDescription() { - return "A generic test for CheckBoxes in different configurations"; - } - - @Override - protected Integer getTicketNumber() { - return null; - } - -} +package com.vaadin.tests.components.checkbox; + +import java.util.Date; + +import com.vaadin.terminal.Resource; +import com.vaadin.terminal.ThemeResource; +import com.vaadin.tests.components.ComponentTestCase; +import com.vaadin.ui.CheckBox; + +public class CheckBoxes extends ComponentTestCase { + + private ThemeResource SMALL_ICON = new ThemeResource( + "../runo/icons/16/ok.png"); + private ThemeResource LARGE_ICON = new ThemeResource( + "../runo/icons/64/document.png"); + private ThemeResource LARGE_ICON_NOCACHE = new ThemeResource( + "../runo/icons/64/document.png?" + new Date().getTime()); + + @Override + protected Class getTestClass() { + return CheckBox.class; + } + + @Override + protected void initializeComponents() { + + setTheme("tests-tickets"); + CheckBox cb; + + cb = createCheckBox("CheckBox with normal text"); + addTestComponent(cb); + + cb = createCheckBox("CheckBox with large text"); + cb.setStyleName("large"); + addTestComponent(cb); + + cb = createCheckBox("CheckBox with normal text and small icon", + SMALL_ICON); + addTestComponent(cb); + cb = createCheckBox("CheckBox with large text and small icon", + SMALL_ICON); + cb.setStyleName("large"); + addTestComponent(cb); + + cb = createCheckBox("CheckBox with normal text and large icon", + LARGE_ICON); + addTestComponent(cb); + cb = createCheckBox("CheckBox with large text and large icon", + LARGE_ICON_NOCACHE); + cb.setStyleName("large"); + addTestComponent(cb); + + } + + private CheckBox createCheckBox(String caption, Resource icon) { + CheckBox cb = createCheckBox(caption); + cb.setIcon(icon); + + return cb; + } + + private CheckBox createCheckBox(String caption) { + return new CheckBox(caption); + } + + @Override + protected String getDescription() { + return "A generic test for CheckBoxes in different configurations"; + } + + @Override + protected Integer getTicketNumber() { + return null; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java b/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java index 20f1ece65e..2af1e41867 100644 --- a/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java +++ b/tests/testbench/com/vaadin/tests/components/checkbox/CheckBoxes2.java @@ -1,56 +1,56 @@ -package com.vaadin.tests.components.checkbox; - -import com.vaadin.tests.components.abstractfield.AbstractFieldTest; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.CheckBox; - -public class CheckBoxes2 extends AbstractFieldTest implements - ClickListener { - - // cannot extend Buttons2 because of Switch mode problems - - @Override - protected Class getTestClass() { - return CheckBox.class; - } - - private Command switchModeCommand = new Command() { - - @SuppressWarnings("deprecation") - public void execute(CheckBox c, Boolean value, Object data) { - c.setSwitchMode(value); - } - }; - - private Command clickListenerCommand = new Command() { - - public void execute(CheckBox c, Boolean value, Object data) { - if (value) { - c.addListener((ClickListener) CheckBoxes2.this); - } else { - c.removeListener((ClickListener) CheckBoxes2.this); - } - - } - }; - - @Override - protected void createActions() { - super.createActions(); - - createBooleanAction("Switch mode", CATEGORY_FEATURES, true, - switchModeCommand); - addClickListener(CATEGORY_LISTENERS); - } - - private void addClickListener(String category) { - createBooleanAction("Click listener", category, false, - clickListenerCommand); - - } - - public void buttonClick(ClickEvent event) { - log(event.getClass().getSimpleName()); - } -} +package com.vaadin.tests.components.checkbox; + +import com.vaadin.tests.components.abstractfield.AbstractFieldTest; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.CheckBox; + +public class CheckBoxes2 extends AbstractFieldTest implements + ClickListener { + + // cannot extend Buttons2 because of Switch mode problems + + @Override + protected Class getTestClass() { + return CheckBox.class; + } + + private Command switchModeCommand = new Command() { + + @SuppressWarnings("deprecation") + public void execute(CheckBox c, Boolean value, Object data) { + c.setSwitchMode(value); + } + }; + + private Command clickListenerCommand = new Command() { + + public void execute(CheckBox c, Boolean value, Object data) { + if (value) { + c.addListener((ClickListener) CheckBoxes2.this); + } else { + c.removeListener((ClickListener) CheckBoxes2.this); + } + + } + }; + + @Override + protected void createActions() { + super.createActions(); + + createBooleanAction("Switch mode", CATEGORY_FEATURES, true, + switchModeCommand); + addClickListener(CATEGORY_LISTENERS); + } + + private void addClickListener(String category) { + createBooleanAction("Click listener", category, false, + clickListenerCommand); + + } + + public void buttonClick(ClickEvent event) { + log(event.getClass().getSimpleName()); + } +} diff --git a/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxCaptionWrapping.java b/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxCaptionWrapping.java index 540af083c4..463d53a4a8 100644 --- a/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxCaptionWrapping.java +++ b/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxCaptionWrapping.java @@ -1,39 +1,39 @@ -package com.vaadin.tests.components.checkbox; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.CheckBox; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; - -public class CheckboxCaptionWrapping extends TestBase { - - @Override - protected String getDescription() { - return "The checkbox caption consists of 10 words which should all be shown. There should be no extra white space between the checkbox caption and the label below it."; - } - - @Override - protected Integer getTicketNumber() { - return 3263; - } - - @Override - protected void setup() { - setTheme("tests-tickets"); - VerticalLayout mainLayout = new VerticalLayout(); - CheckBox cb = new CheckBox( - "Checkbox with some Incididunt ut labore et dolore magna aliqua."); - cb.setStyleName("wrap"); - cb.setWidth("100%"); - mainLayout.setStyleName("borders"); - mainLayout.setWidth("300px"); - mainLayout.addComponent(cb); - mainLayout.addComponent(new Label( - "Lorem ipsum dolor sit amet, consectetur adipisicing" - + " elit, sed do eiusmod tempor.")); - - addComponent(mainLayout); - - } - -} +package com.vaadin.tests.components.checkbox; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; + +public class CheckboxCaptionWrapping extends TestBase { + + @Override + protected String getDescription() { + return "The checkbox caption consists of 10 words which should all be shown. There should be no extra white space between the checkbox caption and the label below it."; + } + + @Override + protected Integer getTicketNumber() { + return 3263; + } + + @Override + protected void setup() { + setTheme("tests-tickets"); + VerticalLayout mainLayout = new VerticalLayout(); + CheckBox cb = new CheckBox( + "Checkbox with some Incididunt ut labore et dolore magna aliqua."); + cb.setStyleName("wrap"); + cb.setWidth("100%"); + mainLayout.setStyleName("borders"); + mainLayout.setWidth("300px"); + mainLayout.addComponent(cb); + mainLayout.addComponent(new Label( + "Lorem ipsum dolor sit amet, consectetur adipisicing" + + " elit, sed do eiusmod tempor.")); + + addComponent(mainLayout); + + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxIcon.java b/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxIcon.java index 1f96a05084..6fa714a6d7 100644 --- a/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxIcon.java +++ b/tests/testbench/com/vaadin/tests/components/checkbox/CheckboxIcon.java @@ -1,29 +1,29 @@ -package com.vaadin.tests.components.checkbox; - -import com.vaadin.terminal.ThemeResource; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.CheckBox; - -public class CheckboxIcon extends TestBase { - - @Override - protected String getDescription() { - return "The icon of a Checkbox component should have the same cursor as the text and should be clickable. The tooltip should appear when hovering the checkbox, the icon or the caption."; - } - - @Override - protected Integer getTicketNumber() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected void setup() { - CheckBox checkbox = new CheckBox("A checkbox"); - checkbox.setIcon(new ThemeResource("../runo/icons/32/calendar.png")); - checkbox.setDescription("Tooltip for checkbox"); - - addComponent(checkbox); - } - -} +package com.vaadin.tests.components.checkbox; + +import com.vaadin.terminal.ThemeResource; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.CheckBox; + +public class CheckboxIcon extends TestBase { + + @Override + protected String getDescription() { + return "The icon of a Checkbox component should have the same cursor as the text and should be clickable. The tooltip should appear when hovering the checkbox, the icon or the caption."; + } + + @Override + protected Integer getTicketNumber() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected void setup() { + CheckBox checkbox = new CheckBox("A checkbox"); + checkbox.setIcon(new ThemeResource("../runo/icons/32/calendar.png")); + checkbox.setDescription("Tooltip for checkbox"); + + addComponent(checkbox); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxDataSourceChange.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxDataSourceChange.java index adeaede187..9285983b99 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxDataSourceChange.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxDataSourceChange.java @@ -1,102 +1,102 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.data.Property; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.ComboBox; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.Table; - -@SuppressWarnings("serial") -public class ComboBoxDataSourceChange extends TestBase { - - private ComboBox cb2; - - @Override - protected void setup() { - final IndexedContainer ds1 = new IndexedContainer(); - // ds1.addContainerProperty("caption", String.class, ""); - for (int i = 0; i < 32; i++) { - ds1.addItem("ds1-" + i); - } - - final IndexedContainer ds2 = new IndexedContainer(); - // ds2.addContainerProperty("caption", String.class, ""); - for (int i = 0; i < 32; i++) { - ds2.addItem("ds2-" + i); - } - - HorizontalLayout hl = new HorizontalLayout(); - hl.setWidth("100%"); - - cb2 = new ComboBox(); - cb2.setImmediate(true); - hl.addComponent(cb2); - HorizontalLayout state = new HorizontalLayout(); - state.setSpacing(true); - hl.addComponent(state); - - final Label currentValue = new Label(); - currentValue.setCaption("Current Value:"); - currentValue.setSizeUndefined(); - final Label currentDS = new Label(); - currentDS.setCaption("Current DS:"); - currentDS.setSizeUndefined(); - state.addComponent(currentValue); - state.addComponent(currentDS); - - Table t = new Table("ds1"); - t.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); - t.setContainerDataSource(ds1); - state.addComponent(t); - - Button b = new Button("Use ds1"); - b.addListener(new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cb2.setContainerDataSource(ds1); - currentDS.setValue("ds1"); - } - }); - state.addComponent(b); - - t = new Table("ds2"); - t.setContainerDataSource(ds2); - t.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); - state.addComponent(t); - - b = new Button("Use ds2"); - b.addListener(new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - cb2.setContainerDataSource(ds2); - currentDS.setValue("ds2"); - } - }); - state.addComponent(b); - - addComponent(hl); - - cb2.addListener(new Property.ValueChangeListener() { - public void valueChange(ValueChangeEvent event) { - currentValue.setValue(event.getProperty().getValue()); - } - }); - } - - @Override - protected String getDescription() { - return "A test for combobox and its container changes."; - } - - @Override - protected Integer getTicketNumber() { - // TODO should be list of integers applies for #5279 - return 4607; - } - -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.data.Property; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.ComboBox; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Table; + +@SuppressWarnings("serial") +public class ComboBoxDataSourceChange extends TestBase { + + private ComboBox cb2; + + @Override + protected void setup() { + final IndexedContainer ds1 = new IndexedContainer(); + // ds1.addContainerProperty("caption", String.class, ""); + for (int i = 0; i < 32; i++) { + ds1.addItem("ds1-" + i); + } + + final IndexedContainer ds2 = new IndexedContainer(); + // ds2.addContainerProperty("caption", String.class, ""); + for (int i = 0; i < 32; i++) { + ds2.addItem("ds2-" + i); + } + + HorizontalLayout hl = new HorizontalLayout(); + hl.setWidth("100%"); + + cb2 = new ComboBox(); + cb2.setImmediate(true); + hl.addComponent(cb2); + HorizontalLayout state = new HorizontalLayout(); + state.setSpacing(true); + hl.addComponent(state); + + final Label currentValue = new Label(); + currentValue.setCaption("Current Value:"); + currentValue.setSizeUndefined(); + final Label currentDS = new Label(); + currentDS.setCaption("Current DS:"); + currentDS.setSizeUndefined(); + state.addComponent(currentValue); + state.addComponent(currentDS); + + Table t = new Table("ds1"); + t.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); + t.setContainerDataSource(ds1); + state.addComponent(t); + + Button b = new Button("Use ds1"); + b.addListener(new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cb2.setContainerDataSource(ds1); + currentDS.setValue("ds1"); + } + }); + state.addComponent(b); + + t = new Table("ds2"); + t.setContainerDataSource(ds2); + t.setRowHeaderMode(Table.ROW_HEADER_MODE_ID); + state.addComponent(t); + + b = new Button("Use ds2"); + b.addListener(new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + cb2.setContainerDataSource(ds2); + currentDS.setValue("ds2"); + } + }); + state.addComponent(b); + + addComponent(hl); + + cb2.addListener(new Property.ValueChangeListener() { + public void valueChange(ValueChangeEvent event) { + currentValue.setValue(event.getProperty().getValue()); + } + }); + } + + @Override + protected String getDescription() { + return "A test for combobox and its container changes."; + } + + @Override + protected Integer getTicketNumber() { + // TODO should be list of integers applies for #5279 + return 4607; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxEnablesComboBox.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxEnablesComboBox.java index 6178d25a2a..d9739602f6 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxEnablesComboBox.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxEnablesComboBox.java @@ -1,49 +1,49 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.ComboBox; - -public class ComboBoxEnablesComboBox extends TestBase { - - private ComboBox cb2; - - @Override - protected void setup() { - ComboBox cb = new ComboBox("Always enabled"); - cb.setImmediate(true); - populate(cb); - cb.addListener(new ValueChangeListener() { - - public void valueChange(ValueChangeEvent event) { - cb2.setEnabled(true); - } - - }); - cb2 = new ComboBox("Initially disabled"); - cb2.setImmediate(true); - cb2.setEnabled(false); - populate(cb2); - - addComponent(cb); - addComponent(cb2); - } - - private void populate(ComboBox cb) { - for (int i = 1; i < 10; i++) { - cb.addItem("Item " + i); - } - } - - @Override - protected String getDescription() { - return "Selecting an item in the first combobox enables the second."; - } - - @Override - protected Integer getTicketNumber() { - return 4632; - } - -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.ComboBox; + +public class ComboBoxEnablesComboBox extends TestBase { + + private ComboBox cb2; + + @Override + protected void setup() { + ComboBox cb = new ComboBox("Always enabled"); + cb.setImmediate(true); + populate(cb); + cb.addListener(new ValueChangeListener() { + + public void valueChange(ValueChangeEvent event) { + cb2.setEnabled(true); + } + + }); + cb2 = new ComboBox("Initially disabled"); + cb2.setImmediate(true); + cb2.setEnabled(false); + populate(cb2); + + addComponent(cb); + addComponent(cb2); + } + + private void populate(ComboBox cb) { + for (int i = 1; i < 10; i++) { + cb.addItem("Item " + i); + } + } + + @Override + protected String getDescription() { + return "Selecting an item in the first combobox enables the second."; + } + + @Override + protected Integer getTicketNumber() { + return 4632; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxIdenticalItems.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxIdenticalItems.java index dcd4af58ad..fd434a7acd 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxIdenticalItems.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxIdenticalItems.java @@ -1,54 +1,54 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.data.Item; -import com.vaadin.data.Property; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.tests.components.TestBase; -import com.vaadin.tests.util.Log; -import com.vaadin.ui.ComboBox; - -public class ComboBoxIdenticalItems extends TestBase { - - private Log log = new Log(5); - - @Override - public void setup() { - final ComboBox select = new ComboBox("ComboBox"); - select.addContainerProperty("caption", String.class, null); - Item item = select.addItem("one-1"); - item.getItemProperty("caption").setValue("One"); - item = select.addItem("one-2"); - item.getItemProperty("caption").setValue("One"); - item = select.addItem("two"); - item.getItemProperty("caption").setValue("Two"); - select.setItemCaptionPropertyId("caption"); - select.setNullSelectionAllowed(false); - select.setImmediate(true); - select.addListener(new Property.ValueChangeListener() { - private static final long serialVersionUID = -7932700771673919620L; - - public void valueChange(ValueChangeEvent event) { - log.log("Item " + select.getValue() + " selected"); - - } - }); - - addComponent(log); - addComponent(select); - } - - @Override - protected String getDescription() { - return "Keyboard selecting of a value is broken in combobox if two " - + "items have the same caption. The first item's id is \"One-1\" " - + "while the second one is \"One-2\". Selecting with mouse works " - + "as expected but selecting with keyboard always returns the " - + "object \"One-1\"."; - } - - @Override - protected Integer getTicketNumber() { - // TODO Auto-generated method stub - return null; - } -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.data.Item; +import com.vaadin.data.Property; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.tests.components.TestBase; +import com.vaadin.tests.util.Log; +import com.vaadin.ui.ComboBox; + +public class ComboBoxIdenticalItems extends TestBase { + + private Log log = new Log(5); + + @Override + public void setup() { + final ComboBox select = new ComboBox("ComboBox"); + select.addContainerProperty("caption", String.class, null); + Item item = select.addItem("one-1"); + item.getItemProperty("caption").setValue("One"); + item = select.addItem("one-2"); + item.getItemProperty("caption").setValue("One"); + item = select.addItem("two"); + item.getItemProperty("caption").setValue("Two"); + select.setItemCaptionPropertyId("caption"); + select.setNullSelectionAllowed(false); + select.setImmediate(true); + select.addListener(new Property.ValueChangeListener() { + private static final long serialVersionUID = -7932700771673919620L; + + public void valueChange(ValueChangeEvent event) { + log.log("Item " + select.getValue() + " selected"); + + } + }); + + addComponent(log); + addComponent(select); + } + + @Override + protected String getDescription() { + return "Keyboard selecting of a value is broken in combobox if two " + + "items have the same caption. The first item's id is \"One-1\" " + + "while the second one is \"One-2\". Selecting with mouse works " + + "as expected but selecting with keyboard always returns the " + + "object \"One-1\"."; + } + + @Override + protected Integer getTicketNumber() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxInvalidNullSelection.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxInvalidNullSelection.java index 2fcb44d4f2..e11b10f3e1 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxInvalidNullSelection.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxInvalidNullSelection.java @@ -1,76 +1,76 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.tests.components.TestBase; -import com.vaadin.tests.util.Log; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.ComboBox; - -public class ComboBoxInvalidNullSelection extends TestBase { - - private static final Object CAPTION = "C"; - private IndexedContainer ds1; - private IndexedContainer ds2; - private ComboBox combo; - private Log log = new Log(5); - - @Override - protected void setup() { - - createDataSources(); - - Button b = new Button("Swap data source"); - b.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - if (combo.getContainerDataSource() == ds1) { - combo.setContainerDataSource(ds2); - } else { - combo.setContainerDataSource(ds1); - } - combo.setValue("Item 3"); - } - }); - - combo = new ComboBox(); - combo.setImmediate(true); - combo.setContainerDataSource(ds1); - combo.addListener(new ValueChangeListener() { - - public void valueChange(ValueChangeEvent event) { - log.log("Value is now: " + combo.getValue()); - } - }); - addComponent(log); - addComponent(b); - addComponent(combo); - addComponent(new Button("Dummy for TestBench")); - } - - private void createDataSources() { - ds1 = new IndexedContainer(); - ds1.addContainerProperty(CAPTION, String.class, ""); - ds1.addItem("Item 1"); - ds1.addItem("Item 2"); - ds1.addItem("Item 3"); - ds1.addItem("Item 4"); - - ds2 = new IndexedContainer(); - ds2.addContainerProperty(CAPTION, String.class, ""); - ds2.addItem("Item 3"); - - } - - @Override - protected String getDescription() { - return "Select \"Item 3\" in the ComboBox, change the data source, focus and blur the ComboBox. The value should temporarily change to null when changing data source but not when focusing and blurring the ComboBox"; - } - - @Override - protected Integer getTicketNumber() { - return 6170; - } - -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.components.TestBase; +import com.vaadin.tests.util.Log; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.ComboBox; + +public class ComboBoxInvalidNullSelection extends TestBase { + + private static final Object CAPTION = "C"; + private IndexedContainer ds1; + private IndexedContainer ds2; + private ComboBox combo; + private Log log = new Log(5); + + @Override + protected void setup() { + + createDataSources(); + + Button b = new Button("Swap data source"); + b.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + if (combo.getContainerDataSource() == ds1) { + combo.setContainerDataSource(ds2); + } else { + combo.setContainerDataSource(ds1); + } + combo.setValue("Item 3"); + } + }); + + combo = new ComboBox(); + combo.setImmediate(true); + combo.setContainerDataSource(ds1); + combo.addListener(new ValueChangeListener() { + + public void valueChange(ValueChangeEvent event) { + log.log("Value is now: " + combo.getValue()); + } + }); + addComponent(log); + addComponent(b); + addComponent(combo); + addComponent(new Button("Dummy for TestBench")); + } + + private void createDataSources() { + ds1 = new IndexedContainer(); + ds1.addContainerProperty(CAPTION, String.class, ""); + ds1.addItem("Item 1"); + ds1.addItem("Item 2"); + ds1.addItem("Item 3"); + ds1.addItem("Item 4"); + + ds2 = new IndexedContainer(); + ds2.addContainerProperty(CAPTION, String.class, ""); + ds2.addItem("Item 3"); + + } + + @Override + protected String getDescription() { + return "Select \"Item 3\" in the ComboBox, change the data source, focus and blur the ComboBox. The value should temporarily change to null when changing data source but not when focusing and blurring the ComboBox"; + } + + @Override + protected Integer getTicketNumber() { + return 6170; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxTextFieldEventOrder.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxTextFieldEventOrder.java index 31979a6a90..d92a1872b8 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxTextFieldEventOrder.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxTextFieldEventOrder.java @@ -1,38 +1,38 @@ -package com.vaadin.tests.components.combobox; -import java.util.Arrays; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Select; -import com.vaadin.ui.TextField; - -public class ComboBoxTextFieldEventOrder extends TestBase { - - @Override - protected void setup() { - TextField textField = new TextField("text field"); - textField.setImmediate(true); - final Select select = new Select("select", Arrays.asList("1", "2", "3", - "4")); - textField.addListener(new ValueChangeListener() { - public void valueChange(ValueChangeEvent event) { - select.addItem(Long.valueOf(select.size() + 1).toString()); // or - // just - // select.requestRepaint(); - } - }); - addComponent(textField); - addComponent(select); - } - - @Override - protected String getDescription() { - return "Entering a text in a TextField and then clicking on the button in a ComboBox should cause the TextField value change to be sent first and the ComboBox filtering afterwards. Failure to do so will cause errors if the value change listener modifies the ComboBox"; - } - - @Override - protected Integer getTicketNumber() { - return 7481; - } -} +package com.vaadin.tests.components.combobox; +import java.util.Arrays; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Select; +import com.vaadin.ui.TextField; + +public class ComboBoxTextFieldEventOrder extends TestBase { + + @Override + protected void setup() { + TextField textField = new TextField("text field"); + textField.setImmediate(true); + final Select select = new Select("select", Arrays.asList("1", "2", "3", + "4")); + textField.addListener(new ValueChangeListener() { + public void valueChange(ValueChangeEvent event) { + select.addItem(Long.valueOf(select.size() + 1).toString()); // or + // just + // select.requestRepaint(); + } + }); + addComponent(textField); + addComponent(select); + } + + @Override + protected String getDescription() { + return "Entering a text in a TextField and then clicking on the button in a ComboBox should cause the TextField value change to be sent first and the ComboBox filtering afterwards. Failure to do so will cause errors if the value change listener modifies the ComboBox"; + } + + @Override + protected Integer getTicketNumber() { + return 7481; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxUndefinedWidthAndIcon.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxUndefinedWidthAndIcon.java index fd5f7d47f8..eb28a9ff4e 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxUndefinedWidthAndIcon.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxUndefinedWidthAndIcon.java @@ -1,36 +1,36 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.data.Item; -import com.vaadin.terminal.Resource; -import com.vaadin.terminal.ThemeResource; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.ComboBox; - -public class ComboBoxUndefinedWidthAndIcon extends TestBase { - @Override - protected void setup() { - ComboBox cb = new ComboBox(); - cb.addContainerProperty("caption", String.class, null); - cb.addContainerProperty("icon", Resource.class, null); - for (int i = 1; i < 200 + 1; i++) { - Item item = cb.addItem(i); - item.getItemProperty("caption").setValue("Item " + i); - item.getItemProperty("icon").setValue( - new ThemeResource("../runo/icons/16/users.png")); - } - cb.setItemIconPropertyId("icon"); - cb.setItemCaptionPropertyId("caption"); - - addComponent(cb); - } - - @Override - protected String getDescription() { - return "The width of the ComboBox should be fixed even though it is set to undefined width. The width should not change when changing pages in the dropdown."; - } - - @Override - protected Integer getTicketNumber() { - return 7013; - } -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.data.Item; +import com.vaadin.terminal.Resource; +import com.vaadin.terminal.ThemeResource; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.ComboBox; + +public class ComboBoxUndefinedWidthAndIcon extends TestBase { + @Override + protected void setup() { + ComboBox cb = new ComboBox(); + cb.addContainerProperty("caption", String.class, null); + cb.addContainerProperty("icon", Resource.class, null); + for (int i = 1; i < 200 + 1; i++) { + Item item = cb.addItem(i); + item.getItemProperty("caption").setValue("Item " + i); + item.getItemProperty("icon").setValue( + new ThemeResource("../runo/icons/16/users.png")); + } + cb.setItemIconPropertyId("icon"); + cb.setItemCaptionPropertyId("caption"); + + addComponent(cb); + } + + @Override + protected String getDescription() { + return "The width of the ComboBox should be fixed even though it is set to undefined width. The width should not change when changing pages in the dropdown."; + } + + @Override + protected Integer getTicketNumber() { + return 7013; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxValueInput.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxValueInput.java index 177b3542a4..9e1fab0cda 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxValueInput.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboBoxValueInput.java @@ -1,63 +1,63 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.ComboBox; - -public class ComboBoxValueInput extends TestBase { - - @Override - protected void setup() { - (getLayout()).setSpacing(true); - - ComboBox cb = getComboBox("A combobox", false); - addComponent(cb); - - cb = getComboBox("A combobox with input prompt", false); - cb.setInputPrompt("Please select"); - addComponent(cb); - - cb = getComboBox("A combobox with null item", true); - addComponent(cb); - - cb = getComboBox("A combobox with null item and input prompt", true); - cb.setInputPrompt("Please select"); - addComponent(cb); - - cb = getComboBox("A disabled combobox", true); - cb.setEnabled(false); - addComponent(cb); - - cb = getComboBox("A read-only combobox", true); - cb.setReadOnly(true); - addComponent(cb); - - cb = getComboBox("A combobox with filteringMode off", false); - cb.setFilteringMode(ComboBox.FILTERINGMODE_OFF); - - } - - @Override - protected String getDescription() { - return "A combobox should always show the selected value when it is not focused. Entering a text when nothing is selected and blurring the combobox should reset the value. The same should happen when a value is selected"; - } - - @Override - protected Integer getTicketNumber() { - return 3268; - } - - private ComboBox getComboBox(String caption, boolean addNullItem) { - ComboBox cb = new ComboBox(caption); - cb.setImmediate(true); - if (addNullItem) { - cb.addItem("Null item"); - cb.setNullSelectionItemId("Null item"); - } - cb.addItem("Value 1"); - cb.addItem("Value 2"); - cb.addItem("Value 3"); - - return cb; - } - -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.ComboBox; + +public class ComboBoxValueInput extends TestBase { + + @Override + protected void setup() { + (getLayout()).setSpacing(true); + + ComboBox cb = getComboBox("A combobox", false); + addComponent(cb); + + cb = getComboBox("A combobox with input prompt", false); + cb.setInputPrompt("Please select"); + addComponent(cb); + + cb = getComboBox("A combobox with null item", true); + addComponent(cb); + + cb = getComboBox("A combobox with null item and input prompt", true); + cb.setInputPrompt("Please select"); + addComponent(cb); + + cb = getComboBox("A disabled combobox", true); + cb.setEnabled(false); + addComponent(cb); + + cb = getComboBox("A read-only combobox", true); + cb.setReadOnly(true); + addComponent(cb); + + cb = getComboBox("A combobox with filteringMode off", false); + cb.setFilteringMode(ComboBox.FILTERINGMODE_OFF); + + } + + @Override + protected String getDescription() { + return "A combobox should always show the selected value when it is not focused. Entering a text when nothing is selected and blurring the combobox should reset the value. The same should happen when a value is selected"; + } + + @Override + protected Integer getTicketNumber() { + return 3268; + } + + private ComboBox getComboBox(String caption, boolean addNullItem) { + ComboBox cb = new ComboBox(caption); + cb.setImmediate(true); + if (addNullItem) { + cb.addItem("Null item"); + cb.setNullSelectionItemId("Null item"); + } + cb.addItem("Value 1"); + cb.addItem("Value 2"); + cb.addItem("Value 3"); + + return cb; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/combobox/ComboxBoxErrorMessage.java b/tests/testbench/com/vaadin/tests/components/combobox/ComboxBoxErrorMessage.java index a6eaf7d3e6..7f0816c842 100644 --- a/tests/testbench/com/vaadin/tests/components/combobox/ComboxBoxErrorMessage.java +++ b/tests/testbench/com/vaadin/tests/components/combobox/ComboxBoxErrorMessage.java @@ -1,26 +1,26 @@ -package com.vaadin.tests.components.combobox; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.ComboBox; - -public class ComboxBoxErrorMessage extends TestBase { - - @Override - protected void setup() { - ComboBox cb = new ComboBox(""); - cb.setRequired(true); - cb.setRequiredError("You must select something"); - addComponent(cb); - } - - @Override - protected String getDescription() { - return "The ComboBox should show an \"You must select something\" tooltip when the cursor is hovering it. Both when hovering the textfield and the dropdown button."; - } - - @Override - protected Integer getTicketNumber() { - return 3345; - } - -} +package com.vaadin.tests.components.combobox; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.ComboBox; + +public class ComboxBoxErrorMessage extends TestBase { + + @Override + protected void setup() { + ComboBox cb = new ComboBox(""); + cb.setRequired(true); + cb.setRequiredError("You must select something"); + addComponent(cb); + } + + @Override + protected String getDescription() { + return "The ComboBox should show an \"You must select something\" tooltip when the cursor is hovering it. Both when hovering the textfield and the dropdown button."; + } + + @Override + protected Integer getTicketNumber() { + return 3345; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java b/tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java index cc7320ad03..8bc464f176 100644 --- a/tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java +++ b/tests/testbench/com/vaadin/tests/components/customcomponent/ClipContent.java @@ -1,56 +1,56 @@ -package com.vaadin.tests.components.customcomponent; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.Label; -import com.vaadin.ui.TextField; - -public class ClipContent extends TestBase { - - @Override - protected void setup() { - - Label text = new Label( - "1_long_line_that_should_be_clipped
2_long_line_that_should_be_clipped
3_long_line_that_should_be_clipped
4_long_line_that_should_be_clipped
", - Label.CONTENT_XHTML); - - final CustomComponent cc = new CustomComponent(text); - cc.setWidth("20px"); - cc.setHeight("20px"); - - final TextField w = new TextField("Width"); - w.setValue("20px"); - w.addListener(new TextField.ValueChangeListener() { - public void valueChange(ValueChangeEvent event) { - cc.setWidth((String) w.getValue()); - } - }); - addComponent(w); - final TextField h = new TextField("Height"); - h.setValue("20px"); - h.addListener(new TextField.ValueChangeListener() { - public void valueChange(ValueChangeEvent event) { - cc.setHeight((String) h.getValue()); - } - }); - addComponent(h); - Button b = new Button("apply"); - addComponent(b); - - addComponent(cc); - - } - - @Override - protected String getDescription() { - return "The text in CustomComponent should be clipped if it has size defined."; - } - - @Override - protected Integer getTicketNumber() { - return null; - } - -} +package com.vaadin.tests.components.customcomponent; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.Label; +import com.vaadin.ui.TextField; + +public class ClipContent extends TestBase { + + @Override + protected void setup() { + + Label text = new Label( + "1_long_line_that_should_be_clipped
2_long_line_that_should_be_clipped
3_long_line_that_should_be_clipped
4_long_line_that_should_be_clipped
", + Label.CONTENT_XHTML); + + final CustomComponent cc = new CustomComponent(text); + cc.setWidth("20px"); + cc.setHeight("20px"); + + final TextField w = new TextField("Width"); + w.setValue("20px"); + w.addListener(new TextField.ValueChangeListener() { + public void valueChange(ValueChangeEvent event) { + cc.setWidth((String) w.getValue()); + } + }); + addComponent(w); + final TextField h = new TextField("Height"); + h.setValue("20px"); + h.addListener(new TextField.ValueChangeListener() { + public void valueChange(ValueChangeEvent event) { + cc.setHeight((String) h.getValue()); + } + }); + addComponent(h); + Button b = new Button("apply"); + addComponent(b); + + addComponent(cc); + + } + + @Override + protected String getDescription() { + return "The text in CustomComponent should be clipped if it has size defined."; + } + + @Override + protected Integer getTicketNumber() { + return null; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/customcomponent/CustomComponentSizeUpdate.java b/tests/testbench/com/vaadin/tests/components/customcomponent/CustomComponentSizeUpdate.java index 575a1651e3..43d4c70eb8 100644 --- a/tests/testbench/com/vaadin/tests/components/customcomponent/CustomComponentSizeUpdate.java +++ b/tests/testbench/com/vaadin/tests/components/customcomponent/CustomComponentSizeUpdate.java @@ -1,44 +1,44 @@ -package com.vaadin.tests.components.customcomponent; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.CustomComponent; -import com.vaadin.ui.NativeButton; - -public class CustomComponentSizeUpdate extends TestBase { - - @Override - protected void setup() { - NativeButton nb = new NativeButton( - "100%x100% button. Click to reduce CustomComponent size"); - nb.setSizeFull(); - - final CustomComponent cc = new CustomComponent(nb); - cc.setWidth("500px"); - cc.setHeight("500px"); - - nb.addListener(new ClickListener() { - - public void buttonClick(ClickEvent event) { - cc.setWidth((cc.getWidth() - 20) + "px"); - cc.setHeight((cc.getHeight() - 20) + "px"); - - } - }); - - addComponent(cc); - - } - - @Override - protected String getDescription() { - return "Click the button to reduce the size of the parent. The button should be resized to fit the parent."; - } - - @Override - protected Integer getTicketNumber() { - return 3705; - } - -} +package com.vaadin.tests.components.customcomponent; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.CustomComponent; +import com.vaadin.ui.NativeButton; + +public class CustomComponentSizeUpdate extends TestBase { + + @Override + protected void setup() { + NativeButton nb = new NativeButton( + "100%x100% button. Click to reduce CustomComponent size"); + nb.setSizeFull(); + + final CustomComponent cc = new CustomComponent(nb); + cc.setWidth("500px"); + cc.setHeight("500px"); + + nb.addListener(new ClickListener() { + + public void buttonClick(ClickEvent event) { + cc.setWidth((cc.getWidth() - 20) + "px"); + cc.setHeight((cc.getHeight() - 20) + "px"); + + } + }); + + addComponent(cc); + + } + + @Override + protected String getDescription() { + return "Click the button to reduce the size of the parent. The button should be resized to fit the parent."; + } + + @Override + protected Integer getTicketNumber() { + return 3705; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/CustomDateFormats.java b/tests/testbench/com/vaadin/tests/components/datefield/CustomDateFormats.java index 7f67af1adc..48bf3622d1 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/CustomDateFormats.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/CustomDateFormats.java @@ -1,207 +1,207 @@ -package com.vaadin.tests.components.datefield; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - -import com.vaadin.data.Item; -import com.vaadin.data.Property; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Component; -import com.vaadin.ui.DateField; -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.NativeSelect; - -public class CustomDateFormats extends TestBase { - - private static final Object CAPTION = "C"; - - private Component customFormats = null; - - @Override - protected void setup() { - final NativeSelect s = new NativeSelect("Locale"); - s.setImmediate(true); - s.setNullSelectionAllowed(false); - s.addContainerProperty(CAPTION, String.class, ""); - addLocale(Locale.FRANCE, s); - addLocale(Locale.CHINESE, s); - addLocale(Locale.US, s); - addLocale(Locale.UK, s); - addLocale(new Locale("fi", "FI"), s); - - s.addListener(new Property.ValueChangeListener() { - - public void valueChange(ValueChangeEvent event) { - setDateFieldLocale((Locale) s.getValue()); - } - }); - addComponent(s); - s.setValue(Locale.FRANCE); - } - - private void addLocale(Locale locale, NativeSelect s) { - Item i = s.addItem(locale); - i.getItemProperty(CAPTION).setValue(locale.toString()); - - } - - protected void setDateFieldLocale(Locale value) { - Component n = getCustomFormats(value); - if (customFormats == null) { - addComponent(n); - } else { - replaceComponent(customFormats, n); - } - customFormats = n; - - } - - private GridLayout getCustomFormats(Locale locale) { - GridLayout gridLayout = createGridLayout(); - usedDebugIds.clear(); - addDateFields(gridLayout, locale); - - return gridLayout; - } - - private GridLayout createGridLayout() { - GridLayout gridLayout = new GridLayout(4, 4); - gridLayout.setMargin(true); - gridLayout.addComponent(new Label("FORMAT")); - gridLayout.addComponent(new Label("DATEFIELD")); - gridLayout.addComponent(new Label("SERVER SIDE VALUE")); - gridLayout.addComponent(new Label("EXPECTED")); - - return gridLayout; - } - - private void addDateFields(GridLayout gridLayout, Locale locale) { - addDateField(gridLayout, "d M yyyy", locale); - addDateField(gridLayout, "d MM yyyy", locale); - addDateField(gridLayout, "d MMM yyyy", locale); - addDateField(gridLayout, "d MMMM yyyy", locale); - - addDateField(gridLayout, "dd M yyyy", locale); - addDateField(gridLayout, "ddd M yyyy", locale); - - addDateField(gridLayout, "d M y", locale, "d M yyyy"); - addDateField(gridLayout, "d M yy", locale); - addDateField(gridLayout, "d M yyy", locale, "d M yyyy"); - addDateField(gridLayout, "d M yyyy", locale); - - addDateField(gridLayout, getDatePattern(locale, DateFormat.FULL), - locale); - addDateField(gridLayout, getDatePattern(locale, DateFormat.LONG), - locale); - addDateField(gridLayout, getDatePattern(locale, DateFormat.MEDIUM), - locale); - addDateField(gridLayout, getDatePattern(locale, DateFormat.SHORT), - locale); - - } - - private String getDatePattern(Locale locale, int dateStyle) { - DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale); - - if (dateFormat instanceof SimpleDateFormat) { - String pattern = ((SimpleDateFormat) dateFormat).toPattern(); - return pattern; - } - return null; - - } - - public class Data { - - private Label label; - private String pattern; - - public Data(Label label, String pattern) { - this.label = label; - this.pattern = pattern; - } - - } - - private Set usedDebugIds = new HashSet(); - - private void addDateField(GridLayout gridLayout, String pattern, - Locale locale, String expectedDateFormat) { - Calendar cal = Calendar.getInstance(); - cal.set(2010, 1, 1); - - Label serversideValueLabel = new Label(); - - DateField df = new DateField(); - df.setResolution(DateField.RESOLUTION_DAY); - df.setLocale(locale); - df.setWidth("300px"); - df.setDateFormat(pattern); - df.setImmediate(true); - String debugId = pattern.replace('/', 'X'); - while (usedDebugIds.contains(debugId)) { - debugId = debugId + "-"; - } - df.setDebugId(debugId); - usedDebugIds.add(debugId); - - df.setData(new Data(serversideValueLabel, pattern)); - df.setValue(cal.getTime()); - df.addListener(new Property.ValueChangeListener() { - - public void valueChange(ValueChangeEvent event) { - updateServerSideLabel((DateField) event.getProperty()); - } - }); - - Label patternLabel = new Label(pattern); - patternLabel.setWidth(null); - SimpleDateFormat expDateFormat = new SimpleDateFormat( - expectedDateFormat, locale); - - Label expectedLabel = new Label(expDateFormat.format(cal.getTime())); - if (!pattern.equals(expectedDateFormat)) { - expectedLabel.setValue(expectedLabel.getValue() - + " (differs from JDK)"); - } - expectedLabel.setWidth(null); - - gridLayout.addComponent(patternLabel); - gridLayout.addComponent(df); - gridLayout.addComponent(serversideValueLabel); - gridLayout.addComponent(expectedLabel); - - updateServerSideLabel(df); - } - - private void updateServerSideLabel(DateField df) { - Data data = (Data) df.getData(); - String pattern = data.pattern; - Locale locale = df.getLocale(); - SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale); - - String newValue = formatter.format(df.getValue()); - data.label.setValue(newValue); - } - - private void addDateField(GridLayout gridLayout, String pattern, - Locale locale) { - addDateField(gridLayout, pattern, locale, pattern); - } - - @Override - protected String getDescription() { - return "Test that DateField renders custom date formats the same way as SimpleDateFormat formats them"; - } - - @Override - protected Integer getTicketNumber() { - return 5465; - } +package com.vaadin.tests.components.datefield; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; + +import com.vaadin.data.Item; +import com.vaadin.data.Property; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Component; +import com.vaadin.ui.DateField; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.NativeSelect; + +public class CustomDateFormats extends TestBase { + + private static final Object CAPTION = "C"; + + private Component customFormats = null; + + @Override + protected void setup() { + final NativeSelect s = new NativeSelect("Locale"); + s.setImmediate(true); + s.setNullSelectionAllowed(false); + s.addContainerProperty(CAPTION, String.class, ""); + addLocale(Locale.FRANCE, s); + addLocale(Locale.CHINESE, s); + addLocale(Locale.US, s); + addLocale(Locale.UK, s); + addLocale(new Locale("fi", "FI"), s); + + s.addListener(new Property.ValueChangeListener() { + + public void valueChange(ValueChangeEvent event) { + setDateFieldLocale((Locale) s.getValue()); + } + }); + addComponent(s); + s.setValue(Locale.FRANCE); + } + + private void addLocale(Locale locale, NativeSelect s) { + Item i = s.addItem(locale); + i.getItemProperty(CAPTION).setValue(locale.toString()); + + } + + protected void setDateFieldLocale(Locale value) { + Component n = getCustomFormats(value); + if (customFormats == null) { + addComponent(n); + } else { + replaceComponent(customFormats, n); + } + customFormats = n; + + } + + private GridLayout getCustomFormats(Locale locale) { + GridLayout gridLayout = createGridLayout(); + usedDebugIds.clear(); + addDateFields(gridLayout, locale); + + return gridLayout; + } + + private GridLayout createGridLayout() { + GridLayout gridLayout = new GridLayout(4, 4); + gridLayout.setMargin(true); + gridLayout.addComponent(new Label("FORMAT")); + gridLayout.addComponent(new Label("DATEFIELD")); + gridLayout.addComponent(new Label("SERVER SIDE VALUE")); + gridLayout.addComponent(new Label("EXPECTED")); + + return gridLayout; + } + + private void addDateFields(GridLayout gridLayout, Locale locale) { + addDateField(gridLayout, "d M yyyy", locale); + addDateField(gridLayout, "d MM yyyy", locale); + addDateField(gridLayout, "d MMM yyyy", locale); + addDateField(gridLayout, "d MMMM yyyy", locale); + + addDateField(gridLayout, "dd M yyyy", locale); + addDateField(gridLayout, "ddd M yyyy", locale); + + addDateField(gridLayout, "d M y", locale, "d M yyyy"); + addDateField(gridLayout, "d M yy", locale); + addDateField(gridLayout, "d M yyy", locale, "d M yyyy"); + addDateField(gridLayout, "d M yyyy", locale); + + addDateField(gridLayout, getDatePattern(locale, DateFormat.FULL), + locale); + addDateField(gridLayout, getDatePattern(locale, DateFormat.LONG), + locale); + addDateField(gridLayout, getDatePattern(locale, DateFormat.MEDIUM), + locale); + addDateField(gridLayout, getDatePattern(locale, DateFormat.SHORT), + locale); + + } + + private String getDatePattern(Locale locale, int dateStyle) { + DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale); + + if (dateFormat instanceof SimpleDateFormat) { + String pattern = ((SimpleDateFormat) dateFormat).toPattern(); + return pattern; + } + return null; + + } + + public class Data { + + private Label label; + private String pattern; + + public Data(Label label, String pattern) { + this.label = label; + this.pattern = pattern; + } + + } + + private Set usedDebugIds = new HashSet(); + + private void addDateField(GridLayout gridLayout, String pattern, + Locale locale, String expectedDateFormat) { + Calendar cal = Calendar.getInstance(); + cal.set(2010, 1, 1); + + Label serversideValueLabel = new Label(); + + DateField df = new DateField(); + df.setResolution(DateField.RESOLUTION_DAY); + df.setLocale(locale); + df.setWidth("300px"); + df.setDateFormat(pattern); + df.setImmediate(true); + String debugId = pattern.replace('/', 'X'); + while (usedDebugIds.contains(debugId)) { + debugId = debugId + "-"; + } + df.setDebugId(debugId); + usedDebugIds.add(debugId); + + df.setData(new Data(serversideValueLabel, pattern)); + df.setValue(cal.getTime()); + df.addListener(new Property.ValueChangeListener() { + + public void valueChange(ValueChangeEvent event) { + updateServerSideLabel((DateField) event.getProperty()); + } + }); + + Label patternLabel = new Label(pattern); + patternLabel.setWidth(null); + SimpleDateFormat expDateFormat = new SimpleDateFormat( + expectedDateFormat, locale); + + Label expectedLabel = new Label(expDateFormat.format(cal.getTime())); + if (!pattern.equals(expectedDateFormat)) { + expectedLabel.setValue(expectedLabel.getValue() + + " (differs from JDK)"); + } + expectedLabel.setWidth(null); + + gridLayout.addComponent(patternLabel); + gridLayout.addComponent(df); + gridLayout.addComponent(serversideValueLabel); + gridLayout.addComponent(expectedLabel); + + updateServerSideLabel(df); + } + + private void updateServerSideLabel(DateField df) { + Data data = (Data) df.getData(); + String pattern = data.pattern; + Locale locale = df.getLocale(); + SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale); + + String newValue = formatter.format(df.getValue()); + data.label.setValue(newValue); + } + + private void addDateField(GridLayout gridLayout, String pattern, + Locale locale) { + addDateField(gridLayout, pattern, locale, pattern); + } + + @Override + protected String getDescription() { + return "Test that DateField renders custom date formats the same way as SimpleDateFormat formats them"; + } + + @Override + protected Integer getTicketNumber() { + return 5465; + } } \ No newline at end of file diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java index 53b1d253ab..440f004531 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldEmptyValid.java @@ -1,144 +1,144 @@ -package com.vaadin.tests.components.datefield; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.tests.components.TestBase; -import com.vaadin.tests.util.Log; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.DateField; -import com.vaadin.ui.Label; -import com.vaadin.ui.PopupDateField; - -@SuppressWarnings("serial") -public class DateFieldEmptyValid extends TestBase { - - private Log log; - - private MyDateField df; - - private SimpleDateFormat formatter = new SimpleDateFormat( - "MMMM d, yyyy hh:mm:ss aaa", Locale.US); - - public class MyDateField extends PopupDateField { - @Override - public boolean isEmpty() { - return super.isEmpty(); - } - - } - - @Override - protected void setup() { - addComponent(new Label("

", Label.CONTENT_XHTML)); - log = new Log(8); - addComponent(log); - df = new MyDateField(); - df.setDebugId("DateField"); - df.setRequired(true); - df.setLocale(new Locale("fi", "FI")); - df.setValue(new Date(100000000000L)); - df.setImmediate(true); - df.setResolution(DateField.RESOLUTION_DAY); - df.addListener(new ValueChangeListener() { - public void valueChange(ValueChangeEvent event) { - log.log("Value changeEvent"); - checkEmpty(); - } - }); - addComponent(df); - checkEmpty(); - Button b = new Button("Clear date"); - b.setDebugId("clear"); - b.addListener(new ClickListener() { - - public void buttonClick(ClickEvent event) { - log.log("Clearing date aka setValue(null)"); - df.setValue(null); - } - }); - addComponent(b); - - b = new Button("Set date to 4.5.1990"); - b.setDebugId("set4.5.1990"); - b.addListener(new ClickListener() { - - @SuppressWarnings("deprecation") - public void buttonClick(ClickEvent event) { - log.log("Setting new value to datefield (4.5.1990)"); - df.setValue(new Date(1990 - 1900, 5 - 1, 4)); - } - }); - addComponent(b); - - b = new Button("Set date to 5.6.2000 using a property data source"); - b.addListener(new ClickListener() { - - @SuppressWarnings("deprecation") - public void buttonClick(ClickEvent event) { - log.log("Setting new object property (5.6.2000) to datefield"); - ObjectProperty dfProp = new ObjectProperty( - new Date(2000 - 1900, 6 - 1, 5), Date.class); - df.setPropertyDataSource(dfProp); - } - }); - b.setDebugId("set-by-ds"); - addComponent(b); - - b = new Button( - "Set date to 27.8.2005 by changing a new property data source from null, ds attached before value setting."); - b.setDebugId("set-via-ds"); - b.addListener(new ClickListener() { - - @SuppressWarnings("deprecation") - public void buttonClick(ClickEvent event) { - log.log("Setting object property (with value null) to datefield and set value of property to 27.8.2005"); - ObjectProperty dfProp = new ObjectProperty(null, - Date.class); - df.setPropertyDataSource(dfProp); - dfProp.setValue(new Date(2005 - 1900, 8 - 1, 27)); - } - }); - addComponent(b); - - b = new Button("Check value"); - b.setDebugId("check-value"); - b.addListener(new ClickListener() { - public void buttonClick(ClickEvent event) { - log.log("Checking state"); - checkEmpty(); - } - }); - addComponent(b); - } - - private void checkEmpty() { - Object value = df.getValue(); - if (value instanceof Date) { - value = formatter.format(df.getValue()); - } - - log.log("DateField value is now " + value); - // log.log("DateField value is now " + df.getValue()); - log.log("isEmpty: " + df.isEmpty() + ", isValid: " + df.isValid()); - } - - @Override - protected String getDescription() { - return "Tests the isEmpty() and isValid() functionality of a DateField. The field is required and has no other validators." - + "IsEmpty() should return true when the field is truly empty i.e. contains no text, no matter how the field has been made empty. If the field contains any text, isEmpty() should return false." - + "IsValid() should in this case return true if the field is not empty and vice versa."; - } - - @Override - protected Integer getTicketNumber() { - return 5277; - } - -} +package com.vaadin.tests.components.datefield; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.tests.components.TestBase; +import com.vaadin.tests.util.Log; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.DateField; +import com.vaadin.ui.Label; +import com.vaadin.ui.PopupDateField; + +@SuppressWarnings("serial") +public class DateFieldEmptyValid extends TestBase { + + private Log log; + + private MyDateField df; + + private SimpleDateFormat formatter = new SimpleDateFormat( + "MMMM d, yyyy hh:mm:ss aaa", Locale.US); + + public class MyDateField extends PopupDateField { + @Override + public boolean isEmpty() { + return super.isEmpty(); + } + + } + + @Override + protected void setup() { + addComponent(new Label("

", Label.CONTENT_XHTML)); + log = new Log(8); + addComponent(log); + df = new MyDateField(); + df.setDebugId("DateField"); + df.setRequired(true); + df.setLocale(new Locale("fi", "FI")); + df.setValue(new Date(100000000000L)); + df.setImmediate(true); + df.setResolution(DateField.RESOLUTION_DAY); + df.addListener(new ValueChangeListener() { + public void valueChange(ValueChangeEvent event) { + log.log("Value changeEvent"); + checkEmpty(); + } + }); + addComponent(df); + checkEmpty(); + Button b = new Button("Clear date"); + b.setDebugId("clear"); + b.addListener(new ClickListener() { + + public void buttonClick(ClickEvent event) { + log.log("Clearing date aka setValue(null)"); + df.setValue(null); + } + }); + addComponent(b); + + b = new Button("Set date to 4.5.1990"); + b.setDebugId("set4.5.1990"); + b.addListener(new ClickListener() { + + @SuppressWarnings("deprecation") + public void buttonClick(ClickEvent event) { + log.log("Setting new value to datefield (4.5.1990)"); + df.setValue(new Date(1990 - 1900, 5 - 1, 4)); + } + }); + addComponent(b); + + b = new Button("Set date to 5.6.2000 using a property data source"); + b.addListener(new ClickListener() { + + @SuppressWarnings("deprecation") + public void buttonClick(ClickEvent event) { + log.log("Setting new object property (5.6.2000) to datefield"); + ObjectProperty dfProp = new ObjectProperty( + new Date(2000 - 1900, 6 - 1, 5), Date.class); + df.setPropertyDataSource(dfProp); + } + }); + b.setDebugId("set-by-ds"); + addComponent(b); + + b = new Button( + "Set date to 27.8.2005 by changing a new property data source from null, ds attached before value setting."); + b.setDebugId("set-via-ds"); + b.addListener(new ClickListener() { + + @SuppressWarnings("deprecation") + public void buttonClick(ClickEvent event) { + log.log("Setting object property (with value null) to datefield and set value of property to 27.8.2005"); + ObjectProperty dfProp = new ObjectProperty(null, + Date.class); + df.setPropertyDataSource(dfProp); + dfProp.setValue(new Date(2005 - 1900, 8 - 1, 27)); + } + }); + addComponent(b); + + b = new Button("Check value"); + b.setDebugId("check-value"); + b.addListener(new ClickListener() { + public void buttonClick(ClickEvent event) { + log.log("Checking state"); + checkEmpty(); + } + }); + addComponent(b); + } + + private void checkEmpty() { + Object value = df.getValue(); + if (value instanceof Date) { + value = formatter.format(df.getValue()); + } + + log.log("DateField value is now " + value); + // log.log("DateField value is now " + df.getValue()); + log.log("isEmpty: " + df.isEmpty() + ", isValid: " + df.isValid()); + } + + @Override + protected String getDescription() { + return "Tests the isEmpty() and isValid() functionality of a DateField. The field is required and has no other validators." + + "IsEmpty() should return true when the field is truly empty i.e. contains no text, no matter how the field has been made empty. If the field contains any text, isEmpty() should return false." + + "IsValid() should in this case return true if the field is not empty and vice versa."; + } + + @Override + protected Integer getTicketNumber() { + return 5277; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldLocale.java b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldLocale.java index fbeeb872d7..dd61ccd60c 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldLocale.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldLocale.java @@ -1,47 +1,47 @@ -package com.vaadin.tests.components.datefield; - -import java.util.Date; -import java.util.Locale; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.DateField; - -public class DateFieldLocale extends TestBase { - - @Override - public void setup() { - final DateField dateField = new DateField("DateField"); - dateField.setLocale(new Locale("fi", "FI")); - dateField.setCaption(dateField.getLocale().toString()); - dateField.setValue(new Date()); - dateField.setResolution(DateField.RESOLUTION_DAY); - - addComponent(new Button("Change locale", new ClickListener() { - - public void buttonClick(ClickEvent event) { - if (dateField.getLocale().getCountry().equalsIgnoreCase("fi")) { - dateField.setLocale(new Locale("zh", "CN")); - } else { - dateField.setLocale(new Locale("fi", "FI")); - } - dateField.setCaption(dateField.getLocale().toString()); - } - })); - - addComponent(dateField); - } - - @Override - protected String getDescription() { - return "Click change locale to switch between Finnish and Chinese locale for the DateField. The date string should be updated in addition to the caption."; - } - - @Override - protected Integer getTicketNumber() { - return 3935; - } - -} +package com.vaadin.tests.components.datefield; + +import java.util.Date; +import java.util.Locale; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.DateField; + +public class DateFieldLocale extends TestBase { + + @Override + public void setup() { + final DateField dateField = new DateField("DateField"); + dateField.setLocale(new Locale("fi", "FI")); + dateField.setCaption(dateField.getLocale().toString()); + dateField.setValue(new Date()); + dateField.setResolution(DateField.RESOLUTION_DAY); + + addComponent(new Button("Change locale", new ClickListener() { + + public void buttonClick(ClickEvent event) { + if (dateField.getLocale().getCountry().equalsIgnoreCase("fi")) { + dateField.setLocale(new Locale("zh", "CN")); + } else { + dateField.setLocale(new Locale("fi", "FI")); + } + dateField.setCaption(dateField.getLocale().toString()); + } + })); + + addComponent(dateField); + } + + @Override + protected String getDescription() { + return "Click change locale to switch between Finnish and Chinese locale for the DateField. The date string should be updated in addition to the caption."; + } + + @Override + protected Integer getTicketNumber() { + return 3935; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java index cb3fc1f916..122fd4347f 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldPopupOffScreen.java @@ -1,62 +1,62 @@ -package com.vaadin.tests.components.datefield; - -import java.sql.Date; - -import com.vaadin.tests.components.AbstractTestCase; -import com.vaadin.ui.Alignment; -import com.vaadin.ui.DateField; -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.Window; - -public class DateFieldPopupOffScreen extends AbstractTestCase { - - @Override - protected String getDescription() { - return "Test for the popup position from a DateField. The popup should always be on-screen even if the DateField is close the the edge of the browser."; - } - - @Override - protected Integer getTicketNumber() { - return 3639; - } - - @Override - public void init() { - Window mainWindow = new Window(getClass().getName()); - - GridLayout mainLayout = new GridLayout(3, 3); - mainLayout.setSizeFull(); - - DateField df; - - df = createDateField(); - mainLayout.addComponent(df, 2, 0); - mainLayout.setComponentAlignment(df, Alignment.TOP_RIGHT); - - df = createDateField(); - mainLayout.addComponent(df, 2, 1); - mainLayout.setComponentAlignment(df, Alignment.MIDDLE_RIGHT); - - df = createDateField(); - mainLayout.addComponent(df, 2, 2); - mainLayout.setComponentAlignment(df, Alignment.BOTTOM_RIGHT); - - df = createDateField(); - mainLayout.addComponent(df, 0, 2); - mainLayout.setComponentAlignment(df, Alignment.BOTTOM_LEFT); - - df = createDateField(); - mainLayout.addComponent(df, 1, 2); - mainLayout.setComponentAlignment(df, Alignment.BOTTOM_CENTER); - - mainWindow.setContent(mainLayout); - setMainWindow(mainWindow); - } - - private DateField createDateField() { - DateField df = new DateField(); - df.setDescription("This is a long, multiline tooltip.
It should always be on screen so it can be read."); - df.setValue(new Date(1000000L)); - return df; - } -} +package com.vaadin.tests.components.datefield; + +import java.sql.Date; + +import com.vaadin.tests.components.AbstractTestCase; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.DateField; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.Window; + +public class DateFieldPopupOffScreen extends AbstractTestCase { + + @Override + protected String getDescription() { + return "Test for the popup position from a DateField. The popup should always be on-screen even if the DateField is close the the edge of the browser."; + } + + @Override + protected Integer getTicketNumber() { + return 3639; + } + + @Override + public void init() { + Window mainWindow = new Window(getClass().getName()); + + GridLayout mainLayout = new GridLayout(3, 3); + mainLayout.setSizeFull(); + + DateField df; + + df = createDateField(); + mainLayout.addComponent(df, 2, 0); + mainLayout.setComponentAlignment(df, Alignment.TOP_RIGHT); + + df = createDateField(); + mainLayout.addComponent(df, 2, 1); + mainLayout.setComponentAlignment(df, Alignment.MIDDLE_RIGHT); + + df = createDateField(); + mainLayout.addComponent(df, 2, 2); + mainLayout.setComponentAlignment(df, Alignment.BOTTOM_RIGHT); + + df = createDateField(); + mainLayout.addComponent(df, 0, 2); + mainLayout.setComponentAlignment(df, Alignment.BOTTOM_LEFT); + + df = createDateField(); + mainLayout.addComponent(df, 1, 2); + mainLayout.setComponentAlignment(df, Alignment.BOTTOM_CENTER); + + mainWindow.setContent(mainLayout); + setMainWindow(mainWindow); + } + + private DateField createDateField() { + DateField df = new DateField(); + df.setDescription("This is a long, multiline tooltip.
It should always be on screen so it can be read."); + df.setValue(new Date(1000000L)); + return df; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldReadOnly.java b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldReadOnly.java index 3084eab32b..516d207a38 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldReadOnly.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldReadOnly.java @@ -1,53 +1,53 @@ -package com.vaadin.tests.components.datefield; - -import java.util.Calendar; -import java.util.Locale; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.DateField; - -public class DateFieldReadOnly extends TestBase { - - @Override - protected String getDescription() { - return "A read-only DateField should not show the popup button and not be editable."; - } - - @Override - protected Integer getTicketNumber() { - return 3163; - } - - @Override - protected void setup() { - final DateField timeField = new DateField("A read-only datefield"); - timeField.setResolution(DateField.RESOLUTION_SEC); - timeField.setDateFormat("HH:mm:ss"); - timeField.setCaption(null); - timeField.setIcon(null); - timeField.setWidth("8em"); - timeField.addStyleName("timeField"); - - // Set date so that testing always has same time - Calendar c = Calendar.getInstance(Locale.ENGLISH); - c.set(2009, 05, 12, 0, 0, 0); - - timeField.setValue(c.getTime()); - timeField.setReadOnly(true); - - addComponent(timeField); - - Button b = new Button("Switch read-only"); - b.addListener(new ClickListener() { - - public void buttonClick(ClickEvent event) { - timeField.setReadOnly(!timeField.isReadOnly()); - } - }); - - addComponent(b); - } -} +package com.vaadin.tests.components.datefield; + +import java.util.Calendar; +import java.util.Locale; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.DateField; + +public class DateFieldReadOnly extends TestBase { + + @Override + protected String getDescription() { + return "A read-only DateField should not show the popup button and not be editable."; + } + + @Override + protected Integer getTicketNumber() { + return 3163; + } + + @Override + protected void setup() { + final DateField timeField = new DateField("A read-only datefield"); + timeField.setResolution(DateField.RESOLUTION_SEC); + timeField.setDateFormat("HH:mm:ss"); + timeField.setCaption(null); + timeField.setIcon(null); + timeField.setWidth("8em"); + timeField.addStyleName("timeField"); + + // Set date so that testing always has same time + Calendar c = Calendar.getInstance(Locale.ENGLISH); + c.set(2009, 05, 12, 0, 0, 0); + + timeField.setValue(c.getTime()); + timeField.setReadOnly(true); + + addComponent(timeField); + + Button b = new Button("Switch read-only"); + b.addListener(new ClickListener() { + + public void buttonClick(ClickEvent event) { + timeField.setReadOnly(!timeField.isReadOnly()); + } + }); + + addComponent(b); + } +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java index cf433257bb..7d1bdfc2c8 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldTest.java @@ -1,137 +1,137 @@ -package com.vaadin.tests.components.datefield; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.Locale; - -import com.vaadin.tests.components.abstractfield.AbstractFieldTest; -import com.vaadin.ui.DateField; - -public class DateFieldTest extends AbstractFieldTest { - - @Override - protected Class getTestClass() { - return (Class) DateField.class; - } - - private Command setValue = new Command() { - - public void execute(T c, Date value, Object data) { - c.setValue(value); - } - }; - - @Override - protected void createActions() { - super.createActions(); - createResolutionSelectAction(CATEGORY_FEATURES); - createBooleanAction("Lenient", CATEGORY_FEATURES, false, lenientCommand); - createBooleanAction("Show week numbers", CATEGORY_FEATURES, false, - weekNumberCommand); - createDateFormatSelectAction(CATEGORY_FEATURES); - createSetValueAction(CATEGORY_FEATURES); - - }; - - private void createSetValueAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("(null)", null); - options.put("(current time)", new Date()); - Calendar c = Calendar.getInstance(new Locale("fi", "FI")); - c.clear(); - c.set(2010, 12 - 1, 12, 12, 0, 0); - c.set(Calendar.MILLISECOND, 0); - options.put("2010-12-12 12:00:00.000", c.getTime()); - c.clear(); - c.set(2000, 1 - 1, 2, 3, 4, 5); - c.set(Calendar.MILLISECOND, 6); - options.put("2000-01-02 03:04:05.006", c.getTime()); - createMultiClickAction("Set value", category, options, setValue, null); - } - - private void createDateFormatSelectAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - - options.put("-", null); - options.put("d M yyyy", "d M yyyy"); - options.put("d MM yyyy", "d MM yyyy"); - options.put("d MMM yyyy", "d MMM yyyy"); - options.put("d MMMM yyyy", "d MMMM yyyy"); - options.put("dd M yyyy", "dd M yyyy"); - options.put("ddd M yyyy", "ddd M yyyy"); - options.put("d M y", "d M y"); - options.put("d M yy", "d M yy"); - options.put("d M yyy", "d M yyy"); - options.put("d M yyyy", "d M yyyy"); - options.put("d M 'custom text' yyyy", "d M 'custom text' yyyy"); - options.put("'day:'d', month:'M', year: 'yyyy", - "'day:'d', month:'M', year: 'yyyy"); - options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.LONG), - getDatePattern(new Locale("fi", "FI"), DateFormat.LONG)); - options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM), - getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM)); - options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT), - getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT)); - - createSelectAction("Date format", category, options, "-", - dateFormatCommand); - - } - - private String getDatePattern(Locale locale, int dateStyle) { - DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale); - - if (dateFormat instanceof SimpleDateFormat) { - String pattern = ((SimpleDateFormat) dateFormat).toPattern(); - return pattern; - } - return null; - - } - - private void createResolutionSelectAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("Year", DateField.RESOLUTION_YEAR); - options.put("Month", DateField.RESOLUTION_MONTH); - options.put("Day", DateField.RESOLUTION_DAY); - options.put("Hour", DateField.RESOLUTION_HOUR); - options.put("Min", DateField.RESOLUTION_MIN); - options.put("Sec", DateField.RESOLUTION_SEC); - options.put("Msec", DateField.RESOLUTION_MSEC); - - createSelectAction("Resolution", category, options, "Year", - resolutionCommand); - } - - private Command resolutionCommand = new Command() { - - public void execute(T c, Integer value, Object data) { - c.setResolution(value); - - } - }; - private Command lenientCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setLenient(false); - - } - }; - private Command weekNumberCommand = new Command() { - - public void execute(T c, Boolean value, Object data) { - c.setShowISOWeekNumbers(value); - - } - }; - private Command dateFormatCommand = new Command() { - - public void execute(T c, String value, Object data) { - c.setDateFormat(value); - } - }; - -} +package com.vaadin.tests.components.datefield; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Locale; + +import com.vaadin.tests.components.abstractfield.AbstractFieldTest; +import com.vaadin.ui.DateField; + +public class DateFieldTest extends AbstractFieldTest { + + @Override + protected Class getTestClass() { + return (Class) DateField.class; + } + + private Command setValue = new Command() { + + public void execute(T c, Date value, Object data) { + c.setValue(value); + } + }; + + @Override + protected void createActions() { + super.createActions(); + createResolutionSelectAction(CATEGORY_FEATURES); + createBooleanAction("Lenient", CATEGORY_FEATURES, false, lenientCommand); + createBooleanAction("Show week numbers", CATEGORY_FEATURES, false, + weekNumberCommand); + createDateFormatSelectAction(CATEGORY_FEATURES); + createSetValueAction(CATEGORY_FEATURES); + + }; + + private void createSetValueAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("(null)", null); + options.put("(current time)", new Date()); + Calendar c = Calendar.getInstance(new Locale("fi", "FI")); + c.clear(); + c.set(2010, 12 - 1, 12, 12, 0, 0); + c.set(Calendar.MILLISECOND, 0); + options.put("2010-12-12 12:00:00.000", c.getTime()); + c.clear(); + c.set(2000, 1 - 1, 2, 3, 4, 5); + c.set(Calendar.MILLISECOND, 6); + options.put("2000-01-02 03:04:05.006", c.getTime()); + createMultiClickAction("Set value", category, options, setValue, null); + } + + private void createDateFormatSelectAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + + options.put("-", null); + options.put("d M yyyy", "d M yyyy"); + options.put("d MM yyyy", "d MM yyyy"); + options.put("d MMM yyyy", "d MMM yyyy"); + options.put("d MMMM yyyy", "d MMMM yyyy"); + options.put("dd M yyyy", "dd M yyyy"); + options.put("ddd M yyyy", "ddd M yyyy"); + options.put("d M y", "d M y"); + options.put("d M yy", "d M yy"); + options.put("d M yyy", "d M yyy"); + options.put("d M yyyy", "d M yyyy"); + options.put("d M 'custom text' yyyy", "d M 'custom text' yyyy"); + options.put("'day:'d', month:'M', year: 'yyyy", + "'day:'d', month:'M', year: 'yyyy"); + options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.LONG), + getDatePattern(new Locale("fi", "FI"), DateFormat.LONG)); + options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM), + getDatePattern(new Locale("fi", "FI"), DateFormat.MEDIUM)); + options.put(getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT), + getDatePattern(new Locale("fi", "FI"), DateFormat.SHORT)); + + createSelectAction("Date format", category, options, "-", + dateFormatCommand); + + } + + private String getDatePattern(Locale locale, int dateStyle) { + DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale); + + if (dateFormat instanceof SimpleDateFormat) { + String pattern = ((SimpleDateFormat) dateFormat).toPattern(); + return pattern; + } + return null; + + } + + private void createResolutionSelectAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("Year", DateField.RESOLUTION_YEAR); + options.put("Month", DateField.RESOLUTION_MONTH); + options.put("Day", DateField.RESOLUTION_DAY); + options.put("Hour", DateField.RESOLUTION_HOUR); + options.put("Min", DateField.RESOLUTION_MIN); + options.put("Sec", DateField.RESOLUTION_SEC); + options.put("Msec", DateField.RESOLUTION_MSEC); + + createSelectAction("Resolution", category, options, "Year", + resolutionCommand); + } + + private Command resolutionCommand = new Command() { + + public void execute(T c, Integer value, Object data) { + c.setResolution(value); + + } + }; + private Command lenientCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setLenient(false); + + } + }; + private Command weekNumberCommand = new Command() { + + public void execute(T c, Boolean value, Object data) { + c.setShowISOWeekNumbers(value); + + } + }; + private Command dateFormatCommand = new Command() { + + public void execute(T c, String value, Object data) { + c.setDateFormat(value); + } + }; + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java index 32456e34c5..4f83575b39 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DateFieldUnparsableDate.java @@ -1,101 +1,101 @@ -package com.vaadin.tests.components.datefield; - -import java.util.Date; - -import com.vaadin.data.Property; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.DateField; - -public class DateFieldUnparsableDate extends TestBase { - - public class MyDateField extends DateField { - Date oldDate = null; - - public MyDateField(String caption) { - super(caption); - addListener(new Property.ValueChangeListener() { - public void valueChange( - com.vaadin.data.Property.ValueChangeEvent event) { - oldDate = (Date) getValue(); - } - }); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - throws ConversionException { - return oldDate; - } - } - - public class MyDateField2 extends DateField { - public MyDateField2(String caption) { - super(caption); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - throws ConversionException { - return null; - } - } - - public class MyDateField3 extends DateField { - public MyDateField3(String caption) { - super(caption); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - throws ConversionException { - throw new ConversionException("You should not enter invalid dates!"); - } - } - - public class MyDateField4 extends DateField { - public MyDateField4(String caption) { - super(caption); - } - - @Override - protected Date handleUnparsableDateString(String dateString) - throws ConversionException { - if (dateString != null && dateString.equals("today")) { - return new Date(); - } - throw new ConversionException("You should not enter invalid dates!"); - } - } - - @Override - protected void setup() { - MyDateField df = new MyDateField( - "Returns the old value for invalid dates"); - df.setImmediate(true); - addComponent(df); - - MyDateField2 df2 = new MyDateField2("Returns empty for invalid dates"); - df2.setImmediate(true); - addComponent(df2); - - MyDateField3 df3 = new MyDateField3( - "Throws an exception for invalid dates"); - df3.setImmediate(true); - addComponent(df3); - - MyDateField4 df4 = new MyDateField4("Can convert 'today'"); - df4.setImmediate(true); - addComponent(df4); - - } - - @Override - protected String getDescription() { - return "DateFields in various configurations (according to caption). All handle unparsable dates differently"; - } - - @Override - protected Integer getTicketNumber() { - return 4236; - } -} +package com.vaadin.tests.components.datefield; + +import java.util.Date; + +import com.vaadin.data.Property; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.DateField; + +public class DateFieldUnparsableDate extends TestBase { + + public class MyDateField extends DateField { + Date oldDate = null; + + public MyDateField(String caption) { + super(caption); + addListener(new Property.ValueChangeListener() { + public void valueChange( + com.vaadin.data.Property.ValueChangeEvent event) { + oldDate = (Date) getValue(); + } + }); + } + + @Override + protected Date handleUnparsableDateString(String dateString) + throws ConversionException { + return oldDate; + } + } + + public class MyDateField2 extends DateField { + public MyDateField2(String caption) { + super(caption); + } + + @Override + protected Date handleUnparsableDateString(String dateString) + throws ConversionException { + return null; + } + } + + public class MyDateField3 extends DateField { + public MyDateField3(String caption) { + super(caption); + } + + @Override + protected Date handleUnparsableDateString(String dateString) + throws ConversionException { + throw new ConversionException("You should not enter invalid dates!"); + } + } + + public class MyDateField4 extends DateField { + public MyDateField4(String caption) { + super(caption); + } + + @Override + protected Date handleUnparsableDateString(String dateString) + throws ConversionException { + if (dateString != null && dateString.equals("today")) { + return new Date(); + } + throw new ConversionException("You should not enter invalid dates!"); + } + } + + @Override + protected void setup() { + MyDateField df = new MyDateField( + "Returns the old value for invalid dates"); + df.setImmediate(true); + addComponent(df); + + MyDateField2 df2 = new MyDateField2("Returns empty for invalid dates"); + df2.setImmediate(true); + addComponent(df2); + + MyDateField3 df3 = new MyDateField3( + "Throws an exception for invalid dates"); + df3.setImmediate(true); + addComponent(df3); + + MyDateField4 df4 = new MyDateField4("Can convert 'today'"); + df4.setImmediate(true); + addComponent(df4); + + } + + @Override + protected String getDescription() { + return "DateFields in various configurations (according to caption). All handle unparsable dates differently"; + } + + @Override + protected Integer getTicketNumber() { + return 4236; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DatePopupStyleName.java b/tests/testbench/com/vaadin/tests/components/datefield/DatePopupStyleName.java index ba4e324dc1..3c42d71af5 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DatePopupStyleName.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DatePopupStyleName.java @@ -1,33 +1,33 @@ -package com.vaadin.tests.components.datefield; - -import java.util.Date; - -import com.vaadin.terminal.UserError; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.DateField; - -public class DatePopupStyleName extends TestBase { - @Override - public void setup() { - setTheme("reindeer-tests"); - - final DateField df = new DateField(); - df.setValue(new Date(1203910239L)); - df.setWidth("200px"); - df.setRequired(true); - df.setComponentError(new UserError("abc")); - df.addStyleName("popup-style"); - addComponent(df); - } - - @Override - protected String getDescription() { - return "The DateField is given a style name 'test', but that style isn't applied on the calendar popup element."; - } - - @Override - protected Integer getTicketNumber() { - return 8083; - } - -} +package com.vaadin.tests.components.datefield; + +import java.util.Date; + +import com.vaadin.terminal.UserError; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.DateField; + +public class DatePopupStyleName extends TestBase { + @Override + public void setup() { + setTheme("reindeer-tests"); + + final DateField df = new DateField(); + df.setValue(new Date(1203910239L)); + df.setWidth("200px"); + df.setRequired(true); + df.setComponentError(new UserError("abc")); + df.addStyleName("popup-style"); + addComponent(df); + } + + @Override + protected String getDescription() { + return "The DateField is given a style name 'test', but that style isn't applied on the calendar popup element."; + } + + @Override + protected Integer getTicketNumber() { + return 8083; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/DisabledDateFieldWidth.java b/tests/testbench/com/vaadin/tests/components/datefield/DisabledDateFieldWidth.java index 33156b9a75..8f201e120d 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/DisabledDateFieldWidth.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/DisabledDateFieldWidth.java @@ -1,42 +1,42 @@ -package com.vaadin.tests.components.datefield; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.DateField; -import com.vaadin.ui.GridLayout; - -public class DisabledDateFieldWidth extends TestBase { - @Override - public void setup() { - - final DateField dateField1 = new DateField("DateField"); - dateField1.setResolution(DateField.RESOLUTION_YEAR); - dateField1.setEnabled(false); - - Button button = new Button("Repaint datefield", - new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - dateField1.requestRepaint(); - } - }); - - GridLayout gl = new GridLayout(3, 1); - gl.addComponent(dateField1); - gl.addComponent(button); - - addComponent(gl); - } - - @Override - protected String getDescription() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected Integer getTicketNumber() { - // TODO Auto-generated method stub - return null; - } -} +package com.vaadin.tests.components.datefield; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.DateField; +import com.vaadin.ui.GridLayout; + +public class DisabledDateFieldWidth extends TestBase { + @Override + public void setup() { + + final DateField dateField1 = new DateField("DateField"); + dateField1.setResolution(DateField.RESOLUTION_YEAR); + dateField1.setEnabled(false); + + Button button = new Button("Repaint datefield", + new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + dateField1.requestRepaint(); + } + }); + + GridLayout gl = new GridLayout(3, 1); + gl.addComponent(dateField1); + gl.addComponent(button); + + addComponent(gl); + } + + @Override + protected String getDescription() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected Integer getTicketNumber() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFieldTest.java b/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFieldTest.java index c2384584e2..1c8d8cfae6 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFieldTest.java @@ -1,12 +1,12 @@ -package com.vaadin.tests.components.datefield; - -import com.vaadin.ui.InlineDateField; - -public class InlineDateFieldTest extends DateFieldTest { - - @Override - protected Class getTestClass() { - return InlineDateField.class; - } - -} +package com.vaadin.tests.components.datefield; + +import com.vaadin.ui.InlineDateField; + +public class InlineDateFieldTest extends DateFieldTest { + + @Override + protected Class getTestClass() { + return InlineDateField.class; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java b/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java index 083e8f0190..56f3641043 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/InlineDateFields.java @@ -1,106 +1,106 @@ -package com.vaadin.tests.components.datefield; - -import java.sql.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; - -import com.vaadin.tests.components.ComponentTestCase; -import com.vaadin.ui.Component; -import com.vaadin.ui.DateField; -import com.vaadin.ui.InlineDateField; - -@SuppressWarnings("serial") -public class InlineDateFields extends ComponentTestCase { - - private static final Locale[] LOCALES = new Locale[] { Locale.US, - Locale.TAIWAN, new Locale("fi", "FI") }; - - @Override - protected Class getTestClass() { - return InlineDateField.class; - } - - @Override - protected void initializeComponents() { - - Locale locale = LOCALES[0]; - - InlineDateField pd = createInlineDateField("Undefined width", "-1", - locale); - pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide"); - addTestComponent(pd); - pd = createInlineDateField("300px width", "300px", locale); - pd.setDebugId("Locale-" + locale.toString() + "-300px-wide"); - addTestComponent(pd); - pd = createInlineDateField("Initially empty", "", locale); - pd.setValue(null); - pd.setDebugId("Locale-" + locale.toString() + "-initially-empty"); - addTestComponent(pd); - - } - - private InlineDateField createInlineDateField(String caption, String width, - Locale locale) { - InlineDateField pd = new InlineDateField(caption + "(" - + locale.toString() + ")"); - pd.setWidth(width); - pd.setValue(new Date(12312312313L)); - pd.setLocale(locale); - pd.setResolution(DateField.RESOLUTION_YEAR); - - return pd; - } - - @Override - protected String getDescription() { - return "A generic test for InlineDateFields in different configurations"; - } - - @Override - protected List createActions() { - List actions = super.createActions(); - actions.add(createResolutionSelectAction()); - actions.add(createLocaleSelectAction()); - return actions; - } - - private Component createResolutionSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - options.put("Year", DateField.RESOLUTION_YEAR); - options.put("Month", DateField.RESOLUTION_MONTH); - options.put("Day", DateField.RESOLUTION_DAY); - options.put("Hour", DateField.RESOLUTION_HOUR); - options.put("Min", DateField.RESOLUTION_MIN); - options.put("Sec", DateField.RESOLUTION_SEC); - options.put("Msec", DateField.RESOLUTION_MSEC); - return createSelectAction("Resolution", options, "Year", - new Command() { - - public void execute(InlineDateField c, Integer value, - Object data) { - c.setResolution(value); - - } - }); - } - - private Component createLocaleSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - for (Locale locale : LOCALES) { - options.put(locale.toString(), locale); - } - return createSelectAction("Locale", options, LOCALES[0].toString(), - new Command() { - - public void execute(InlineDateField c, Locale value, - Object data) { - c.setCaption(c.getCaption().replaceAll( - c.getLocale().toString(), value.toString())); - c.setLocale(value); - - } - }); - } - -} +package com.vaadin.tests.components.datefield; + +import java.sql.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; + +import com.vaadin.tests.components.ComponentTestCase; +import com.vaadin.ui.Component; +import com.vaadin.ui.DateField; +import com.vaadin.ui.InlineDateField; + +@SuppressWarnings("serial") +public class InlineDateFields extends ComponentTestCase { + + private static final Locale[] LOCALES = new Locale[] { Locale.US, + Locale.TAIWAN, new Locale("fi", "FI") }; + + @Override + protected Class getTestClass() { + return InlineDateField.class; + } + + @Override + protected void initializeComponents() { + + Locale locale = LOCALES[0]; + + InlineDateField pd = createInlineDateField("Undefined width", "-1", + locale); + pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide"); + addTestComponent(pd); + pd = createInlineDateField("300px width", "300px", locale); + pd.setDebugId("Locale-" + locale.toString() + "-300px-wide"); + addTestComponent(pd); + pd = createInlineDateField("Initially empty", "", locale); + pd.setValue(null); + pd.setDebugId("Locale-" + locale.toString() + "-initially-empty"); + addTestComponent(pd); + + } + + private InlineDateField createInlineDateField(String caption, String width, + Locale locale) { + InlineDateField pd = new InlineDateField(caption + "(" + + locale.toString() + ")"); + pd.setWidth(width); + pd.setValue(new Date(12312312313L)); + pd.setLocale(locale); + pd.setResolution(DateField.RESOLUTION_YEAR); + + return pd; + } + + @Override + protected String getDescription() { + return "A generic test for InlineDateFields in different configurations"; + } + + @Override + protected List createActions() { + List actions = super.createActions(); + actions.add(createResolutionSelectAction()); + actions.add(createLocaleSelectAction()); + return actions; + } + + private Component createResolutionSelectAction() { + LinkedHashMap options = new LinkedHashMap(); + options.put("Year", DateField.RESOLUTION_YEAR); + options.put("Month", DateField.RESOLUTION_MONTH); + options.put("Day", DateField.RESOLUTION_DAY); + options.put("Hour", DateField.RESOLUTION_HOUR); + options.put("Min", DateField.RESOLUTION_MIN); + options.put("Sec", DateField.RESOLUTION_SEC); + options.put("Msec", DateField.RESOLUTION_MSEC); + return createSelectAction("Resolution", options, "Year", + new Command() { + + public void execute(InlineDateField c, Integer value, + Object data) { + c.setResolution(value); + + } + }); + } + + private Component createLocaleSelectAction() { + LinkedHashMap options = new LinkedHashMap(); + for (Locale locale : LOCALES) { + options.put(locale.toString(), locale); + } + return createSelectAction("Locale", options, LOCALES[0].toString(), + new Command() { + + public void execute(InlineDateField c, Locale value, + Object data) { + c.setCaption(c.getCaption().replaceAll( + c.getLocale().toString(), value.toString())); + c.setLocale(value); + + } + }); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/NarrowPopupDateFieldInTable.java b/tests/testbench/com/vaadin/tests/components/datefield/NarrowPopupDateFieldInTable.java index 73ec3b659e..dab47ebdd9 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/NarrowPopupDateFieldInTable.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/NarrowPopupDateFieldInTable.java @@ -1,34 +1,34 @@ -package com.vaadin.tests.components.datefield; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Component; -import com.vaadin.ui.PopupDateField; -import com.vaadin.ui.Table; - -public class NarrowPopupDateFieldInTable extends TestBase { - - private final Object DATE = "Date"; - - @Override - public void setup() { - PopupDateField df = new PopupDateField(); - df.setWidth("100%"); - - Table t = new Table(); - t.setWidth("100px"); - t.addContainerProperty(DATE, Component.class, null); - t.addItem(new Object[] { df }, "1"); - addComponent(t); - } - - @Override - protected String getDescription() { - return "Simple test to ensure a narrow PopupDateField can be used in a Table."; - } - - @Override - protected Integer getTicketNumber() { - return 6166; - } - +package com.vaadin.tests.components.datefield; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Component; +import com.vaadin.ui.PopupDateField; +import com.vaadin.ui.Table; + +public class NarrowPopupDateFieldInTable extends TestBase { + + private final Object DATE = "Date"; + + @Override + public void setup() { + PopupDateField df = new PopupDateField(); + df.setWidth("100%"); + + Table t = new Table(); + t.setWidth("100px"); + t.addContainerProperty(DATE, Component.class, null); + t.addItem(new Object[] { df }, "1"); + addComponent(t); + } + + @Override + protected String getDescription() { + return "Simple test to ensure a narrow PopupDateField can be used in a Table."; + } + + @Override + protected Integer getTicketNumber() { + return 6166; + } + } \ No newline at end of file diff --git a/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFieldTest.java b/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFieldTest.java index ae238b2a91..3ab1f52891 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFieldTest.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFieldTest.java @@ -1,38 +1,38 @@ -package com.vaadin.tests.components.datefield; - -import java.util.LinkedHashMap; - -import com.vaadin.ui.PopupDateField; - -public class PopupDateFieldTest extends DateFieldTest { - - @Override - protected Class getTestClass() { - return PopupDateField.class; - } - - @Override - protected void createActions() { - super.createActions(); - - createInputPromptSelectAction(CATEGORY_FEATURES); - } - - private void createInputPromptSelectAction(String category) { - LinkedHashMap options = new LinkedHashMap(); - options.put("", null); - options.put("Please enter date", "Please enter date"); - options.put("åäöÅÄÖ", "åäöÅÄÖ"); - - createSelectAction("Input prompt", category, options, "", - new Command() { - - public void execute(PopupDateField c, String value, - Object data) { - c.setInputPrompt(value); - - } - }); - } - -} +package com.vaadin.tests.components.datefield; + +import java.util.LinkedHashMap; + +import com.vaadin.ui.PopupDateField; + +public class PopupDateFieldTest extends DateFieldTest { + + @Override + protected Class getTestClass() { + return PopupDateField.class; + } + + @Override + protected void createActions() { + super.createActions(); + + createInputPromptSelectAction(CATEGORY_FEATURES); + } + + private void createInputPromptSelectAction(String category) { + LinkedHashMap options = new LinkedHashMap(); + options.put("", null); + options.put("Please enter date", "Please enter date"); + options.put("åäöÅÄÖ", "åäöÅÄÖ"); + + createSelectAction("Input prompt", category, options, "", + new Command() { + + public void execute(PopupDateField c, String value, + Object data) { + c.setInputPrompt(value); + + } + }); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java b/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java index 8b9cb68d7b..7e8b19b2a1 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/PopupDateFields.java @@ -1,105 +1,105 @@ -package com.vaadin.tests.components.datefield; - -import java.sql.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; - -import com.vaadin.tests.components.ComponentTestCase; -import com.vaadin.ui.Component; -import com.vaadin.ui.DateField; -import com.vaadin.ui.PopupDateField; - -@SuppressWarnings("serial") -public class PopupDateFields extends ComponentTestCase { - - private static final Locale[] LOCALES = new Locale[] { Locale.US, - Locale.TAIWAN, new Locale("fi", "FI") }; - - @Override - protected Class getTestClass() { - return PopupDateField.class; - } - - @Override - protected void initializeComponents() { - - for (Locale locale : LOCALES) { - PopupDateField pd = createPopupDateField("Undefined width", "-1", - locale); - pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide"); - addTestComponent(pd); - pd = createPopupDateField("500px width", "500px", locale); - pd.setDebugId("Locale-" + locale.toString() + "-500px-wide"); - addTestComponent(pd); - pd = createPopupDateField("Initially empty", "", locale); - pd.setValue(null); - pd.setDebugId("Locale-" + locale.toString() + "-initially-empty"); - addTestComponent(pd); - } - - } - - private PopupDateField createPopupDateField(String caption, String width, - Locale locale) { - PopupDateField pd = new PopupDateField(caption + "(" - + locale.toString() + ")"); - pd.setWidth(width); - pd.setValue(new Date(12312312313L)); - pd.setLocale(locale); - pd.setResolution(DateField.RESOLUTION_YEAR); - - return pd; - } - - @Override - protected String getDescription() { - return "A generic test for PopupDateFields in different configurations"; - } - - @Override - protected List createActions() { - List actions = super.createActions(); - actions.add(createResolutionSelectAction()); - actions.add(createInputPromptSelectAction()); - return actions; - } - - private Component createResolutionSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - options.put("Year", DateField.RESOLUTION_YEAR); - options.put("Month", DateField.RESOLUTION_MONTH); - options.put("Day", DateField.RESOLUTION_DAY); - options.put("Hour", DateField.RESOLUTION_HOUR); - options.put("Min", DateField.RESOLUTION_MIN); - options.put("Sec", DateField.RESOLUTION_SEC); - options.put("Msec", DateField.RESOLUTION_MSEC); - return createSelectAction("Resolution", options, "Year", - new Command() { - - public void execute(PopupDateField c, Integer value, - Object data) { - c.setResolution(value); - - } - }); - } - - private Component createInputPromptSelectAction() { - LinkedHashMap options = new LinkedHashMap(); - options.put("", null); - options.put("Please enter date", "Please enter date"); - options.put("åäöÅÄÖ", "åäöÅÄÖ"); - - return createSelectAction("Input prompt", options, "", - new Command() { - - public void execute(PopupDateField c, String value, - Object data) { - c.setInputPrompt(value); - - } - }); - } - -} +package com.vaadin.tests.components.datefield; + +import java.sql.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; + +import com.vaadin.tests.components.ComponentTestCase; +import com.vaadin.ui.Component; +import com.vaadin.ui.DateField; +import com.vaadin.ui.PopupDateField; + +@SuppressWarnings("serial") +public class PopupDateFields extends ComponentTestCase { + + private static final Locale[] LOCALES = new Locale[] { Locale.US, + Locale.TAIWAN, new Locale("fi", "FI") }; + + @Override + protected Class getTestClass() { + return PopupDateField.class; + } + + @Override + protected void initializeComponents() { + + for (Locale locale : LOCALES) { + PopupDateField pd = createPopupDateField("Undefined width", "-1", + locale); + pd.setDebugId("Locale-" + locale.toString() + "-undefined-wide"); + addTestComponent(pd); + pd = createPopupDateField("500px width", "500px", locale); + pd.setDebugId("Locale-" + locale.toString() + "-500px-wide"); + addTestComponent(pd); + pd = createPopupDateField("Initially empty", "", locale); + pd.setValue(null); + pd.setDebugId("Locale-" + locale.toString() + "-initially-empty"); + addTestComponent(pd); + } + + } + + private PopupDateField createPopupDateField(String caption, String width, + Locale locale) { + PopupDateField pd = new PopupDateField(caption + "(" + + locale.toString() + ")"); + pd.setWidth(width); + pd.setValue(new Date(12312312313L)); + pd.setLocale(locale); + pd.setResolution(DateField.RESOLUTION_YEAR); + + return pd; + } + + @Override + protected String getDescription() { + return "A generic test for PopupDateFields in different configurations"; + } + + @Override + protected List createActions() { + List actions = super.createActions(); + actions.add(createResolutionSelectAction()); + actions.add(createInputPromptSelectAction()); + return actions; + } + + private Component createResolutionSelectAction() { + LinkedHashMap options = new LinkedHashMap(); + options.put("Year", DateField.RESOLUTION_YEAR); + options.put("Month", DateField.RESOLUTION_MONTH); + options.put("Day", DateField.RESOLUTION_DAY); + options.put("Hour", DateField.RESOLUTION_HOUR); + options.put("Min", DateField.RESOLUTION_MIN); + options.put("Sec", DateField.RESOLUTION_SEC); + options.put("Msec", DateField.RESOLUTION_MSEC); + return createSelectAction("Resolution", options, "Year", + new Command() { + + public void execute(PopupDateField c, Integer value, + Object data) { + c.setResolution(value); + + } + }); + } + + private Component createInputPromptSelectAction() { + LinkedHashMap options = new LinkedHashMap(); + options.put("", null); + options.put("Please enter date", "Please enter date"); + options.put("åäöÅÄÖ", "åäöÅÄÖ"); + + return createSelectAction("Input prompt", options, "", + new Command() { + + public void execute(PopupDateField c, String value, + Object data) { + c.setInputPrompt(value); + + } + }); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/ShowSelectedDateAfterInvalid.java b/tests/testbench/com/vaadin/tests/components/datefield/ShowSelectedDateAfterInvalid.java index fde3d4e56b..6686fa6fe0 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/ShowSelectedDateAfterInvalid.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/ShowSelectedDateAfterInvalid.java @@ -1,57 +1,57 @@ -package com.vaadin.tests.components.datefield; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Form; -import com.vaadin.ui.Label; -import com.vaadin.ui.PopupDateField; - -/** - * First entering an invalid date, forcing a server roundtrip and then selecting - * a valid date from the popup in a non-immediate {@link PopupDateField} caused - * the invalid date string to continue to show. - */ -public class ShowSelectedDateAfterInvalid extends TestBase { - - @Override - protected void setup() { - final Label result = new Label(); - - final Form form = new Form(); - - PopupDateField datefield = new PopupDateField(); - datefield.setResolution(PopupDateField.RESOLUTION_DAY); - datefield.setDateFormat("dd/MM/yyyy"); - - form.addField("datefield", datefield); - - Button button = new Button("Validate"); - - button.addListener(new Button.ClickListener() { - public void buttonClick(Button.ClickEvent event) { - form.setValidationVisible(true); - if (form.isValid()) { - result.setValue("Valid!"); - } else { - result.setValue("Invalid"); - } - } - - }); - - addComponent(form); - addComponent(button); - addComponent(result); - } - - @Override - protected String getDescription() { - return "DateField doesn't show selected value after invalid and then selecting a value"; - } - - @Override - protected Integer getTicketNumber() { - return 5369; - } - -} +package com.vaadin.tests.components.datefield; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Form; +import com.vaadin.ui.Label; +import com.vaadin.ui.PopupDateField; + +/** + * First entering an invalid date, forcing a server roundtrip and then selecting + * a valid date from the popup in a non-immediate {@link PopupDateField} caused + * the invalid date string to continue to show. + */ +public class ShowSelectedDateAfterInvalid extends TestBase { + + @Override + protected void setup() { + final Label result = new Label(); + + final Form form = new Form(); + + PopupDateField datefield = new PopupDateField(); + datefield.setResolution(PopupDateField.RESOLUTION_DAY); + datefield.setDateFormat("dd/MM/yyyy"); + + form.addField("datefield", datefield); + + Button button = new Button("Validate"); + + button.addListener(new Button.ClickListener() { + public void buttonClick(Button.ClickEvent event) { + form.setValidationVisible(true); + if (form.isValid()) { + result.setValue("Valid!"); + } else { + result.setValue("Invalid"); + } + } + + }); + + addComponent(form); + addComponent(button); + addComponent(result); + } + + @Override + protected String getDescription() { + return "DateField doesn't show selected value after invalid and then selecting a value"; + } + + @Override + protected Integer getTicketNumber() { + return 5369; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/datefield/WidthRecalculationOnEnableStateChange.java b/tests/testbench/com/vaadin/tests/components/datefield/WidthRecalculationOnEnableStateChange.java index f25a9f0350..517bf2ee76 100644 --- a/tests/testbench/com/vaadin/tests/components/datefield/WidthRecalculationOnEnableStateChange.java +++ b/tests/testbench/com/vaadin/tests/components/datefield/WidthRecalculationOnEnableStateChange.java @@ -1,44 +1,44 @@ -package com.vaadin.tests.components.datefield; - -import java.util.Date; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.DateField; - -public class WidthRecalculationOnEnableStateChange extends TestBase { - @Override - public void setup() { - setTheme("reindeer-tests"); - - final DateField df = new DateField(); - df.setValue(new Date(1203910239L)); - df.setWidth("200px"); - df.addStyleName("enabled-readonly-styled"); - addComponent(df); - addComponent(new Button("Toggle disabled for date field", - new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - df.setEnabled(!df.isEnabled()); - } - })); - addComponent(new Button("Toggle read only for date field", - new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - df.setReadOnly(!df.isReadOnly()); - } - })); - } - - @Override - protected String getDescription() { - return "Setting the disabled state doesn't recalculate the input element width. Setting the read-only state instead recalculates the width. In both cases, the popup button is hidden using CSS.

The DateField is also given a style name 'test', but that style isn't applied on the calendar popup element."; - } - - @Override - protected Integer getTicketNumber() { - return 8085; - } - -} +package com.vaadin.tests.components.datefield; + +import java.util.Date; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.DateField; + +public class WidthRecalculationOnEnableStateChange extends TestBase { + @Override + public void setup() { + setTheme("reindeer-tests"); + + final DateField df = new DateField(); + df.setValue(new Date(1203910239L)); + df.setWidth("200px"); + df.addStyleName("enabled-readonly-styled"); + addComponent(df); + addComponent(new Button("Toggle disabled for date field", + new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + df.setEnabled(!df.isEnabled()); + } + })); + addComponent(new Button("Toggle read only for date field", + new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + df.setReadOnly(!df.isReadOnly()); + } + })); + } + + @Override + protected String getDescription() { + return "Setting the disabled state doesn't recalculate the input element width. Setting the read-only state instead recalculates the width. In both cases, the popup button is hidden using CSS.

The DateField is also given a style name 'test', but that style isn't applied on the calendar popup element."; + } + + @Override + protected Integer getTicketNumber() { + return 8085; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedFlash.java b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedFlash.java index 87e0714545..fb6b55ded0 100644 --- a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedFlash.java +++ b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedFlash.java @@ -1,34 +1,34 @@ -package com.vaadin.tests.components.embedded; - -import com.vaadin.terminal.ExternalResource; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Embedded; - -public class EmbeddedFlash extends TestBase { - - @Override - protected String getDescription() { - return "The embedded flash should have the movie parameter set to \"someRandomValue\" and an allowFullScreen parameter set to \"true\"."; - } - - @Override - protected Integer getTicketNumber() { - return 3367; - } - - @Override - public void setup() { - Embedded player = new Embedded(); - player.setType(Embedded.TYPE_OBJECT); - player.setWidth("400px"); - player.setHeight("300px"); - player.setMimeType("application/x-shockwave-flash"); - String url = "http://www.youtube.com/v/qQ9N742QB4g&autoplay=1"; - player.setSource(new ExternalResource(url)); - player.setParameter("movie", "someRandomValue"); - player.setParameter("allowFullScreen", "true"); - - addComponent(player); - } - -} +package com.vaadin.tests.components.embedded; + +import com.vaadin.terminal.ExternalResource; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Embedded; + +public class EmbeddedFlash extends TestBase { + + @Override + protected String getDescription() { + return "The embedded flash should have the movie parameter set to \"someRandomValue\" and an allowFullScreen parameter set to \"true\"."; + } + + @Override + protected Integer getTicketNumber() { + return 3367; + } + + @Override + public void setup() { + Embedded player = new Embedded(); + player.setType(Embedded.TYPE_OBJECT); + player.setWidth("400px"); + player.setHeight("300px"); + player.setMimeType("application/x-shockwave-flash"); + String url = "http://www.youtube.com/v/qQ9N742QB4g&autoplay=1"; + player.setSource(new ExternalResource(url)); + player.setParameter("movie", "someRandomValue"); + player.setParameter("allowFullScreen", "true"); + + addComponent(player); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java index bea25a2122..0fb8b27b75 100644 --- a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java +++ b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedPdf.java @@ -1,32 +1,32 @@ -package com.vaadin.tests.components.embedded; - -import com.vaadin.terminal.ClassResource; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Embedded; -import com.vaadin.ui.Window; - -public class EmbeddedPdf extends TestBase { - - @Override - protected String getDescription() { - return "The embedded flash should have the movie parameter set to \"someRandomValue\" and an allowFullScreen parameter set to \"true\"."; - } - - @Override - protected Integer getTicketNumber() { - return 3367; - } - - @Override - public void setup() { - Embedded player = new Embedded(); - player.setType(Embedded.TYPE_BROWSER); - player.setWidth("400px"); - player.setHeight("300px"); - player.setSource(new ClassResource(getClass(), "test.pdf", this)); - addComponent(player); - - player.getWindow().addWindow(new Window("Testwindow")); - } - -} +package com.vaadin.tests.components.embedded; + +import com.vaadin.terminal.ClassResource; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Embedded; +import com.vaadin.ui.Window; + +public class EmbeddedPdf extends TestBase { + + @Override + protected String getDescription() { + return "The embedded flash should have the movie parameter set to \"someRandomValue\" and an allowFullScreen parameter set to \"true\"."; + } + + @Override + protected Integer getTicketNumber() { + return 3367; + } + + @Override + public void setup() { + Embedded player = new Embedded(); + player.setType(Embedded.TYPE_BROWSER); + player.setWidth("400px"); + player.setHeight("300px"); + player.setSource(new ClassResource(getClass(), "test.pdf", this)); + addComponent(player); + + player.getWindow().addWindow(new Window("Testwindow")); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedTooltip.java b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedTooltip.java index 2ac39c05a0..d8be22f507 100644 --- a/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedTooltip.java +++ b/tests/testbench/com/vaadin/tests/components/embedded/EmbeddedTooltip.java @@ -1,27 +1,27 @@ -package com.vaadin.tests.components.embedded; - -import com.vaadin.terminal.ThemeResource; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Embedded; - -public class EmbeddedTooltip extends TestBase { - - @Override - protected String getDescription() { - return "The tooltip for an Embedded image should be visible also when hovering the image"; - } - - @Override - protected Integer getTicketNumber() { - return 2853; - } - - @Override - protected void setup() { - Embedded e = new Embedded("Embedded caption", new ThemeResource( - "../runo/icons/64/ok.png")); - e.setDescription("Embedded tooltip, only shown on caption, not on the image"); - addComponent(e); - - } -} +package com.vaadin.tests.components.embedded; + +import com.vaadin.terminal.ThemeResource; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Embedded; + +public class EmbeddedTooltip extends TestBase { + + @Override + protected String getDescription() { + return "The tooltip for an Embedded image should be visible also when hovering the image"; + } + + @Override + protected Integer getTicketNumber() { + return 2853; + } + + @Override + protected void setup() { + Embedded e = new Embedded("Embedded caption", new ThemeResource( + "../runo/icons/64/ok.png")); + e.setDescription("Embedded tooltip, only shown on caption, not on the image"); + addComponent(e); + + } +} diff --git a/tests/testbench/com/vaadin/tests/components/form/FormFieldCaptions.java b/tests/testbench/com/vaadin/tests/components/form/FormFieldCaptions.java index b4dee985f4..25487fba7c 100644 --- a/tests/testbench/com/vaadin/tests/components/form/FormFieldCaptions.java +++ b/tests/testbench/com/vaadin/tests/components/form/FormFieldCaptions.java @@ -1,86 +1,86 @@ -package com.vaadin.tests.components.form; - -import com.vaadin.data.Item; -import com.vaadin.data.util.BeanItem; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Form; -import com.vaadin.ui.HorizontalLayout; - -public class FormFieldCaptions extends TestBase { - - @Override - protected void setup() { - // Method 1 - Form form1 = new Form(); - Item item1 = createItem(); - for (Object propertyId : item1.getItemPropertyIds()) { - form1.addItemProperty(propertyId, item1.getItemProperty(propertyId)); - } - - // Method 2 - - Form form2 = new Form(); - Item item2 = createItem(); - form2.setItemDataSource(item2); - - // Layout - HorizontalLayout hl = new HorizontalLayout(); - hl.addComponent(form1); - hl.addComponent(form2); - - addComponent(hl); - } - - private Item createItem() { - return new BeanItem(new Person("John", "Doe", 38)); - } - - public class Person { - private String firstName; - private String lastName; - - public Person(String firstName, String lastName, int age) { - super(); - this.firstName = firstName; - this.lastName = lastName; - this.age = age; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - private int age; - } - - @Override - protected String getDescription() { - return "The two forms generated using different methods should have the same captions for all fields"; - } - - @Override - protected Integer getTicketNumber() { - return 3554; - } - -} +package com.vaadin.tests.components.form; + +import com.vaadin.data.Item; +import com.vaadin.data.util.BeanItem; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Form; +import com.vaadin.ui.HorizontalLayout; + +public class FormFieldCaptions extends TestBase { + + @Override + protected void setup() { + // Method 1 + Form form1 = new Form(); + Item item1 = createItem(); + for (Object propertyId : item1.getItemPropertyIds()) { + form1.addItemProperty(propertyId, item1.getItemProperty(propertyId)); + } + + // Method 2 + + Form form2 = new Form(); + Item item2 = createItem(); + form2.setItemDataSource(item2); + + // Layout + HorizontalLayout hl = new HorizontalLayout(); + hl.addComponent(form1); + hl.addComponent(form2); + + addComponent(hl); + } + + private Item createItem() { + return new BeanItem(new Person("John", "Doe", 38)); + } + + public class Person { + private String firstName; + private String lastName; + + public Person(String firstName, String lastName, int age) { + super(); + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + private int age; + } + + @Override + protected String getDescription() { + return "The two forms generated using different methods should have the same captions for all fields"; + } + + @Override + protected Integer getTicketNumber() { + return 3554; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/form/FormRenderingFlicker.java b/tests/testbench/com/vaadin/tests/components/form/FormRenderingFlicker.java index 5858366a63..ecf3215005 100644 --- a/tests/testbench/com/vaadin/tests/components/form/FormRenderingFlicker.java +++ b/tests/testbench/com/vaadin/tests/components/form/FormRenderingFlicker.java @@ -1,65 +1,65 @@ -package com.vaadin.tests.components.form; - -import com.vaadin.data.Item; -import com.vaadin.event.ItemClickEvent; -import com.vaadin.event.ItemClickEvent.ItemClickListener; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Form; -import com.vaadin.ui.Panel; -import com.vaadin.ui.Table; -import com.vaadin.ui.VerticalLayout; - -public class FormRenderingFlicker extends TestBase { - - private VerticalLayout tableLayout; - private Table table; - private Panel tablePanel; - private Form form; - - @Override - protected String getDescription() { - return "Clicking on an item in the table will replace the panel (surrounding the table) with a form. This should not cause the table rows to move downwards or cause any other visible flicker"; - } - - @Override - protected Integer getTicketNumber() { - return 2816; - } - - @Override - protected void setup() { - createTableLayout(); - form = new Form(); - - tablePanel = new Panel(); - tablePanel.setContent(tableLayout); - - addComponent(tablePanel); - } - - private void createTableLayout() { - tableLayout = new VerticalLayout(); - table = new Table(); - table.addContainerProperty("name", String.class, ""); - table.addContainerProperty("age", String.class, ""); - for (int i = 0; i < 100; i++) { - table.addItem(new Object[] { "Name " + i, String.valueOf(i) }, - new Object()); - } - table.setImmediate(true); - table.addListener(new ItemClickListener() { - - public void itemClick(ItemClickEvent event) { - clicked(event.getItem()); - } - - }); - - tableLayout.addComponent(table); - } - - protected void clicked(Item item) { - getLayout().replaceComponent(tablePanel, form); - } - -} +package com.vaadin.tests.components.form; + +import com.vaadin.data.Item; +import com.vaadin.event.ItemClickEvent; +import com.vaadin.event.ItemClickEvent.ItemClickListener; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Form; +import com.vaadin.ui.Panel; +import com.vaadin.ui.Table; +import com.vaadin.ui.VerticalLayout; + +public class FormRenderingFlicker extends TestBase { + + private VerticalLayout tableLayout; + private Table table; + private Panel tablePanel; + private Form form; + + @Override + protected String getDescription() { + return "Clicking on an item in the table will replace the panel (surrounding the table) with a form. This should not cause the table rows to move downwards or cause any other visible flicker"; + } + + @Override + protected Integer getTicketNumber() { + return 2816; + } + + @Override + protected void setup() { + createTableLayout(); + form = new Form(); + + tablePanel = new Panel(); + tablePanel.setContent(tableLayout); + + addComponent(tablePanel); + } + + private void createTableLayout() { + tableLayout = new VerticalLayout(); + table = new Table(); + table.addContainerProperty("name", String.class, ""); + table.addContainerProperty("age", String.class, ""); + for (int i = 0; i < 100; i++) { + table.addItem(new Object[] { "Name " + i, String.valueOf(i) }, + new Object()); + } + table.setImmediate(true); + table.addListener(new ItemClickListener() { + + public void itemClick(ItemClickEvent event) { + clicked(event.getItem()); + } + + }); + + tableLayout.addComponent(table); + } + + protected void clicked(Item item) { + getLayout().replaceComponent(tablePanel, form); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java b/tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java index 624d0746e9..a3baab921f 100644 --- a/tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java +++ b/tests/testbench/com/vaadin/tests/components/form/FormWithEnterShortCut.java @@ -1,47 +1,47 @@ -package com.vaadin.tests.components.form; - -import com.vaadin.event.ShortcutAction.KeyCode; -import com.vaadin.tests.components.TestBase; -import com.vaadin.tests.util.Log; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Field; -import com.vaadin.ui.Form; -import com.vaadin.ui.TextField; - -public class FormWithEnterShortCut extends TestBase { - private Log log = new Log(2); - - @Override - protected void setup() { - - final Form form = new Form(); - final Field tf = new TextField("Search"); - form.addField("searchfield", tf); - - Button button = new Button("Go"); - button.addListener(new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - log.log("search: " + tf.getValue()); - } - }); - button.setClickShortcut(KeyCode.ENTER); - button.setStyleName("primary"); - - form.getFooter().addComponent(button); - - addComponent(log); - addComponent(form); - - } - - @Override - protected String getDescription() { - return "Focusing a button and pressing enter (which is a shortcut for button click) should only produce one click event"; - } - - @Override - protected Integer getTicketNumber() { - return 5433; - } -} +package com.vaadin.tests.components.form; + +import com.vaadin.event.ShortcutAction.KeyCode; +import com.vaadin.tests.components.TestBase; +import com.vaadin.tests.util.Log; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Field; +import com.vaadin.ui.Form; +import com.vaadin.ui.TextField; + +public class FormWithEnterShortCut extends TestBase { + private Log log = new Log(2); + + @Override + protected void setup() { + + final Form form = new Form(); + final Field tf = new TextField("Search"); + form.addField("searchfield", tf); + + Button button = new Button("Go"); + button.addListener(new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + log.log("search: " + tf.getValue()); + } + }); + button.setClickShortcut(KeyCode.ENTER); + button.setStyleName("primary"); + + form.getFooter().addComponent(button); + + addComponent(log); + addComponent(form); + + } + + @Override + protected String getDescription() { + return "Focusing a button and pressing enter (which is a shortcut for button click) should only produce one click event"; + } + + @Override + protected Integer getTicketNumber() { + return 5433; + } +} diff --git a/tests/testbench/com/vaadin/tests/components/form/FormWithPropertyFormatterConnected.java b/tests/testbench/com/vaadin/tests/components/form/FormWithPropertyFormatterConnected.java index 116dd5bcc7..eba570c490 100644 --- a/tests/testbench/com/vaadin/tests/components/form/FormWithPropertyFormatterConnected.java +++ b/tests/testbench/com/vaadin/tests/components/form/FormWithPropertyFormatterConnected.java @@ -1,90 +1,90 @@ -package com.vaadin.tests.components.form; - -import com.vaadin.data.Item; -import com.vaadin.data.util.BeanItem; -import com.vaadin.data.util.PropertyFormatter; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.Button; -import com.vaadin.ui.Component; -import com.vaadin.ui.DefaultFieldFactory; -import com.vaadin.ui.Field; -import com.vaadin.ui.Form; -import com.vaadin.ui.FormFieldFactory; - -public class FormWithPropertyFormatterConnected extends TestBase { - @Override - protected void setup() { - Form form2 = new Form(); - form2.setFormFieldFactory(new FormFieldFactory() { - - public Field createField(Item item, Object propertyId, - Component uiContext) { - AbstractField f = (AbstractField) DefaultFieldFactory.get() - .createField(item, propertyId, uiContext); - if (propertyId.equals("age")) { - f.setPropertyDataSource(new PropertyFormatter() { - - @Override - public Object parse(String formattedValue) - throws Exception { - String str = formattedValue - .replaceAll("[^0-9.]", ""); - if (formattedValue.toLowerCase().contains("months")) { - return Double.parseDouble(str) / 12; - } - return Double.parseDouble(str); - } - - @Override - public String format(Object value) { - Double dValue = (Double) value; - if (dValue < 1) { - return ((int)(dValue * 12)) + " months"; - } - return dValue + " years"; - } - }); - f.setImmediate(true); - } - return f; - } - }); - form2.setItemDataSource(createItem()); - - addComponent(form2); - addComponent(new Button("B")); - } - - private Item createItem() { - return new BeanItem(new Person(0.5)); - } - - public class Person { - public Person(double age) { - super(); - this.age = age; - } - - public double getAge() { - return age; - } - - public void setAge(double age) { - this.age = age; - } - - private double age; - } - - @Override - protected String getDescription() { - return "It should be possible to inject PropertyFormatter and similar classses to fields in form. The test app hooks formatter that displays age in years or months and also accepts value in both (years by default, months if mentioned in the field)"; - } - - @Override - protected Integer getTicketNumber() { - return null; - } - -} +package com.vaadin.tests.components.form; + +import com.vaadin.data.Item; +import com.vaadin.data.util.BeanItem; +import com.vaadin.data.util.PropertyFormatter; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.Button; +import com.vaadin.ui.Component; +import com.vaadin.ui.DefaultFieldFactory; +import com.vaadin.ui.Field; +import com.vaadin.ui.Form; +import com.vaadin.ui.FormFieldFactory; + +public class FormWithPropertyFormatterConnected extends TestBase { + @Override + protected void setup() { + Form form2 = new Form(); + form2.setFormFieldFactory(new FormFieldFactory() { + + public Field createField(Item item, Object propertyId, + Component uiContext) { + AbstractField f = (AbstractField) DefaultFieldFactory.get() + .createField(item, propertyId, uiContext); + if (propertyId.equals("age")) { + f.setPropertyDataSource(new PropertyFormatter() { + + @Override + public Object parse(String formattedValue) + throws Exception { + String str = formattedValue + .replaceAll("[^0-9.]", ""); + if (formattedValue.toLowerCase().contains("months")) { + return Double.parseDouble(str) / 12; + } + return Double.parseDouble(str); + } + + @Override + public String format(Object value) { + Double dValue = (Double) value; + if (dValue < 1) { + return ((int)(dValue * 12)) + " months"; + } + return dValue + " years"; + } + }); + f.setImmediate(true); + } + return f; + } + }); + form2.setItemDataSource(createItem()); + + addComponent(form2); + addComponent(new Button("B")); + } + + private Item createItem() { + return new BeanItem(new Person(0.5)); + } + + public class Person { + public Person(double age) { + super(); + this.age = age; + } + + public double getAge() { + return age; + } + + public void setAge(double age) { + this.age = age; + } + + private double age; + } + + @Override + protected String getDescription() { + return "It should be possible to inject PropertyFormatter and similar classses to fields in form. The test app hooks formatter that displays age in years or months and also accepts value in both (years by default, months if mentioned in the field)"; + } + + @Override + protected Integer getTicketNumber() { + return null; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/formlayout/FormLayoutReplaceComponent.java b/tests/testbench/com/vaadin/tests/components/formlayout/FormLayoutReplaceComponent.java index e42d64201e..9427318a10 100644 --- a/tests/testbench/com/vaadin/tests/components/formlayout/FormLayoutReplaceComponent.java +++ b/tests/testbench/com/vaadin/tests/components/formlayout/FormLayoutReplaceComponent.java @@ -1,57 +1,57 @@ -package com.vaadin.tests.components.formlayout; -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.CheckBox; -import com.vaadin.ui.FormLayout; -import com.vaadin.ui.TextField; - -public class FormLayoutReplaceComponent extends TestBase { - - @Override - protected void setup() { - addComponent(new FL()); - - } - - public class FL extends FormLayout implements ClickListener { - - private TextField messages; - private CheckBox control; - - @SuppressWarnings("deprecation") - public FL() { - setCaption("Test"); - control = new CheckBox("Messages On/Off"); - control.addListener(this); - control.setImmediate(true); - addComponent(control); - - // The bug is in replaceComponent, triggered when VTextField is - // replaced by VTextArea so cannot replace this with TextArea. - messages = new TextField("Messages"); - messages.setRows(10); - messages.setColumns(40); - messages.setVisible(false); - messages.setEnabled(false); - addComponent(messages); - } - - public final void buttonClick(Button.ClickEvent e) { - if (e.getButton() == control) { - messages.setVisible(control.booleanValue()); - } - } - } - - @Override - protected String getDescription() { - return "Check or uncheck the CheckBox to show/hide the messages field inside the FormLayout."; - } - - @Override - protected Integer getTicketNumber() { - return 6308; - } - +package com.vaadin.tests.components.formlayout; +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.TextField; + +public class FormLayoutReplaceComponent extends TestBase { + + @Override + protected void setup() { + addComponent(new FL()); + + } + + public class FL extends FormLayout implements ClickListener { + + private TextField messages; + private CheckBox control; + + @SuppressWarnings("deprecation") + public FL() { + setCaption("Test"); + control = new CheckBox("Messages On/Off"); + control.addListener(this); + control.setImmediate(true); + addComponent(control); + + // The bug is in replaceComponent, triggered when VTextField is + // replaced by VTextArea so cannot replace this with TextArea. + messages = new TextField("Messages"); + messages.setRows(10); + messages.setColumns(40); + messages.setVisible(false); + messages.setEnabled(false); + addComponent(messages); + } + + public final void buttonClick(Button.ClickEvent e) { + if (e.getButton() == control) { + messages.setVisible(control.booleanValue()); + } + } + } + + @Override + protected String getDescription() { + return "Check or uncheck the CheckBox to show/hide the messages field inside the FormLayout."; + } + + @Override + protected Integer getTicketNumber() { + return 6308; + } + } \ No newline at end of file diff --git a/tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java b/tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java index 157772f8cd..c8eb1483b4 100644 --- a/tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java +++ b/tests/testbench/com/vaadin/tests/components/formlayout/TableInFormLayoutCausesScrolling.java @@ -1,45 +1,45 @@ -package com.vaadin.tests.components.formlayout; - -import com.vaadin.tests.components.AbstractTestCase; -import com.vaadin.ui.FormLayout; -import com.vaadin.ui.Table; -import com.vaadin.ui.TextField; -import com.vaadin.ui.Window; - -public class TableInFormLayoutCausesScrolling extends AbstractTestCase { - - @Override - public void init() { - // Window Initialization. - final Window window = new Window("Main Window"); - setMainWindow(window); - - // FormLayout creation - final FormLayout fl = new FormLayout(); - window.setContent(fl); - - // Add 20 TextField - for (int i = 20; i-- > 0;) { - fl.addComponent(new TextField()); - } - - // Add 1 selectable table with some items - final Table table = new Table(); - table.setSelectable(true); - table.addContainerProperty("item", String.class, ""); - for (int i = 50; i-- > 0;) { - table.addItem(new String[] { "item" + i }, i); - } - window.addComponent(table); - } - - @Override - protected String getDescription() { - return "Clicking in the Table should not cause the page to scroll"; - } - - @Override - protected Integer getTicketNumber() { - return 7309; - } +package com.vaadin.tests.components.formlayout; + +import com.vaadin.tests.components.AbstractTestCase; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.Table; +import com.vaadin.ui.TextField; +import com.vaadin.ui.Window; + +public class TableInFormLayoutCausesScrolling extends AbstractTestCase { + + @Override + public void init() { + // Window Initialization. + final Window window = new Window("Main Window"); + setMainWindow(window); + + // FormLayout creation + final FormLayout fl = new FormLayout(); + window.setContent(fl); + + // Add 20 TextField + for (int i = 20; i-- > 0;) { + fl.addComponent(new TextField()); + } + + // Add 1 selectable table with some items + final Table table = new Table(); + table.setSelectable(true); + table.addContainerProperty("item", String.class, ""); + for (int i = 50; i-- > 0;) { + table.addItem(new String[] { "item" + i }, i); + } + window.addComponent(table); + } + + @Override + protected String getDescription() { + return "Clicking in the Table should not cause the page to scroll"; + } + + @Override + protected Integer getTicketNumber() { + return 7309; + } } \ No newline at end of file diff --git a/tests/testbench/com/vaadin/tests/components/gridlayout/MoveComponentsFromGridLayoutToInnerLayout.java b/tests/testbench/com/vaadin/tests/components/gridlayout/MoveComponentsFromGridLayoutToInnerLayout.java index 08a37dcd9a..da0efe9464 100644 --- a/tests/testbench/com/vaadin/tests/components/gridlayout/MoveComponentsFromGridLayoutToInnerLayout.java +++ b/tests/testbench/com/vaadin/tests/components/gridlayout/MoveComponentsFromGridLayoutToInnerLayout.java @@ -1,58 +1,58 @@ -package com.vaadin.tests.components.gridlayout; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.ComponentContainer; -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.VerticalLayout; - -public class MoveComponentsFromGridLayoutToInnerLayout extends TestBase { - - protected Button testButton; - private GridLayout gl; - protected ComponentContainer vl; - - @Override - protected void setup() { - gl = new GridLayout(); - gl.setWidth("200px"); - gl.setHeight("200px"); - - testButton = new Button("Click to move to inner layout", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - vl.addComponent(testButton); - } - }); - - gl.addComponent(testButton); - - vl = new VerticalLayout(); - gl.addComponent(vl); - - addComponent(gl); - - Button b = new Button("Repaint inner layout", - new Button.ClickListener() { - - public void buttonClick(ClickEvent event) { - vl.requestRepaint(); - } - }); - - addComponent(b); - } - - @Override - protected String getDescription() { - return "Click the first button to move it from an outer layout to an inner. Then click the second button to repaint the inner layout."; - } - - @Override - protected Integer getTicketNumber() { - return 6060; - } - -} +package com.vaadin.tests.components.gridlayout; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.ComponentContainer; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.VerticalLayout; + +public class MoveComponentsFromGridLayoutToInnerLayout extends TestBase { + + protected Button testButton; + private GridLayout gl; + protected ComponentContainer vl; + + @Override + protected void setup() { + gl = new GridLayout(); + gl.setWidth("200px"); + gl.setHeight("200px"); + + testButton = new Button("Click to move to inner layout", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + vl.addComponent(testButton); + } + }); + + gl.addComponent(testButton); + + vl = new VerticalLayout(); + gl.addComponent(vl); + + addComponent(gl); + + Button b = new Button("Repaint inner layout", + new Button.ClickListener() { + + public void buttonClick(ClickEvent event) { + vl.requestRepaint(); + } + }); + + addComponent(b); + } + + @Override + protected String getDescription() { + return "Click the first button to move it from an outer layout to an inner. Then click the second button to repaint the inner layout."; + } + + @Override + protected Integer getTicketNumber() { + return 6060; + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/label/HundredPercentWideLabelResize.java b/tests/testbench/com/vaadin/tests/components/label/HundredPercentWideLabelResize.java index 1d2fb2a59c..a5bb291b67 100644 --- a/tests/testbench/com/vaadin/tests/components/label/HundredPercentWideLabelResize.java +++ b/tests/testbench/com/vaadin/tests/components/label/HundredPercentWideLabelResize.java @@ -1,42 +1,42 @@ -package com.vaadin.tests.components.label; - -import com.vaadin.tests.components.TestBase; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Label; - -public class HundredPercentWideLabelResize extends TestBase { - - @Override - protected String getDescription() { - return "100% wide label re-wrap should cause re-layout; forceLayout fixes this."; - } - - @Override - protected Integer getTicketNumber() { - return 2514; - } - - @Override - protected void setup() { - getLayout().setWidth("500px"); - Label text = new Label( - "This is a fairly long text that will wrap if the width of the layout is narrow enough. Directly below the text is a Button - however, when the layout changes size, the Label re-wraps w/o moving the button, causing eiter clipping or a big space."); - text.setWidth("100%"); - getLayout().addComponent(text); - - getLayout().addComponent( - new Button("toggle width", new Button.ClickListener() { - public void buttonClick(ClickEvent event) { - if (getLayout().getWidth() == 500) { - getLayout().setWidth("100px"); - } else { - getLayout().setWidth("500px"); - } - - } - - })); - } - -} +package com.vaadin.tests.components.label; + +import com.vaadin.tests.components.TestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Label; + +public class HundredPercentWideLabelResize extends TestBase { + + @Override + protected String getDescription() { + return "100% wide label re-wrap should cause re-layout; forceLayout fixes this."; + } + + @Override + protected Integer getTicketNumber() { + return 2514; + } + + @Override + protected void setup() { + getLayout().setWidth("500px"); + Label text = new Label( + "This is a fairly long text that will wrap if the width of the layout is narrow enough. Directly below the text is a Button - however, when the layout changes size, the Label re-wraps w/o moving the button, causing eiter clipping or a big space."); + text.setWidth("100%"); + getLayout().addComponent(text); + + getLayout().addComponent( + new Button("toggle width", new Button.ClickListener() { + public void buttonClick(ClickEvent event) { + if (getLayout().getWidth() == 500) { + getLayout().setWidth("100px"); + } else { + getLayout().setWidth("500px"); + } + + } + + })); + } + +} diff --git a/tests/testbench/com/vaadin/tests/components/label/LabelTest.java b/tests/testbench/com/vaadin/tests/components/label/LabelTest.java index 38ced67f18..5c71046404 100644 --- a/tests/testbench/com/vaadin/tests/components/label/LabelTest.java +++ b/tests/testbench/com/vaadin/tests/components/label/LabelTest.java @@ -1,100 +1,100 @@ -package com.vaadin.tests.components.label; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; - -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.tests.components.AbstractComponentTest; -import com.vaadin.ui.Label; - -public class LabelTest extends AbstractComponentTest