method2testcases
stringlengths 118
6.63k
|
---|
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @Override public boolean setParent(Object itemId, Object newParentId) throws UnsupportedOperationException { return false; } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testSetParent() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); HierarchicalTestItem testItem1 = new HierarchicalTestItem(23); HierarchicalTestItem testItem2 = new HierarchicalTestItem(42); assertThat(container.setParent(testItem1, testItem2), is(false)); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @Override public boolean areChildrenAllowed(Object itemId) { return hasChildren(itemId); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testAreChildrenAllowed_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.areChildrenAllowed(new TestItem(42)), is(false)); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @Override public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed) throws UnsupportedOperationException { return false; } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testSetChildrenAllowed() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); HierarchicalTestItem testItem = new HierarchicalTestItem(23); assertThat(container.setChildrenAllowed(testItem, true), is(false)); } |
### Question:
MemberAccessors { @SuppressWarnings("unchecked") public static <T> T getValue(Object object, Member fieldOrMethod) { if (fieldOrMethod instanceof Field) { return (T)getFieldValue(object, fieldOrMethod); } else if (fieldOrMethod instanceof Method) { Function<Object, Object> accessor = ACCESSOR_CACHE .computeIfAbsent(fieldOrMethod, key -> new MemberAccessors((Method)key).createFunction()); return (T)accessor.apply(object); } else { throw new IllegalArgumentException("Only field or method is supported, found " + fieldOrMethod.getClass().getCanonicalName() + " as type of " + getNameOf(fieldOrMethod)); } } private MemberAccessors(Method method); @Override String toString(); @SuppressWarnings("unchecked") static T getValue(Object object, Member fieldOrMethod); }### Answer:
@Test void testFieldAccess() throws NoSuchFieldException, SecurityException { TestObject testObject = new TestObject(); Member fieldOrMethod = TestObject.class.getDeclaredField("field"); String result = MemberAccessors.getValue(testObject, fieldOrMethod); assertThat(result, is(testObject.field)); }
@Test void testFieldAccess_NativeType() throws NoSuchFieldException, SecurityException { TestObject testObject = new TestObject(); Member fieldOrMethod = TestObject.class.getDeclaredField("intField"); int result = MemberAccessors.getValue(testObject, fieldOrMethod); assertThat(result, is(testObject.intField)); }
@Test void testGetValue() throws NoSuchMethodException, SecurityException { TestObject testObject = new TestObject(); Member fieldOrMethod = TestObject.class.getDeclaredMethod("getValue"); String result = MemberAccessors.getValue(testObject, fieldOrMethod); assertThat(result, is(testObject.getValue())); }
@Test void testGetValue_Void() throws NoSuchMethodException, SecurityException { TestObject testObject = new TestObject(); Member fieldOrMethod = TestObject.class.getDeclaredMethod("getVoid"); Assertions.assertThrows(IllegalArgumentException.class, () -> MemberAccessors.getValue(testObject, fieldOrMethod)); }
@Test void testGetValue_NativeReturnType() throws NoSuchMethodException, SecurityException { TestObject testObject = new TestObject(); Member fieldOrMethod = TestObject.class.getDeclaredMethod("getInt"); int result = MemberAccessors.getValue(testObject, fieldOrMethod); assertThat(result, is(testObject.getInt())); }
@Test void testGetValue_MethodThrowsException() throws NoSuchMethodException, SecurityException { TestObject testObject = new TestObject(); Member fieldOrMethod = TestObject.class.getDeclaredMethod("getThrowException"); assertThrows(RuntimeException.class, () -> MemberAccessors.getValue(testObject, fieldOrMethod)); }
@Test void testGetValue_UnsupportedMemberType() throws NoSuchMethodException, SecurityException { TestObject testObject = new TestObject(); Constructor<? extends TestObject> constructor = testObject.getClass().getDeclaredConstructor(); assertThrows(IllegalArgumentException.class, () -> MemberAccessors.getValue(testObject, constructor)); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @Override public boolean isRoot(Object itemId) { return roots.contains(itemId); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testIsRoot_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.isRoot(new TestItem(42)), is(false)); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @Override public boolean hasChildren(Object itemId) { return getHierarchicalItem(itemId) .map(HierarchicalRowPmo::hasChildRows) .orElse(false); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testHasChildren_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.hasChildren(new TestItem(42)), is(false)); } |
### Question:
PmoBasedSectionFactory { public static AbstractSection createAndBindSection(Object pmo, BindingContext bindingContext) { requireNonNull(pmo, "pmo must not be null"); requireNonNull(bindingContext, "bindingContext must not be null"); Class<? extends Object> pmoClass = pmo.getClass(); LinkkiComponentDefinition componentDefinition = ComponentAnnotationReader.findComponentDefinition(pmoClass) .orElse(SectionComponentDefiniton.DEFAULT); LinkkiLayoutDefinition layoutDefinition = LayoutAnnotationReader.findLayoutDefinition(pmoClass) .orElse(SectionLayoutDefinition.DEFAULT); ComponentWrapper componentWrapper = UiCreator .createComponent(pmo, bindingContext, componentDefinition, Optional.of(layoutDefinition)); return (AbstractSection)componentWrapper.getComponent(); } AbstractSection createSection(Object pmo, BindingContext bindingContext); BaseSection createBaseSection(Object pmo, BindingContext bindingContext); TableSection createTableSection(ContainerPmo<T> pmo, BindingContext bindingContext); static AbstractSection createAndBindSection(Object pmo, BindingContext bindingContext); }### Answer:
@Test public void testSetSectionId() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SCCPmoWithID(), bindingContext); assertThat(section.getId(), is("test-ID")); }
@Test public void testSetSectionDefaultId() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SCCPmoWithoutID(), bindingContext); assertThat(section.getId(), is("SCCPmoWithoutID")); }
@Test public void testSetComponentId() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SCCPmoWithID(), bindingContext); @SuppressWarnings("deprecation") GridLayout gridLayout = TestUiUtil .getContentGrid((org.linkki.core.vaadin.component.section.FormSection)section); Component textField = gridLayout.getComponent(1, 0); assertThat(textField.getId(), is("testProperty")); }
@SuppressWarnings("deprecation") @Test public void testSectionWithDefaultLayout_shouldCreateFormSection() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SCCPmoWithoutID(), bindingContext); assertThat(section, is(instanceOf(org.linkki.core.vaadin.component.section.FormSection.class))); }
@Test public void testSectionWithHorizontalLayout_shouldCreateHorizontalSection() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SectionWithHorizontalLayout(), bindingContext); assertThat(section, is(instanceOf(HorizontalSection.class))); }
@Test public void testSectionWithCustomLayout_shouldCreateCustomLayoutSection() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SectionWithCustomLayout(), bindingContext); assertThat(section, is(instanceOf(CustomLayoutSection.class))); }
@SuppressWarnings("deprecation") @Test public void testSectionWithoutAnnotation_usesDefaultValues() { AbstractSection section = PmoBasedSectionFactory.createAndBindSection(new SectionWithoutAnnotation(), bindingContext); assertThat(section, is(instanceOf(org.linkki.core.vaadin.component.section.FormSection.class))); assertThat(section.getId(), is(SectionWithoutAnnotation.class.getSimpleName())); assertThat(section.getCaption(), is(nullValue())); assertThat(((org.linkki.core.vaadin.component.section.FormSection)section).getNumberOfColumns(), is(1)); } |
### Question:
PmoBasedSectionFactory { public AbstractSection createSection(Object pmo, BindingContext bindingContext) { return createAndBindSection(pmo, bindingContext); } AbstractSection createSection(Object pmo, BindingContext bindingContext); BaseSection createBaseSection(Object pmo, BindingContext bindingContext); TableSection createTableSection(ContainerPmo<T> pmo, BindingContext bindingContext); static AbstractSection createAndBindSection(Object pmo, BindingContext bindingContext); }### Answer:
@Test public void testCreateSectionHeader() { SCCPmoWithID containerPmo = new SCCPmoWithID(); PmoBasedSectionFactory factory = new PmoBasedSectionFactory(); AbstractSection tableSection = factory.createSection(containerPmo, bindingContext); HorizontalLayout header = (HorizontalLayout)tableSection.getComponent(0); assertThat(header.getComponent(2), instanceOf(Button.class)); assertThat(header.getComponent(2).getCaption(), is("header button")); } |
### Question:
SectionCreationContext { @Deprecated public BaseSection createSection() { return (BaseSection)PmoBasedSectionFactory.createAndBindSection(pmo, bindingContext); } @Deprecated SectionCreationContext(Object pmo, BindingContext bindingContext); @Deprecated BaseSection createSection(); }### Answer:
@Test public void testSetSectionId() { BaseSection section = createContext(new SCCPmoWithID()).createSection(); assertThat(section.getId(), is("test-ID")); }
@Test public void testSetSectionDefaultId() { BaseSection section = createContext(new SCCPmoWithoutID()).createSection(); assertThat(section.getId(), is("SCCPmoWithoutID")); }
@Test public void testSetComponentId() { BaseSection section = createContext(new SCCPmoWithID()).createSection(); assertThat(section.getComponentCount(), is(2)); assertThat(section.getComponent(0).isVisible(), is(false)); GridLayout gridLayout = TestUiUtil.getContentGrid((FormSection)section); @NonNull Component textField = gridLayout.getComponent(1, 0); assertThat(textField.getId(), is("testProperty")); }
@Test public void testSectionWithDefaultLayout_shouldCreateFormLayout() { BaseSection section = createContext(new SCCPmoWithoutID()).createSection(); assertThat(section, is(instanceOf(FormSection.class))); }
@Test public void testSectionWithHorizontalLayout_shouldCreateHorizontalSection() { BaseSection section = createContext(new SectionWithHorizontalLayout()).createSection(); assertThat(section, is(instanceOf(HorizontalSection.class))); }
@Test public void testSectionWithCustomLayout_shouldCreateCustomLayoutSection() { BaseSection section = createContext(new SectionWithCustomLayout()).createSection(); assertThat(section, is(instanceOf(CustomLayoutSection.class))); }
@Test public void testSectionWithoutAnnotation_usesDefaultValues() { BaseSection section = createContext(new SectionWithoutAnnotation()).createSection(); assertThat(section, is(instanceOf(FormSection.class))); assertThat(section.getId(), is(SectionWithoutAnnotation.class.getSimpleName())); assertThat(section.getCaption(), is(nullValue())); assertThat(((FormSection)section).getNumberOfColumns(), is(1)); } |
### Question:
VaadinUiCreator { public static Component createComponent(Object pmo, BindingContext bindingContext) { ComponentWrapper wrapper = UiCreator.createComponent(pmo, bindingContext); return (Component)wrapper.getComponent(); } private VaadinUiCreator(); static Component createComponent(Object pmo, BindingContext bindingContext); }### Answer:
@SuppressWarnings("deprecation") @Test public void testCreateComponent() { TestPmo pmo = new TestPmo(); BindingContext bindingContext = new BindingContext(); Component component = VaadinUiCreator.createComponent(pmo, bindingContext); assertThat(component, instanceOf(org.linkki.core.vaadin.component.section.FormSection.class)); assertThat(bindingContext.getBindings(), hasSize(1)); Binding binding = bindingContext.getBindings().iterator().next(); assertThat(binding.getBoundComponent(), is(component)); assertThat(binding, is(instanceOf(BindingContext.class))); Collection<Binding> elementBindings = ((BindingContext)binding).getBindings(); assertThat(elementBindings.size(), is(1)); assertThat(elementBindings.iterator().next().getBoundComponent(), is(instanceOf(TextField.class))); } |
### Question:
Vaadin8 implements UiFrameworkExtension { @Override public Locale getLocale() { UI ui = UI.getCurrent(); if (ui != null) { Locale locale = ui.getLocale(); if (locale != null) { return locale; } } return Locale.GERMAN; } @Override Locale getLocale(); @Override ComponentWrapperFactory getComponentWrapperFactory(); @Override Stream<?> getChildComponents(Object uiComponent); }### Answer:
@Test public void testGetUiLocale() { assertThat(UI.getCurrent(), is(nullValue())); assertThat(UiFramework.getLocale(), is(Locale.GERMAN)); UI ui = MockUi.mockUi(); when(ui.getLocale()).thenReturn(Locale.ITALIAN); assertThat(UiFramework.getLocale(), is(Locale.ITALIAN)); } |
### Question:
Vaadin8 implements UiFrameworkExtension { @Override public Stream<?> getChildComponents(Object uiComponent) { if (uiComponent instanceof HasComponents) { return StreamUtil.stream((HasComponents)uiComponent); } return Stream.empty(); } @Override Locale getLocale(); @Override ComponentWrapperFactory getComponentWrapperFactory(); @Override Stream<?> getChildComponents(Object uiComponent); }### Answer:
@Test public void testGetChildComponents() { Component component1 = new Label("first label"); Component component2 = new Label("second label"); HasComponents componentWithChildren = new VerticalLayout(component1, component2); Component[] arr = { component1, component2 }; assertThat(UiFramework.get().getChildComponents(componentWithChildren).toArray(), is(arr)); } |
### Question:
ButtonBindingDefinition implements BindingDefinition { @Override public Button newComponent() { Button button = ComponentFactory.newButton(); if (buttonAnnotation.showIcon()) { button.setIcon(buttonAnnotation.icon()); } for (String styleName : buttonAnnotation.styleNames()) { button.addStyleName(styleName); } if (buttonAnnotation.shortcutKeyCode() != -1) { button.setClickShortcut(buttonAnnotation.shortcutKeyCode(), buttonAnnotation.shortcutModifierKeys()); } return button; } ButtonBindingDefinition(UIButton annotation); @Override Button newComponent(); @Override String label(); @Override EnabledType enabled(); @Override VisibleType visible(); @Override RequiredType required(); @Override String modelObject(); @Override String modelAttribute(); }### Answer:
@Test public void testNewComponent_DefaultAnnotations() { ButtonBindingDefinition adapter = new ButtonBindingDefinition(defaultAnnotation()); Component component = adapter.newComponent(); assertThat(component, is(instanceOf(Button.class))); Button button = (Button)component; assertThat(button.getIcon(), is(nullValue())); assertThat(button.getStyleName(), is("")); }
@Test public void testNewComponent_CustomAnnotationsAreUsed() { ButtonBindingDefinition adapter = new ButtonBindingDefinition(customAnnotation()); Component component = adapter.newComponent(); assertThat(component, is(instanceOf(Button.class))); Button button = (Button)component; assertThat(button.getIcon(), is(VaadinIcons.AMBULANCE)); assertThat(button.getStyleName(), is(ValoTheme.BUTTON_ICON_ONLY)); }
@SuppressWarnings("deprecation") @Test public void testNewComponent_UseShortcutKeyCode() { Button button = new ButtonBindingDefinition(shortcutButton()).newComponent(); assertThat(button, not(nullValue())); Button buttonSpy = spy(button); buttonSpy.setClickShortcut(KeyCode.ENTER); verify(buttonSpy).removeShortcutListener(clickShortcutCaptor.capture()); @NonNull ClickShortcut value = clickShortcutCaptor.getValue(); assertThat(value.getKeyCode(), is(KeyCode.E)); assertThat(value.getModifiers(), is(new int[] { ModifierKey.ALT })); }
@Test public void testNewComponent_CustomAnnotationsAreUsed() { ButtonBindingDefinition adapter = new ButtonBindingDefinition(customAnnotation()); Component component = adapter.newComponent(); assertThat(component, is(instanceOf(Button.class))); Button button = (Button)component; assertThat(button.getIcon(), is(FontAwesome.AMBULANCE)); assertThat(button.getStyleName(), is(ValoTheme.BUTTON_ICON_ONLY)); }
@Test public void testNewComponent_UseShortcutKeyCode() { Button button = new ButtonBindingDefinition(shortcutButton()).newComponent(); assertThat(button, not(nullValue())); Button buttonSpy = spy(button); buttonSpy.setClickShortcut(KeyCode.ENTER); verify(buttonSpy).removeShortcutListener(clickShortcutCaptor.capture()); @NonNull ClickShortcut value = clickShortcutCaptor.getValue(); assertThat(value.getKeyCode(), is(KeyCode.E)); assertThat(value.getModifiers(), is(new int[] { ModifierKey.ALT })); } |
### Question:
DateFieldBindingDefinition implements BindingDefinition { @Override public Component newComponent() { DateField dateField = ComponentFactory.newDateField(); if (StringUtils.isNotBlank(uiDateField.dateFormat())) { dateField.setDateFormat(uiDateField.dateFormat()); } else { Locale locale = UiFramework.getLocale(); dateField.setDateFormat(DateFormats.getPattern(locale)); } return dateField; } DateFieldBindingDefinition(UIDateField uiDateField); @Override Component newComponent(); @Override String label(); @Override EnabledType enabled(); @Override RequiredType required(); @Override VisibleType visible(); @Override String modelAttribute(); @Override String modelObject(); }### Answer:
@Test public void testNewComponent_DefaultDateFormatIsUsed() { assertThat(UiFramework.getLocale(), is(Locale.GERMAN)); DateFieldBindingDefinition adapter = new DateFieldBindingDefinition(defaultAnnotation()); Component component = adapter.newComponent(); assertThat(component, is(instanceOf(DateField.class))); DateField dateField = (DateField)component; assertThat(dateField.getDateFormat(), is(DateFormats.PATTERN_DE)); }
@Test public void testNewComponent_CustomDateFormatIsUsed() { DateFieldBindingDefinition adapter = new DateFieldBindingDefinition(customAnnotation()); Component component = adapter.newComponent(); assertThat(component, is(instanceOf(DateField.class))); DateField dateField = (DateField)component; assertThat(dateField.getDateFormat(), is(CUSTOM_DATE_FORMAT)); } |
### Question:
LabelComponentWrapper extends VaadinComponentWrapper { @Override public void postUpdate() { getLabelComponent().ifPresent(l -> { l.setEnabled(getComponent().isEnabled()); l.setVisible(getComponent().isVisible()); l.setDescription(getComponent().getDescription()); updateRequiredIndicator(l); }); } LabelComponentWrapper(Component component); LabelComponentWrapper(@CheckForNull Label label, Component component); @Override void postUpdate(); @Override void setLabel(String labelText); Optional<Label> getLabelComponent(); @Override String toString(); }### Answer:
@Test public void testPostUpdate_AddsRequiredIndicatorToLabelIfFieldIsRequired() { LabelComponentWrapper wrapper = new LabelComponentWrapper(label, field); field.setRequiredIndicatorVisible(true); wrapper.postUpdate(); assertThat(label.getStyleName(), containsString(LinkkiTheme.REQUIRED_LABEL_COMPONENT_WRAPPER)); }
@Test public void testPostUpdate_DoesNotAddRequiredIndicatorToLabelIfFieldIsNotRequired() { LabelComponentWrapper wrapper = new LabelComponentWrapper(label, field); field.setRequiredIndicatorVisible(false); wrapper.postUpdate(); assertThat(label.getStyleName(), not(containsString(LinkkiTheme.REQUIRED_LABEL_COMPONENT_WRAPPER))); }
@Test public void testPostUpdate_DoesNotAddRequiredIndicatorToLabelIfFieldIsReadOnly() { LabelComponentWrapper wrapper = new LabelComponentWrapper(label, field); field.setRequiredIndicatorVisible(true); field.setReadOnly(true); wrapper.postUpdate(); assertThat(label.getStyleName(), not(containsString(LinkkiTheme.REQUIRED_LABEL_COMPONENT_WRAPPER))); } |
### Question:
CaptionComponentWrapper extends VaadinComponentWrapper { @Override public void setLabel(String labelText) { getComponent().setCaption(StringUtils.isEmpty(labelText) ? null : labelText); } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setLabel(String labelText); @Override String toString(); }### Answer:
@Test public void testSetLabel() { Component component = mock(Component.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); wrapper.setLabel("testLabel"); verify(component).setCaption("testLabel"); }
@Test public void testSetLabel_EmptyString() { Component component = new TextField(); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); wrapper.setLabel(""); assertThat(component.getCaption(), is(nullValue())); } |
### Question:
FormattedDecimalFieldToStringConverter extends FormattedNumberToStringConverter<Decimal> { @Override protected Decimal convertToModel(Number value) { return Decimal.valueOf(value.doubleValue()); } FormattedDecimalFieldToStringConverter(String format); @Override Result<Decimal> convertToModel(@CheckForNull String value, ValueContext context); @Override String convertToPresentation(@CheckForNull Decimal value, ValueContext context); }### Answer:
@Test public void testConvertToModelWithoutSeparators() { assertThat(converter.convertToModel("17385,89", new ValueContext(Locale.GERMAN)) .getOrThrow(s -> new AssertionError(s)), is(Decimal.valueOf(17385.89))); }
@Test public void testConvertToModelWithNull() { assertThat(converter.convertToModel(null, new ValueContext()) .getOrThrow(s -> new AssertionError(s)), is(Decimal.NULL)); } |
### Question:
FormattedDecimalFieldToStringConverter extends FormattedNumberToStringConverter<Decimal> { @Override public String convertToPresentation(@CheckForNull Decimal value, ValueContext context) { if (value == null || value.isNull()) { return ""; } else { return super.convertToPresentation(value, context); } } FormattedDecimalFieldToStringConverter(String format); @Override Result<Decimal> convertToModel(@CheckForNull String value, ValueContext context); @Override String convertToPresentation(@CheckForNull Decimal value, ValueContext context); }### Answer:
@Test public void testConvertToPresentationWithNull() { assertThat(converter.convertToPresentation(null, new ValueContext()), is("")); } |
### Question:
IdAndNameCaptionProvider implements ItemCaptionProvider<Object> { @Override public String getCaption(Object o) { return getName(o) + " [" + getId(o) + "]"; } @Override String getCaption(Object o); }### Answer:
@Test public void testIdAndNameCaptionProvider_AnonymousClass() { ItemCaptionProvider<Object> provider = new IdAndNameCaptionProvider(); assertThat(provider.getCaption(TestEnum.VALUE1), is("name1 [id1]")); }
@Test public void testIdAndNameCaptionProvider_AllMethods() { ItemCaptionProvider<Object> provider = new IdAndNameCaptionProvider(); assertThat(provider.getCaption(AllMethodsEnum.VALUE), is("getName(Locale) [id]")); }
@Test public void testIdAndNameCaptionProvider_MissingGetIdMethod() { ItemCaptionProvider<Object> provider = new IdAndNameCaptionProvider(); Assertions.assertThrows(IllegalStateException.class, () -> { provider.getCaption(UnnamedEnum.VALUE); }); } |
### Question:
ApplicationLayout extends VerticalLayout implements ViewDisplay { @Override public void showView(View view) { if (view instanceof Component) { setMainArea((Component)view); } else { throw new IllegalArgumentException( "View is not a component: " + view); } } ApplicationLayout(ApplicationHeader header, @CheckForNull ApplicationFooter footer); @Override void showView(View view); }### Answer:
@Test public void testShowView() { setUpApplicationLayout(); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(instanceOf(EmptyView.class))); View view = mock(View.class, withSettings().extraInterfaces(Component.class)); applicationLayout.showView(view); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(view)); View view2 = mock(View.class, withSettings().extraInterfaces(Component.class)); applicationLayout.showView(view2); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(view2)); }
@Test public void testShowView_NoFooter() { applicationLayout = new ApplicationLayout(header, null); assertThat(applicationLayout.getComponentCount(), is(2)); assertThat(applicationLayout.getComponent(1), is(instanceOf(EmptyView.class))); View view = mock(View.class, withSettings().extraInterfaces(Component.class)); applicationLayout.showView(view); assertThat(applicationLayout.getComponentCount(), is(2)); assertThat(applicationLayout.getComponent(1), is(view)); View view2 = mock(View.class, withSettings().extraInterfaces(Component.class)); applicationLayout.showView(view2); assertThat(applicationLayout.getComponentCount(), is(2)); assertThat(applicationLayout.getComponent(1), is(view2)); } |
### Question:
LinkkiUi extends UI { @Override protected void init(VaadinRequest request) { requireNonNull(applicationConfig, "configure must be called before any other methods to set applicationConfig and applicationLayout"); setErrorHandler(createErrorHandler()); VaadinSession vaadinSession = VaadinSession.getCurrent(); if (vaadinSession != null) { vaadinSession.setConverterFactory(applicationConfig.getConverterFactory()); vaadinSession.setErrorHandler(getErrorHandler()); } Page.getCurrent().setTitle(getPageTitle()); setContent(applicationLayout); } @SuppressFBWarnings(value = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "applicationConfig/Layout will be non-null once configure was called") protected LinkkiUi(); @SuppressFBWarnings(value = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "applicationConfig/Layout will be non-null once configure was called") LinkkiUi(ApplicationConfig applicationConfig); @Override ApplicationNavigator getNavigator(); ApplicationConfig getApplicationConfig(); ApplicationLayout getApplicationLayout(); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "when called from the constructor before configure") @Override void setContent(@CheckForNull Component content); static LinkkiUi getCurrent(); static ApplicationConfig getCurrentApplicationConfig(); static ApplicationNavigator getCurrentApplicationNavigator(); static ApplicationLayout getCurrentApplicationLayout(); }### Answer:
@Test public void testInit() { initUi(); assertThat(UI.getCurrent().getContent(), is(linkkiUi.getApplicationLayout())); } |
### Question:
SidebarSheet { protected void unselect() { getButton().removeStyleName(LinkkiApplicationTheme.SIDEBAR_SELECTED); getContent().setVisible(false); } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); Button getButton(); Component getContent(); String getName(); @Override String toString(); }### Answer:
@Test public void testUnselect_checkVisibilitySetToFalse() { HorizontalLayout content = new HorizontalLayout(); SidebarSheet sheet = createSideBarSheet(content); sheet.unselect(); assertThat(content.isVisible(), is(false)); } |
### Question:
SidebarSheet { protected void select() { getContent().setVisible(true); getButton().addStyleName(LinkkiApplicationTheme.SIDEBAR_SELECTED); uiUpdateObserver.ifPresent(UiUpdateObserver::uiUpdated); } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); Button getButton(); Component getContent(); String getName(); @Override String toString(); }### Answer:
@Test public void testSelect_checkVisibilitySetToTrue() { HorizontalLayout content = new HorizontalLayout(); SidebarSheet sheet = createSideBarSheet(content); sheet.select(); assertThat(content.isVisible(), is(true)); }
@Test public void testSelect_CheckObserver() { HorizontalLayout content = new HorizontalLayout(); SidebarSheet sidebarSheet = new SidebarSheet(FontAwesome.STAR_HALF_FULL, "Test SidebarSheet", content, () -> triggered = true); sidebarSheet.select(); assertThat(triggered, is(true)); } |
### Question:
SidebarSheet { @Override public String toString() { return name; } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); Button getButton(); Component getContent(); String getName(); @Override String toString(); }### Answer:
@Test public void testToString() { SidebarSheet sheet = new SidebarSheet(FontAwesome.ADJUST, "Foo", new TextField()); assertThat(sheet.toString(), is("Foo")); } |
### Question:
SidebarLayout extends CssLayout { public void select(SidebarSheet sheet) { if (!sidebarSheets.contains(sheet)) { throw new IllegalArgumentException("The sheet " + sheet + " is not part of this SidebarLayout"); } if (selected == sheet) { return; } Component content = sheet.getContent(); if (content.getParent() == null) { contentArea.addComponent(content); } else if (content.getParent() != contentArea) { throw new IllegalStateException("Content of the selected sidebar sheet already has a parent!"); } if (selected != null) { selected.unselect(); } this.selected = sheet; sheet.select(); } SidebarLayout(); void addSheets(Stream<SidebarSheet> sheets); void addSheets(Iterable<SidebarSheet> sheets); void addSheets(@NonNull SidebarSheet... sheets); void addSheet(SidebarSheet sheet); void select(SidebarSheet sheet); SidebarSheet getSelected(); List<SidebarSheet> getSidebarSheets(); }### Answer:
@Test public void testSelect_NotRegistered() { SidebarLayout sidebarLayout = new SidebarLayout(); SidebarSheet sheet1 = new SidebarSheet(ANY_ICON, ANY_STRING, createNewContent()); Assertions.assertThrows(IllegalArgumentException.class, () -> { sidebarLayout.select(sheet1); }); } |
### Question:
OkCancelDialog extends Window { @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override public void setContent(@CheckForNull Component content) { if (mainArea == null) { super.setContent(content); } else { mainArea.removeAllComponents(); mainArea.addComponent(content); } } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); static Builder builder(String caption); }### Answer:
@Test public void testSetContent() { OkCancelDialog dialog = OkCancelDialog.builder("").build(); assertThat(DialogTestUtil.getContents(dialog).size(), is(0)); dialog.setContent(new Label()); assertThat(DialogTestUtil.getContents(dialog), hasSize(1)); assertThat(dialog, is(showingEnabledOkButton())); } |
### Question:
OkCancelDialog extends Window { protected void ok() { okHandler.apply(); } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); static Builder builder(String caption); }### Answer:
@Test public void testOk() { Handler okHandler = mock(Handler.class); Handler cancelHandler = mock(Handler.class); OkCancelDialog dialog = OkCancelDialog.builder("") .okHandler(okHandler) .cancelHandler(cancelHandler) .build(); dialog.open(); assertThat(UI.getCurrent().getWindows(), hasSize(1)); DialogTestUtil.clickOkButton(dialog); verify(okHandler).apply(); verify(cancelHandler, never()).apply(); assertThat(UI.getCurrent().getWindows(), hasSize(0)); } |
### Question:
OkCancelDialog extends Window { public static Builder builder(String caption) { return new Builder(caption); } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); static Builder builder(String caption); }### Answer:
@Test public void testContent() { Label content1 = new Label("1"); Label content2 = new Label("2"); OkCancelDialog dialog = OkCancelDialog.builder("caption") .content(content1, content2) .build(); assertThat(DialogTestUtil.getContents(dialog), contains(content1, content2)); }
@Test public void testButtonOption() { OkCancelDialog dialog = OkCancelDialog.builder("").buttonOption(ButtonOption.OK_ONLY).build(); assertThat(DialogTestUtil.getButtons(dialog), hasSize(1)); } |
### Question:
MetaAnnotation { public boolean isPresentOn(@CheckForNull Annotation annotation) { if (annotation != null) { return repeatable ? annotation.annotationType().getAnnotationsByType(metaAnnotationClass).length > 0 : annotation.annotationType().isAnnotationPresent(metaAnnotationClass); } else { return false; } } private MetaAnnotation(Class<META> metaAnnotationClass); static MetaAnnotation<META> of(Class<META> metaAnnotationClass); boolean isRepeatable(); boolean isPresentOnAnyAnnotationOn(AnnotatedElement annotatedElement); boolean isPresentOn(@CheckForNull Annotation annotation); Optional<META> findOn(Annotation annotation); Stream<META> findAllOn(Annotation annotation); Stream<Annotation> findAnnotatedAnnotationsOn(AnnotatedElement annotatedElement); BinaryOperator<A> onlyOneOn(AnnotatedElement annotatedElement); Supplier<? extends IllegalArgumentException> missingAnnotation(Annotation annotation,
AnnotatedElement annotatedElement,
String checkerMethod); }### Answer:
@Test public void testIsPresentOn() { assertThat(MetaAnnotation.of(MetaMarkerAnnotation.class).isPresentOn(annotatedAnnotation)); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public void setId(String id) { component.setId(id); } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testSetId() { Component component = mock(Component.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); verify(component).setId("testID"); wrapper.setId("anotherId"); verify(component).setId("anotherId"); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public void setLabel(String labelText) { component.setCaption(labelText); } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testSetLabel() { Component component = mock(Component.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); wrapper.setLabel("testLabel"); verify(component).setCaption("testLabel"); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public void setEnabled(boolean enabled) { component.setEnabled(enabled); } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testSetEnabled() { Component component = mock(Component.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); wrapper.setEnabled(true); verify(component).setEnabled(true); wrapper.setEnabled(false); verify(component).setEnabled(false); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public void setVisible(boolean visible) { component.setVisible(visible); } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testSetVisible() { Component component = mock(Component.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); wrapper.setVisible(true); verify(component).setVisible(true); wrapper.setVisible(false); verify(component).setVisible(false); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public void setTooltip(String text) { if (component instanceof AbstractComponent) { ((AbstractComponent)component).setDescription(text); } } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testSetTooltip() { AbstractComponent component = mock(AbstractComponent.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); wrapper.setTooltip("testTip"); verify(component).setDescription("testTip"); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public Component getComponent() { return component; } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testGetComponent() { Component component = mock(Component.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); assertThat(wrapper.getComponent(), is(sameInstance(component))); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public void setValidationMessages(MessageList messagesForProperty) { if (component instanceof AbstractComponent) { AbstractComponent field = (AbstractComponent)component; field.setComponentError(getErrorHandler(messagesForProperty)); } } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testSetValidationMessages() { AbstractComponent component = mock(AbstractComponent.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); ArgumentCaptor<ErrorMessage> errorMessageCaptor = ArgumentCaptor.forClass(ErrorMessage.class); MessageList messages = new MessageList(Message.newError("e", "testError"), Message.newWarning("w", "testWarning")); wrapper.setValidationMessages(messages); verify(component).setComponentError(errorMessageCaptor.capture()); @NonNull ErrorMessage errorMessage = errorMessageCaptor.getValue(); assertThat(errorMessage.getErrorLevel(), is(ErrorLevel.ERROR)); assertThat(errorMessage.getFormattedHtmlMessage(), containsString("testError")); assertThat(errorMessage.getFormattedHtmlMessage(), containsString("testWarning")); }
@Test public void testSetValidationMessages_Empty() { AbstractComponent component = mock(AbstractComponent.class); CaptionComponentWrapper wrapper = new CaptionComponentWrapper("testID", component, WrapperType.FIELD); MessageList messages = new MessageList(); wrapper.setValidationMessages(messages); verify(component).setComponentError(null); } |
### Question:
CaptionComponentWrapper implements ComponentWrapper { @Override public WrapperType getType() { return wrapperType; } CaptionComponentWrapper(Component component, WrapperType wrapperType); CaptionComponentWrapper(String id, Component component, WrapperType wrapperType); @Override void setId(String id); @Override void setLabel(String labelText); @Override void setEnabled(boolean enabled); @Override void setVisible(boolean visible); @Override void setTooltip(String text); @Override Component getComponent(); @Override void setValidationMessages(MessageList messagesForProperty); @Override WrapperType getType(); @Override void registerBinding(Binding binding); @Override String toString(); }### Answer:
@Test public void testGetType() { Component component = mock(Component.class); assertThat(new CaptionComponentWrapper("testID", component, WrapperType.FIELD).getType(), is(WrapperType.FIELD)); assertThat(new CaptionComponentWrapper("testID", component, WrapperType.LAYOUT).getType(), is(WrapperType.LAYOUT)); } |
### Question:
MetaAnnotation { public Optional<META> findOn(Annotation annotation) { return repeatable ? findAllOn(annotation).reduce((a1, a2) -> { throw new IllegalArgumentException(annotation.annotationType() + " has multiple @" + metaAnnotationClass.getSimpleName() + " annotations. Please use " + MetaAnnotation.class.getSimpleName() + "#findAllOn(Annotation) for repeatable annotations."); }) : Optional.ofNullable(annotation.annotationType().getAnnotation(metaAnnotationClass)); } private MetaAnnotation(Class<META> metaAnnotationClass); static MetaAnnotation<META> of(Class<META> metaAnnotationClass); boolean isRepeatable(); boolean isPresentOnAnyAnnotationOn(AnnotatedElement annotatedElement); boolean isPresentOn(@CheckForNull Annotation annotation); Optional<META> findOn(Annotation annotation); Stream<META> findAllOn(Annotation annotation); Stream<Annotation> findAnnotatedAnnotationsOn(AnnotatedElement annotatedElement); BinaryOperator<A> onlyOneOn(AnnotatedElement annotatedElement); Supplier<? extends IllegalArgumentException> missingAnnotation(Annotation annotation,
AnnotatedElement annotatedElement,
String checkerMethod); }### Answer:
@Test public void testFindOn() { Optional<MetaMarkerAnnotation> metaMarkerAnnotation = MetaAnnotation.of(MetaMarkerAnnotation.class) .findOn(annotatedAnnotation); assertThat(metaMarkerAnnotation.isPresent()); assertThat(metaMarkerAnnotation.get().value(), is("foo")); } |
### Question:
LinkkiConverterFactory extends DefaultConverterFactory { @Override @CheckForNull protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter( @CheckForNull Class<PRESENTATION> presentationType, @CheckForNull Class<MODEL> modelType) { @SuppressWarnings("unchecked") @CheckForNull Converter<PRESENTATION, MODEL> converter = converterFinder.get().stream() .filter(Converter.class::isInstance) .map(Converter.class::cast) .filter(c -> c.getPresentationType().isAssignableFrom(presentationType) && c.getModelType().isAssignableFrom(modelType)) .findFirst() .orElseGet(() -> super.findConverter(presentationType, modelType)); return converter; } LinkkiConverterFactory(); LinkkiConverterFactory(Supplier<Sequence<Converter<?, ?>>> converterFinder); static final Sequence<Converter<?, ?>> DEFAULT_JAVA_8_DATE_CONVERTERS; }### Answer:
@Test public void testFindConverter_noneRegistered() { LinkkiConverterFactory linkkiConverterFactory = new LinkkiConverterFactory(() -> Sequence.empty()); assertThat(linkkiConverterFactory.findConverter(String.class, Date.class), is(instanceOf(StringToDateConverter.class))); assertThat(linkkiConverterFactory.findConverter(String.class, java.time.LocalDate.class), is(nullValue())); assertThat(linkkiConverterFactory.findConverter(String.class, org.joda.time.LocalDate.class), is(nullValue())); }
@Test public void testFindConverter_allRegistered() { LinkkiConverterFactory linkkiConverterFactory = new LinkkiConverterFactory( () -> Sequence.of(new JodaLocalDateToStringConverter(), new JodaLocalDateTimeToStringConverter(), new JodaLocalDateToDateConverter(), new LocalDateToStringConverter(), new LocalDateTimeToStringConverter(), new LocalDateToDateConverter())); assertThat(linkkiConverterFactory.findConverter(String.class, Date.class), is(instanceOf(StringToDateConverter.class))); assertThat(linkkiConverterFactory.findConverter(String.class, java.time.LocalDate.class), is(instanceOf(LocalDateToStringConverter.class))); assertThat(linkkiConverterFactory.findConverter(String.class, org.joda.time.LocalDate.class), is(instanceOf(JodaLocalDateToStringConverter.class))); assertThat(linkkiConverterFactory.findConverter(String.class, java.time.LocalDateTime.class), is(instanceOf(LocalDateTimeToStringConverter.class))); assertThat(linkkiConverterFactory.findConverter(String.class, org.joda.time.LocalDateTime.class), is(instanceOf(JodaLocalDateTimeToStringConverter.class))); assertThat(linkkiConverterFactory.findConverter(Date.class, java.time.LocalDate.class), is(instanceOf(LocalDateToDateConverter.class))); assertThat(linkkiConverterFactory.findConverter(Date.class, org.joda.time.LocalDate.class), is(instanceOf(JodaLocalDateToDateConverter.class))); }
@Test public void testFindConverter_overrideDefault() { LinkkiConverterFactory linkkiConverterFactory = new LinkkiConverterFactory( () -> Sequence.of(new MyStringToDateConverter())); assertThat(linkkiConverterFactory.findConverter(String.class, Date.class), is(instanceOf(MyStringToDateConverter.class))); } |
### Question:
JodaLocalDateToStringConverter implements Converter<String, LocalDate> { @CheckForNull @Override public LocalDate convertToModel(@CheckForNull String value, @CheckForNull Class<? extends LocalDate> targetType, @CheckForNull Locale locale) throws Converter.ConversionException { throw new UnsupportedOperationException(getClass().getName() + " only supports convertToPresentation"); } @CheckForNull @Override LocalDate convertToModel(@CheckForNull String value,
@CheckForNull Class<? extends LocalDate> targetType,
@CheckForNull Locale locale); @CheckForNull @Override String convertToPresentation(@CheckForNull LocalDate value,
@CheckForNull Class<? extends String> targetType,
@CheckForNull Locale locale); static DateTimeFormatter getFormat(Locale locale); @Override Class<LocalDate> getModelType(); @Override Class<String> getPresentationType(); }### Answer:
@Test public void testConvertToModel() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new JodaLocalDateToStringConverter().convertToModel(null, null, null); }); } |
### Question:
JodaLocalDateToStringConverter implements Converter<String, LocalDate> { @CheckForNull @Override public String convertToPresentation(@CheckForNull LocalDate value, @CheckForNull Class<? extends String> targetType, @CheckForNull Locale locale) throws Converter.ConversionException { if (value == null) { return ""; } return getFormat(getNullsafeLocale(locale)).print(value); } @CheckForNull @Override LocalDate convertToModel(@CheckForNull String value,
@CheckForNull Class<? extends LocalDate> targetType,
@CheckForNull Locale locale); @CheckForNull @Override String convertToPresentation(@CheckForNull LocalDate value,
@CheckForNull Class<? extends String> targetType,
@CheckForNull Locale locale); static DateTimeFormatter getFormat(Locale locale); @Override Class<LocalDate> getModelType(); @Override Class<String> getPresentationType(); }### Answer:
@Test public void testConvertToPresentation_null_shouldReturnEmptyString() { String presentation = new JodaLocalDateToStringConverter().convertToPresentation(null, String.class, null); assertNotNull(presentation); assertThat(presentation, is("")); }
@Test public void testConvertToPresentation() { LocalDate date = LocalDate.now(); String presentation = new JodaLocalDateToStringConverter().convertToPresentation(date, null, Locale.GERMANY); assertNotNull(presentation); assertThat(presentation, is(date.toString(DateFormats.PATTERN_DE))); } |
### Question:
JodaLocalDateTimeToStringConverter implements Converter<String, LocalDateTime> { @CheckForNull @Override public LocalDateTime convertToModel(@CheckForNull String value, @CheckForNull Class<? extends LocalDateTime> targetType, @CheckForNull Locale locale) throws ConversionException { throw new UnsupportedOperationException(getClass().getName() + " only supports convertToPresentation"); } @CheckForNull @Override LocalDateTime convertToModel(@CheckForNull String value,
@CheckForNull Class<? extends LocalDateTime> targetType,
@CheckForNull Locale locale); @CheckForNull @Override String convertToPresentation(@CheckForNull LocalDateTime value,
@CheckForNull Class<? extends String> targetType,
@CheckForNull Locale locale); @Override Class<LocalDateTime> getModelType(); @Override Class<String> getPresentationType(); }### Answer:
@Test public void testConvertToModel() { Assertions.assertThrows(UnsupportedOperationException.class, () -> { new JodaLocalDateTimeToStringConverter().convertToModel(null, null, null); }); } |
### Question:
JodaLocalDateTimeToStringConverter implements Converter<String, LocalDateTime> { @CheckForNull @Override public String convertToPresentation(@CheckForNull LocalDateTime value, @CheckForNull Class<? extends String> targetType, @CheckForNull Locale locale) throws ConversionException { if (value == null) { return ""; } String dateString = localDateConverter.convertToPresentation(value.toLocalDate(), targetType, locale); String timeString = DateTimeFormat.shortTime() .withLocale(JodaLocalDateToStringConverter.getNullsafeLocale(locale)) .print(value); return dateString + '\t' + timeString; } @CheckForNull @Override LocalDateTime convertToModel(@CheckForNull String value,
@CheckForNull Class<? extends LocalDateTime> targetType,
@CheckForNull Locale locale); @CheckForNull @Override String convertToPresentation(@CheckForNull LocalDateTime value,
@CheckForNull Class<? extends String> targetType,
@CheckForNull Locale locale); @Override Class<LocalDateTime> getModelType(); @Override Class<String> getPresentationType(); }### Answer:
@Test public void testConvertToPresentation_null_shouldReturnEmptyString() { String presentation = new JodaLocalDateTimeToStringConverter().convertToPresentation(null, String.class, null); assertNotNull(presentation); assertThat(presentation, is("")); }
@Test public void testConvertToPresentation_locale_de() { LocalDateTime dateTime = new LocalDateTime(2016, 12, 29, 15, 30, 0, 555); String presentation = new JodaLocalDateTimeToStringConverter().convertToPresentation(dateTime, null, Locale.GERMANY); assertNotNull(presentation); assertThat(presentation, is("29.12.2016\t15:30")); }
@Test public void testConvertToPresentation_locale_() { LocalDateTime dateTime = new LocalDateTime(2016, 12, 29, 15, 30, 0, 555); String presentation = new JodaLocalDateTimeToStringConverter().convertToPresentation(dateTime, null, Locale.US); assertNotNull(presentation); assertThat(presentation, is("12/29/16\t3:30 PM")); } |
### Question:
MetaAnnotation { public Stream<META> findAllOn(Annotation annotation) { return Arrays.stream(annotation.annotationType().getAnnotationsByType(metaAnnotationClass)); } private MetaAnnotation(Class<META> metaAnnotationClass); static MetaAnnotation<META> of(Class<META> metaAnnotationClass); boolean isRepeatable(); boolean isPresentOnAnyAnnotationOn(AnnotatedElement annotatedElement); boolean isPresentOn(@CheckForNull Annotation annotation); Optional<META> findOn(Annotation annotation); Stream<META> findAllOn(Annotation annotation); Stream<Annotation> findAnnotatedAnnotationsOn(AnnotatedElement annotatedElement); BinaryOperator<A> onlyOneOn(AnnotatedElement annotatedElement); Supplier<? extends IllegalArgumentException> missingAnnotation(Annotation annotation,
AnnotatedElement annotatedElement,
String checkerMethod); }### Answer:
@Test public void testFindAllOn() { List<MetaMarkerAnnotation> metaMarkerAnnotation = MetaAnnotation.of(MetaMarkerAnnotation.class) .findAllOn(annotatedAnnotation).collect(Collectors.toList()); assertThat(metaMarkerAnnotation, hasSize(1)); assertThat(metaMarkerAnnotation.get(0).value(), is("foo")); } |
### Question:
TableCreator implements ColumnBasedComponentCreator { @Override public ComponentWrapper createComponent(ContainerPmo<?> containerPmo) { Table table = containerPmo.isHierarchical() ? new TreeTable() : new Table(); table.addStyleName(LinkkiTheme.TABLE); table.setHeightUndefined(); table.setWidth("100%"); table.setSortEnabled(false); return new TableComponentWrapper<>(containerPmo.getClass().getSimpleName(), table); } @Override ComponentWrapper createComponent(ContainerPmo<?> containerPmo); @Override void initColumn(ContainerPmo<?> containerPmo,
ComponentWrapper tableWrapper,
BindingContext bindingContext,
PropertyElementDescriptors elementDesc); }### Answer:
@Test public void testCreateComponent_PmoClassIsUsedAsId() { TableCreator creator = new TableCreator(); Table table = (Table)creator.createComponent(new TestTablePmo()).getComponent(); assertThat(table.getId(), is("TestTablePmo")); } |
### Question:
PmoBasedTableFactory { public Table createTable() { return (Table)CONTAINER_COMPONENT_FACTORY.createContainerComponent(containerPmo, bindingContext); } PmoBasedTableFactory(ContainerPmo<?> containerPmo, BindingContext bindingContext); Table createTable(); }### Answer:
@Test public void testPageLength() { TestTablePmo tablePmo = new TestTablePmo(15); Table table = new PmoBasedTableFactory(tablePmo, bindingContext).createTable(); ItemSetChangeListener itemSetChangedListener = addItemSetChangeListener(bindingContext); assertThat(table.getPageLength(), is(15)); tablePmo.setPageLength(25); bindingContext.modelChanged(); assertThat(table.getPageLength(), is(25)); verifyNoInteractions(itemSetChangedListener); }
@Test public void testItems_AfterConstruction() { TestRowPmo rowPmo1 = new TestRowPmo(); TestRowPmo rowPmo2 = new TestRowPmo(); TestTablePmo tablePmo = new TestTablePmo(rowPmo1, rowPmo2); Table table = new PmoBasedTableFactory(tablePmo, bindingContext).createTable(); assertThat(tablePmo.getItems(), contains(rowPmo1, rowPmo2)); assertThat(table.getItemIds(), contains(rowPmo1, rowPmo2)); }
@Test public void testItems_UponUpdate_AddItems() { TestTablePmo tablePmo = new TestTablePmo(); Table table = new PmoBasedTableFactory(tablePmo, bindingContext).createTable(); ItemSetChangeListener itemSetChangedListener = addItemSetChangeListener(bindingContext); assertThat(table.getItemIds(), is(empty())); TestRowPmo newRow = new TestRowPmo(); tablePmo.getItems().add(newRow); bindingContext.modelChanged(); assertThat(tablePmo.getItems(), contains(newRow)); assertThat(table.getItemIds(), contains(newRow)); verify(itemSetChangedListener).containerItemSetChange(any()); verifyNoMoreInteractions(itemSetChangedListener); }
@Test public void testItems_UponUpdate_RemoveItems() { TestRowPmo row1 = new TestRowPmo(); TestRowPmo row2 = new TestRowPmo(); TestTablePmo tablePmo = new TestTablePmo(row1, row2); Table table = new PmoBasedTableFactory(tablePmo, bindingContext).createTable(); ItemSetChangeListener itemSetChangedListener = addItemSetChangeListener(bindingContext); assertThat(table.getItemIds().size(), is(2)); tablePmo.getItems().remove(row1); bindingContext.modelChanged(); assertThat(tablePmo.getItems(), contains(row2)); assertThat(table.getItemIds(), contains(row2)); verify(itemSetChangedListener).containerItemSetChange(any()); verifyNoMoreInteractions(itemSetChangedListener); }
@Test public void testDataSourceSet() { TestTablePmo tablePmo = new TestTablePmo(); Table table = new PmoBasedTableFactory(tablePmo, bindingContext).createTable(); assertThat(getTableContainer(bindingContext), is(table.getContainerDataSource())); }
@Test public void testFooterUpdateAfterConstruction() { TableFooterPmo footerPmo = property -> property; TestTablePmo tablePmo = new TestTablePmo(footerPmo); Table table = new PmoBasedTableFactory(tablePmo, bindingContext).createTable(); ItemSetChangeListener itemSetChangedListener = addItemSetChangeListener(bindingContext); assertThat(table.isFooterVisible()); assertThat(table.getColumnFooter(TestRowPmo.PROPERTY_VALUE_1), is(TestRowPmo.PROPERTY_VALUE_1)); assertThat(table.getColumnFooter(TestRowPmo.PROPERTY_VALUE_2), is(TestRowPmo.PROPERTY_VALUE_2)); tablePmo.setFooterPmo(null); bindingContext.modelChanged(); assertThat(table.isFooterVisible(), is(false)); verifyNoMoreInteractions(itemSetChangedListener); tablePmo.setFooterPmo(property -> "test"); bindingContext.modelChanged(); assertThat(table.isFooterVisible()); assertThat(table.getColumnFooter(TestRowPmo.PROPERTY_VALUE_1), is("test")); verifyNoMoreInteractions(itemSetChangedListener); } |
### Question:
MetaAnnotation { public boolean isRepeatable() { return repeatable; } private MetaAnnotation(Class<META> metaAnnotationClass); static MetaAnnotation<META> of(Class<META> metaAnnotationClass); boolean isRepeatable(); boolean isPresentOnAnyAnnotationOn(AnnotatedElement annotatedElement); boolean isPresentOn(@CheckForNull Annotation annotation); Optional<META> findOn(Annotation annotation); Stream<META> findAllOn(Annotation annotation); Stream<Annotation> findAnnotatedAnnotationsOn(AnnotatedElement annotatedElement); BinaryOperator<A> onlyOneOn(AnnotatedElement annotatedElement); Supplier<? extends IllegalArgumentException> missingAnnotation(Annotation annotation,
AnnotatedElement annotatedElement,
String checkerMethod); }### Answer:
@Test public void testIsRepeatable() { assertThat(MetaAnnotation.of(MetaMarkerAnnotation.class).isRepeatable(), is(false)); assertThat(MetaAnnotation.of(RepeatableMetaMarkerAnnotation.class).isRepeatable()); } |
### Question:
AbstractSection extends VerticalLayout { private static void addHeaderButton(AbstractOrderedLayout header, Button button) { button.addStyleName(LinkkiTheme.BUTTON_TEXT); header.addComponent(button); } AbstractSection(String caption); AbstractSection(String caption, boolean closeable); AbstractSection(String caption, boolean closeable, Optional<Button> editButton); boolean isEditButtonAvailable(); void addHeaderButton(Button button); boolean isOpen(); boolean isClosed(); void open(); void close(); }### Answer:
@Test public void testAddHeaderButton_HeaderButtonIsAddedBeforeCloseButton() { AbstractSection section = new TestSection("caption", true, Optional.empty()); HorizontalLayout sectionHeader = (HorizontalLayout)section.getComponent(0); assertThat(sectionHeader, is(notNullValue())); assertThat(sectionHeader.getComponentCount(), is(3)); assertThat(sectionHeader.getComponent(1), is(instanceOf(Button.class))); Button closeButton = (Button)sectionHeader.getComponent(1); assertThat(closeButton.getIcon(), is(FontAwesome.ANGLE_DOWN)); Button headerButton1 = ComponentFactory.newButton(); section.addHeaderButton(headerButton1); assertThat(sectionHeader.getComponentCount(), is(4)); assertThat(sectionHeader.getComponent(2), is(closeButton)); Button button1 = (Button)sectionHeader.getComponent(1); assertThat(button1, is(headerButton1)); Button headerButton2 = ComponentFactory.newButton(); section.addHeaderButton(headerButton2); assertThat(sectionHeader.getComponentCount(), is(5)); assertThat(sectionHeader.getComponent(3), is(closeButton)); Button button2 = (Button)sectionHeader.getComponent(2); assertThat(button2, is(headerButton2)); }
@Test public void testAddHeaderButton_HeaderButtonIsAddedAtEndIfCloseButtonIsMissing() { AbstractSection section = new TestSection("caption", false, Optional.empty()); HorizontalLayout sectionHeader = (HorizontalLayout)section.getComponent(0); assertThat(sectionHeader, is(notNullValue())); assertThat(sectionHeader.getComponentCount(), is(2)); Button headerButton1 = ComponentFactory.newButton(); section.addHeaderButton(headerButton1); assertThat(sectionHeader.getComponentCount(), is(3)); Button button1 = (Button)sectionHeader.getComponent(1); assertThat(button1, is(headerButton1)); Button headerButton2 = ComponentFactory.newButton(); section.addHeaderButton(headerButton2); assertThat(sectionHeader.getComponentCount(), is(4)); assertThat(sectionHeader.getComponent(1), is(button1)); Button button2 = (Button)sectionHeader.getComponent(2); assertThat(button2, is(headerButton2)); } |
### Question:
SectionCreationContext { @Deprecated public BaseSection createSection() { return (BaseSection)sectionBuilder.createSection(); } @Deprecated SectionCreationContext(Object pmo, BindingContext bindingContext); @Deprecated BaseSection createSection(); }### Answer:
@Test public void testSetSectionId() { BaseSection section = createContext(new SCCPmoWithID()).createSection(); assertThat(section.getId(), is("test-ID")); }
@Test public void testSetSectionDefaultId() { BaseSection section = createContext(new SCCPmoWithoutID()).createSection(); assertThat(section.getId(), is("SCCPmoWithoutID")); }
@Test public void testSetComponentId() { BaseSection section = createContext(new SCCPmoWithID()).createSection(); assertThat(section.getComponentCount(), is(2)); @NonNull Panel panel = (Panel)section.getComponent(1); @NonNull GridLayout gridLayout = (GridLayout)panel.getContent(); @NonNull Component textField = gridLayout.getComponent(1, 0); assertThat(textField.getId(), is("testProperty")); }
@Test public void testSectionWithDefaultLayout_shouldCreateFormLayout() { BaseSection section = createContext(new SCCPmoWithoutID()).createSection(); assertThat(section, is(instanceOf(FormSection.class))); }
@Test public void testSectionWithHorizontalLayout_shouldCreateHorizontalSection() { BaseSection section = createContext(new SectionWithHorizontalLayout()).createSection(); assertThat(section, is(instanceOf(HorizontalSection.class))); }
@Test public void testSectionWithCustomLayout_shouldCreateCustomLayoutSection() { BaseSection section = createContext(new SectionWithCustomLayout()).createSection(); assertThat(section, is(instanceOf(CustomLayoutSection.class))); }
@Test public void testSectionWithoutAnnotation_usesDefaultValues() { BaseSection section = createContext(new SectionWithoutAnnotation()).createSection(); assertThat(section, is(instanceOf(FormSection.class))); assertThat(section.getId(), is(SectionWithoutAnnotation.class.getSimpleName())); assertThat(section.getCaption(), is(nullValue())); assertThat(((FormSection)section).getNumberOfColumns(), is(1)); } |
### Question:
MetaAnnotation { public static <META extends Annotation> MetaAnnotation<META> of(Class<META> metaAnnotationClass) { Target target = metaAnnotationClass.getAnnotation(Target.class); if (target == null) { throw new IllegalArgumentException( metaAnnotationClass.getSimpleName() + " has no @" + Target.class.getSimpleName() + " annotation"); } if (Arrays.stream(target.value()).noneMatch(t -> t == ElementType.ANNOTATION_TYPE || t == ElementType.TYPE)) { throw new IllegalArgumentException( metaAnnotationClass.getSimpleName() + " is no meta-annotation. @" + Target.class.getSimpleName() + " is " + Arrays.toString(target.value()) + " but should be " + ElementType.ANNOTATION_TYPE); } return new MetaAnnotation<>(metaAnnotationClass); } private MetaAnnotation(Class<META> metaAnnotationClass); static MetaAnnotation<META> of(Class<META> metaAnnotationClass); boolean isRepeatable(); boolean isPresentOnAnyAnnotationOn(AnnotatedElement annotatedElement); boolean isPresentOn(@CheckForNull Annotation annotation); Optional<META> findOn(Annotation annotation); Stream<META> findAllOn(Annotation annotation); Stream<Annotation> findAnnotatedAnnotationsOn(AnnotatedElement annotatedElement); BinaryOperator<A> onlyOneOn(AnnotatedElement annotatedElement); Supplier<? extends IllegalArgumentException> missingAnnotation(Annotation annotation,
AnnotatedElement annotatedElement,
String checkerMethod); }### Answer:
@Test public void testOf_NoTarget() { try { MetaAnnotation.of(NoTargetAnnotation.class); fail("expected a " + IllegalArgumentException.class.getSimpleName()); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString(NoTargetAnnotation.class.getSimpleName())); assertThat(e.getMessage(), containsString(Target.class.getSimpleName())); } }
@Test public void testOf_WrongTarget() { try { MetaAnnotation.of(MethodAnnotation.class); fail("expected a " + IllegalArgumentException.class.getSimpleName()); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString(MethodAnnotation.class.getSimpleName())); assertThat(e.getMessage(), containsString(Target.class.getSimpleName())); assertThat(e.getMessage(), containsString(ElementType.METHOD.toString())); assertThat(e.getMessage(), containsString(ElementType.ANNOTATION_TYPE.toString())); } } |
### Question:
TabSheetArea extends VerticalLayout implements Area { protected List<Page> getTabs() { return StreamUtil.stream(() -> tabSheet.iterator()) .filter(c -> c instanceof Page) .map(c -> (Page)c) .collect(Collectors.toList()); } TabSheetArea(); TabSheetArea(boolean preserveHeader); @PostConstruct final void init(); TabSheet getTabSheet(); @Override void reloadBindings(); }### Answer:
@Test public void testGetTabs() { Page tabPage1 = mock(Page.class); Page tabPage2 = mock(Page.class); TabSheetArea tabSheetArea = new TestArea(); assertThat(tabSheetArea.getTabs(), is(empty())); tabSheetArea.addTab(tabPage1, "1"); tabSheetArea.addTab(tabPage2, "2"); assertThat(tabSheetArea.getTabs(), contains(tabPage1, tabPage2)); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { public void setItems(Collection<? extends T> items) { requireNonNull(items, "items must not be null"); getAllItemIds().clear(); getAllItemIds().addAll(items); fireItemSetChange(); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testBackupListShouldBeClearedOnRemoveAllItems() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); container.setItems(Collections.singletonList(new TestItem())); assertThat(container.getItemIds(), hasSize(1)); container.setItems(Collections.emptyList()); assertThat(container.getItemIds(), hasSize(0)); }
@Test public void testEqualsOfWrapperShouldOnlyCheckReference() { TestItem testItem = new TestItem(42); LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); container.setItems(Collections.singletonList(testItem)); TestItem equalItem = new TestItem(42); assertThat(testItem, is(equalItem)); assertThat(container.getItemIds().get(0), is(equalItem)); assertThat(container.getItemIds().get(0), is(testItem)); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @Override @SuppressWarnings({ "unchecked" }) public Collection<T> getChildren(Object itemId) { return children.computeIfAbsent((T)itemId, this::getChildrenTypesafe); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testGetChildren_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.getChildren(new TestItem(42)), is(empty())); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @CheckForNull @Override public T getParent(Object itemId) { return parents.get(itemId); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testGetParent_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.getParent(new TestItem(42)), is(nullValue())); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @Override public boolean setParent(Object itemId, Object newParentId) throws UnsupportedOperationException { return false; } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testSetParent() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); HierarchicalTestItem testItem1 = new HierarchicalTestItem(23); HierarchicalTestItem testItem2 = new HierarchicalTestItem(42); assertThat(container.setParent(testItem1, testItem2), is(false)); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @Override public boolean areChildrenAllowed(Object itemId) { return hasChildren(itemId); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testAreChildrenAllowed_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.areChildrenAllowed(new TestItem(42)), is(false)); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @Override public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed) throws UnsupportedOperationException { return false; } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testSetChildrenAllowed() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); HierarchicalTestItem testItem = new HierarchicalTestItem(23); assertThat(container.setChildrenAllowed(testItem, true), is(false)); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @Override public boolean isRoot(Object itemId) { return containsId(itemId); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testIsRoot_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.isRoot(new TestItem(42)), is(false)); } |
### Question:
LinkkiInMemoryContainer extends AbstractInMemoryContainer<T, Object, Item> implements Container.Hierarchical { @Override public boolean hasChildren(Object itemId) { return getHierarchicalItem(itemId) .map(HierarchicalRowPmo::hasChildRows) .orElse(false); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override @CheckForNull Property<T> getContainerProperty(@CheckForNull Object itemId, Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testHasChildren_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.hasChildren(new TestItem(42)), is(false)); } |
### Question:
Vaadin7 implements UiFrameworkExtension { @Override public Locale getLocale() { UI ui = UI.getCurrent(); if (ui != null) { Locale locale = ui.getLocale(); if (locale != null) { return locale; } } return Locale.GERMAN; } @Override Locale getLocale(); @Override ComponentWrapperFactory getComponentWrapperFactory(); @Override Stream<?> getChildComponents(Object uiComponent); }### Answer:
@Test public void testGetUiLocale() { assertThat(UI.getCurrent(), is(nullValue())); assertThat(UiFramework.getLocale(), is(Locale.GERMAN)); UI ui = MockUi.mockUi(); when(ui.getLocale()).thenReturn(Locale.ITALIAN); assertThat(UiFramework.getLocale(), is(Locale.ITALIAN)); } |
### Question:
Vaadin7 implements UiFrameworkExtension { @Override public Stream<?> getChildComponents(Object uiComponent) { if (uiComponent instanceof HasComponents) { return StreamUtil.stream((HasComponents)uiComponent); } return Stream.empty(); } @Override Locale getLocale(); @Override ComponentWrapperFactory getComponentWrapperFactory(); @Override Stream<?> getChildComponents(Object uiComponent); }### Answer:
@Test public void testGetChildComponents() { Component component1 = new Label("first label"); Component component2 = new Label("second label"); HasComponents componentWithChildren = new VerticalLayout(component1, component2); Component[] arr = { component1, component2 }; assertThat(UiFramework.get().getChildComponents(componentWithChildren).toArray(), is(arr)); } |
### Question:
UiFramework { public static UiFrameworkExtension get() { return Services.get(UiFrameworkExtension.class); } private UiFramework(); static Locale getLocale(); static ComponentWrapperFactory getComponentWrapperFactory(); static UiFrameworkExtension get(); static Stream<?> getChildComponents(Object uiComponent); }### Answer:
@Test public void testGet() { assertThat(UiFramework.get(), is(instanceOf(TestUiFramework.class))); } |
### Question:
ComponentAnnotationReader { public static <A extends Annotation> LinkkiComponentDefinition getComponentDefinition( A annotation, AnnotatedElement annotatedElement) { LinkkiComponent linkkiComponent = LINKKI_COMPONENT_ANNOTATION.findOn(annotation) .orElseThrow(LINKKI_COMPONENT_ANNOTATION .missingAnnotation(annotation, annotatedElement, ComponentAnnotationReader.class.getSimpleName() + "#isComponentDefinition(Annotation)")); @SuppressWarnings("unchecked") Class<ComponentDefinitionCreator<A>> creatorClass = (Class<ComponentDefinitionCreator<A>>)linkkiComponent .value(); return Classes.instantiate(creatorClass).create(annotation, annotatedElement); } private ComponentAnnotationReader(); static boolean isComponentDefinition(@CheckForNull Annotation annotation); static boolean isComponentDefinitionPresent(AnnotatedElement annotatedElement); static Stream<Method> getComponentDefinitionMethods(Class<?> pmoClass); static LinkkiComponentDefinition getComponentDefinition(
A annotation,
AnnotatedElement annotatedElement); static Optional<LinkkiComponentDefinition> findComponentDefinition(AnnotatedElement annotatedElement); static Annotation getComponentDefinitionAnnotation(AnnotatedElement annotatedElement, Object pmo); static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetComponentDefinition() throws Exception { LinkkiComponentDefinition componentDefinition = ComponentAnnotationReader .getComponentDefinition(ClassWithComponentAnnotatedAnnotations.class.getMethod("annotated") .getAnnotation(AnnotationWithComponentAnnotation.class), ClassWithComponentAnnotatedAnnotations.class.getMethod("annotated")); assertThat(componentDefinition.createComponent("input"), is(TESTCOMPONENT)); assertThat(componentDefinition.createComponent(this), is(TESTCOMPONENT)); }
@Test public void testGetComponentDefinition_AnnotatedField() throws Exception { LinkkiComponentDefinition componentDefinition = ComponentAnnotationReader .getComponentDefinition(ClassWithComponentAnnotatedAnnotations.class.getField("component") .getAnnotation(AnnotationWithComponentAnnotation.class), ClassWithComponentAnnotatedAnnotations.class.getField("component")); assertThat(componentDefinition.createComponent("input"), is(TESTCOMPONENT)); assertThat(componentDefinition.createComponent(this), is(TESTCOMPONENT)); }
@Test public void testGetComponentDefinition_MethodAnnotatedWithoutComponentAnnotation() throws Exception { Method method = ClassWithComponentAnnotatedAnnotations.class.getMethod("annotatedWithoutComponent"); AnnotationWithoutComponentAnnotation annotation = method .getAnnotation(AnnotationWithoutComponentAnnotation.class); try { ComponentAnnotationReader.getComponentDefinition(annotation, method); fail("expected an " + IllegalArgumentException.class.getSimpleName()); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString(AnnotationWithoutComponentAnnotation.class.getSimpleName())); assertThat(e.getMessage(), containsString("annotatedWithoutComponent")); assertThat(e.getMessage(), containsString("isComponentDefinition")); } }
@Test public void testGetComponentDefinition_MethodAnnotatedWithInvalidComponentAnnotation() throws Exception { Method method = ClassWithComponentAnnotatedAnnotations.class .getMethod("annotatedWithInvalidComponentAnnotation"); AnnotationWithInvalidCreator annotation = method .getAnnotation(AnnotationWithInvalidCreator.class); try { ComponentAnnotationReader.getComponentDefinition(annotation, method); fail("expected an " + IllegalArgumentException.class.getSimpleName()); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString(AnnotationWithInvalidCreator.Creator.class.getSimpleName())); } } |
### Question:
ComponentAnnotationReader { public static boolean isComponentDefinition(@CheckForNull Annotation annotation) { return LINKKI_COMPONENT_ANNOTATION.isPresentOn(annotation); } private ComponentAnnotationReader(); static boolean isComponentDefinition(@CheckForNull Annotation annotation); static boolean isComponentDefinitionPresent(AnnotatedElement annotatedElement); static Stream<Method> getComponentDefinitionMethods(Class<?> pmoClass); static LinkkiComponentDefinition getComponentDefinition(
A annotation,
AnnotatedElement annotatedElement); static Optional<LinkkiComponentDefinition> findComponentDefinition(AnnotatedElement annotatedElement); static Annotation getComponentDefinitionAnnotation(AnnotatedElement annotatedElement, Object pmo); static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testIsLinkkiComponentDefinition() throws Exception { assertTrue(ComponentAnnotationReader .isComponentDefinition(ClassWithComponentAnnotatedAnnotations.class.getMethod("annotated") .getAnnotation(AnnotationWithComponentAnnotation.class))); assertFalse(ComponentAnnotationReader .isComponentDefinition(ClassWithComponentAnnotatedAnnotations.class .getMethod("annotatedWithoutComponent") .getAnnotation(AnnotationWithoutComponentAnnotation.class))); } |
### Question:
PositionAnnotationReader { public static int getPosition(AnnotatedElement element) { return Arrays.stream(element.getAnnotations()) .filter(a -> a.annotationType().isAnnotationPresent(LinkkiPositioned.class)) .map(PositionAnnotationReader::getPosition) .reduce((a, b) -> verifySamePosition(element, a, b)) .orElseGet(() -> getDeprecatedPosition(element)); } private PositionAnnotationReader(); static int getPosition(AnnotatedElement element); static int getPosition(Annotation annotation); }### Answer:
@Test public void testGetPositionAnnotatedElement() throws Exception { int position = PositionAnnotationReader.getPosition(PosTestPmo.class.getMethod("test")); assertThat(position, is(42)); }
@Test public void testGetPositionAnnotatedElement_SamePosTwice() throws Exception { int position = PositionAnnotationReader.getPosition(PosTestPmo.class.getMethod("testSamePos")); assertThat(position, is(42)); }
@Test public void testGetPositionAnnotatedElement_DiffPos() { Assertions.assertThrows(IllegalArgumentException.class, () -> { PositionAnnotationReader.getPosition(PosTestPmo.class.getMethod("testDiffPos")); }); }
@Test public void testGetPositionAnnotatedElement_BindingDefinition() throws Exception { int position = PositionAnnotationReader.getPosition(PosTestPmo.class.getMethod("testDeprecated")); assertThat(position, is(4711)); } |
### Question:
LayoutAnnotationReader { public static boolean isLayoutDefinition(@CheckForNull Annotation annotation) { return LINKKI_LAYOUT_ANNOTATION.isPresentOn(annotation); } private LayoutAnnotationReader(); static boolean isLayoutDefinition(@CheckForNull Annotation annotation); static Optional<LinkkiLayoutDefinition> findLayoutDefinition(AnnotatedElement annotatedElement); }### Answer:
@Test public void testIsLayoutDefinition() { assertThat(LayoutAnnotationReader.isLayoutDefinition(DummyPmo.class.getAnnotation(DummyLayout.class))); assertThat(LayoutAnnotationReader.isLayoutDefinition(DummyLayout.class.getAnnotation(LinkkiLayout.class)), is(false)); } |
### Question:
LayoutAnnotationReader { public static Optional<LinkkiLayoutDefinition> findLayoutDefinition(AnnotatedElement annotatedElement) { return LINKKI_LAYOUT_ANNOTATION .findAnnotatedAnnotationsOn(annotatedElement) .reduce(LINKKI_LAYOUT_ANNOTATION.onlyOneOn(annotatedElement)) .map(annotation -> getLayoutDefinition(annotation, annotatedElement)); } private LayoutAnnotationReader(); static boolean isLayoutDefinition(@CheckForNull Annotation annotation); static Optional<LinkkiLayoutDefinition> findLayoutDefinition(AnnotatedElement annotatedElement); }### Answer:
@Test public void testFindLayoutDefinition() { Optional<LinkkiLayoutDefinition> layoutDefinition = LayoutAnnotationReader.findLayoutDefinition(DummyPmo.class); assertThat(layoutDefinition, is(present())); assertThat(layoutDefinition.get(), is(instanceOf(DummyLayoutDefinition.class))); assertThat(LayoutAnnotationReader.findLayoutDefinition(String.class), is(absent())); } |
### Question:
UiCreator { public static <C, W extends ComponentWrapper> Stream<W> createUiElements(Object pmo, BindingContext bindingContext, Function<C, W> componentWrapperCreator) { return ComponentAnnotationReader.getComponentDefinitionMethods(pmo.getClass()) .map(m -> createUiElement(m, pmo, bindingContext, componentWrapperCreator)); } private UiCreator(); static Stream<W> createUiElements(Object pmo,
BindingContext bindingContext,
Function<C, W> componentWrapperCreator); static W createUiElement(AnnotatedElement annotatedElement,
Object pmo,
BindingContext bindingContext,
Function<C, W> componentWrapperCreator); static ComponentWrapper createComponent(Object pmo,
BindingContext bindingContext); @Deprecated @SuppressWarnings("overloads") static ComponentWrapper createComponent(Object pmo,
BindingContext bindingContext,
Function<Class<?>, Optional<LinkkiComponentDefinition>> componentDefinitionFinder,
Function<Class<?>, Optional<LinkkiLayoutDefinition>> layoutDefinitionFinder); @SuppressWarnings("overloads") static ComponentWrapper createComponent(Object pmo,
BindingContext bindingContext,
LinkkiComponentDefinition componentDefinition,
Optional<LinkkiLayoutDefinition> layoutDefinition); }### Answer:
@Test public void testCreateUiElements() { TestSectionPmo testSectionPmo = new TestSectionPmo(); BindingContext bindingContext = new BindingContext(); List<TestComponentWrapper> wrappers = UiCreator .createUiElements(testSectionPmo, bindingContext, TestComponentWrapper::new) .collect(Collectors.toList()); assertThat(wrappers, hasSize(2)); List<String> componentIds = wrappers.stream().map(TestComponentWrapper::getComponent) .map(TestUiComponent::getId).collect(Collectors.toList()); assertThat(componentIds, contains(TestPmo.PROPERTY_VALUE, TestModelObject.PROPERTY_MODEL_PROP)); List<String> boundIds = bindingContext.getBindings().stream().map(Binding::getBoundComponent) .map(TestUiComponent.class::cast).map(TestUiComponent::getId).collect(Collectors.toList()); assertThat(boundIds, containsInAnyOrder(TestPmo.PROPERTY_VALUE, TestModelObject.PROPERTY_MODEL_PROP)); }
@DisplayName("Given a dynamic field annotated with both @TestUIField and @TestUIField2,") @ParameterizedTest(name = "when the get~ComponentType method returns {0}") @ValueSource(classes = { TestUIField.class, TestUIField2.class }) public void testCreateUiElements_DynamicField(Class<?> componentType) { class DynamicFieldTestPmo { @SuppressFBWarnings("UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS") @TestUIField(position = 10) @TestUIField2(position = 10) public String getDynamic() { return "dyn"; } @SuppressFBWarnings("UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS") public Class<?> getDynamicComponentType() { return componentType; } } DynamicFieldTestPmo testPmo = new DynamicFieldTestPmo(); BindingContext bindingContext = new BindingContext(); List<TestUiComponent> components = UiCreator .createUiElements(testPmo, bindingContext, TestComponentWrapper::new) .map(TestComponentWrapper::getComponent) .collect(Collectors.toList()); assertThat(components, hasSize(1)); if (componentType.equals(TestUIField.class)) { assertThat(components.get(0), is(not(instanceOf(TestUIField2.TestUiComponent2.class)))); } else if (componentType.equals(TestUIField2.class)) { assertThat(components.get(0), is(instanceOf(TestUIField2.TestUiComponent2.class))); } } |
### Question:
SimpleItemSupplier implements Supplier<List<PMO>> { @Override public List<PMO> get() { List<? extends MO> actualModelObjects = modelObjectSupplier.get(); requireNonNull(actualModelObjects, "modelObjectSupplier must supply a List of model objects (which may be empty)"); if (hasUnderlyingModelObjectListChanged(actualModelObjects)) { HashSet<? extends MO> actualModelObjectsSet = new HashSet<>(actualModelObjects); itemMap.keySet().removeIf(o -> !actualModelObjectsSet.contains(o)); items = new LinkedList<>(); actualModelObjects.forEach(mo -> items.add(applymo2pmoMapping(mo))); modelObjectsCopy = new ArrayList<>(actualModelObjects); } return items; } SimpleItemSupplier(Supplier<? extends List<? extends MO>> modelObjectSupplier,
Function<MO, PMO> mo2pmoMapping); @Override List<PMO> get(); }### Answer:
@Test public void testCreateItemSupplierWithoutUnknownType() { Supplier<List<Integer>> supplier = () -> Arrays.asList(1); SimpleItemSupplier<Integer, Integer> itemSupplier2 = new SimpleItemSupplier<>(supplier, UnaryOperator.identity()); assertThat(itemSupplier2.get(), hasItem(1)); }
@Test public void testGet_shouldReturnEmptyList_ifUnderlyingListIsEmpty() { assertThat(itemSupplier.get(), hasSize(0)); }
@Test public void testGet_shouldReturnNewList_ifUnderlyingListHasCanged() { itemSupplier.get(); modelObjects.add(42); assertThat(itemSupplier.get(), hasSize(1)); SimplePmo pmo = itemSupplier.get().get(0); assertThat(pmo.getModelObject(), is(42)); modelObjects.add(43); assertThat(itemSupplier.get(), hasSize(2)); assertThat(itemSupplier.get().get(0), is(pmo)); assertThat(itemSupplier.get().get(1).getModelObject(), is(43)); }
@Test public void testGet_shouldReturnNewList_ifUnderlyingListHasCangedOrder() { modelObjects.add(0); modelObjects.add(1); assertThat(itemSupplier.get(), hasSize(2)); assertThat(itemSupplier, hasPmosForModelobjects(0, 1)); SimplePmo pmo2 = itemSupplier.get().get(1); modelObjects.set(0, 99); assertThat(itemSupplier.get(), hasSize(2)); assertThat(itemSupplier, hasPmosForModelobjects(99, 1)); assertThat(pmo2, is(itemSupplier.get().get(1))); }
@Test public void testGet_ShouldRemoveUnusedModelObjectMappings() { modelObjects.add(0); SimplePmo pmo1 = itemSupplier.get().get(0); modelObjects.set(0, 99); itemSupplier.get(); modelObjects.set(0, 0); assertThat(pmo1, is(not(itemSupplier.get().get(0)))); }
@Test public void testGet_shouldReturnSameList_ifUnderlyingListHasNotChanged() { modelObjects.add(42); List<SimplePmo> list = itemSupplier.get(); List<SimplePmo> list2 = itemSupplier.get(); assertThat(list == list2); } |
### Question:
ColumnBasedComponentFactory { public Object createContainerComponent(ContainerPmo<?> containerPmo, BindingContext bindingContext) { ComponentWrapper tableWrapper = containerComponentCreator .createComponent(requireNonNull(containerPmo, "containerPmo must not be null")); requireNonNull(bindingContext, "bindingContext must not be null"); List<LinkkiAspectDefinition> tableAspects = AspectAnnotationReader .createAspectDefinitionsFor(containerPmo.getClass()); ContainerBinding binding = bindingContext.bindContainer(containerPmo, BoundProperty.empty(), tableAspects, tableWrapper); createColumns(containerPmo, tableWrapper, binding); binding.updateFromPmo(); return tableWrapper.getComponent(); } ColumnBasedComponentFactory(ColumnBasedComponentCreator containerComponentCreator); Object createContainerComponent(ContainerPmo<?> containerPmo, BindingContext bindingContext); }### Answer:
@Test public void testCreateContainerComponent() { ColumnBasedComponentCreator containerComponentCreator = spy(new TestColumnBasedComponentCreator()); ColumnBasedComponentFactory columnBasedComponentFactory = new ColumnBasedComponentFactory( containerComponentCreator); BindingContext bindingContext = new BindingContext(); TestContainerPmo containerPmo = new TestContainerPmo(); TableFooterPmo footerPmo = $ -> "foot"; containerPmo.setFooterPmo(footerPmo); TestColumnBasedComponent<?> containerComponent = new TestColumnBasedComponent<>(); TestColumnBasedComponentWrapper<?> containerComponentWrapper = new TestColumnBasedComponentWrapper<>( containerComponent); when(containerComponentCreator.createComponent(containerPmo)).thenReturn(containerComponentWrapper); Object createdContainerComponent = columnBasedComponentFactory.createContainerComponent(containerPmo, bindingContext); assertThat(createdContainerComponent, is(sameInstance(containerComponent))); Collection<Binding> bindings = bindingContext.getBindings(); assertThat(getNumberOfBindingsFor(containerComponent, bindings), is(1)); assertThat(getBindingFor(containerComponent, bindings).getPmo(), is(containerPmo)); verify(containerComponentCreator, times(2)).initColumn(eq(containerPmo), eq(containerComponentWrapper), any(BindingContext.class), any(PropertyElementDescriptors.class)); assertThat(containerComponent.getFooterPmo(), hasValue(footerPmo)); assertThat(containerComponent.getColumnsOnLastFooterUpdate(), is(2)); assertThat(containerComponent.getPageLength(), is(0)); containerPmo.addItem(new TestRowPmo()); bindingContext.modelChanged(); assertThat(containerComponent.getPageLength(), is(1)); } |
### Question:
Sections { public static String getSectionId(Object pmo) { Optional<Method> idMethod = BeanUtils.getMethod(pmo.getClass(), (m) -> m.isAnnotationPresent(SectionID.class)); return idMethod.map(m -> getIdFromSectionIdMethod(pmo, m)).orElse(pmo.getClass().getSimpleName()); } private Sections(); static String getSectionId(Object pmo); static Optional<ButtonPmo> getEditButtonPmo(Object pmo); }### Answer:
@Test public void testGetSectionId() { assertThat(Sections.getSectionId(new SectionPmoWithoutId()), is(SectionPmoWithoutId.class.getSimpleName())); TestSectionPmo testSectionPmo = new TestSectionPmo(); testSectionPmo.setId("foo"); assertThat(Sections.getSectionId(testSectionPmo), is("foo")); } |
### Question:
Sections { public static Optional<ButtonPmo> getEditButtonPmo(Object pmo) { return (pmo instanceof PresentationModelObject) ? ((PresentationModelObject)pmo).getEditButtonPmo() : Optional.empty(); } private Sections(); static String getSectionId(Object pmo); static Optional<ButtonPmo> getEditButtonPmo(Object pmo); }### Answer:
@Test public void testGetEditButtonPmo() { assertThat(Sections.getEditButtonPmo(new SectionPmoWithoutId()), is(absent())); assertThat(Sections.getEditButtonPmo(new DefaultPresentationModelObject()), is(absent())); TestSectionPmo testSectionPmo = new TestSectionPmo(); assertThat(Sections.getEditButtonPmo(testSectionPmo), is(absent())); TestButtonPmo editButtonPmo = new TestButtonPmo(); testSectionPmo.setEditButtonPmo(editButtonPmo); assertThat(Sections.getEditButtonPmo(testSectionPmo), hasValue(editButtonPmo)); } |
### Question:
DefaultPmoNlsService implements PmoNlsService { @Override public String getSectionCaption(Class<?> pmoClass, String fallbackValue) { return getLabel(pmoClass, PmoNlsService.getSectionCaptionKey(pmoClass), fallbackValue); } DefaultPmoNlsService(); DefaultPmoNlsService(PmoBundleNameGenerator bundleNameGenerator); @Override String getSectionCaption(Class<?> pmoClass, String fallbackValue); @Override String getLabel(Class<?> pmoClass, String propertyName, String aspectName, String fallbackValue); }### Answer:
@Test public void testGetSectionCaption() { DefaultPmoNlsService defaultPmoNlsService = new DefaultPmoNlsService(); assertThat(defaultPmoNlsService.getSectionCaption(DefaultPmoNlsServiceTest.class, "bar"), is("TheCaption")); } |
### Question:
DefaultPmoNlsService implements PmoNlsService { @Override public String getLabel(Class<?> pmoClass, String propertyName, String aspectName, String fallbackValue) { return getLabel(pmoClass, PmoNlsService.getPropertyKey(pmoClass, propertyName, aspectName), fallbackValue); } DefaultPmoNlsService(); DefaultPmoNlsService(PmoBundleNameGenerator bundleNameGenerator); @Override String getSectionCaption(Class<?> pmoClass, String fallbackValue); @Override String getLabel(Class<?> pmoClass, String propertyName, String aspectName, String fallbackValue); }### Answer:
@Test public void testGetLabel() { DefaultPmoNlsService defaultPmoNlsService = new DefaultPmoNlsService(); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_TEST, "", "foo"), is("no aspect")); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_TEST, "bla", "fallback"), is("blubb")); }
@Test public void testGetLabel_Fallback() { DefaultPmoNlsService defaultPmoNlsService = new DefaultPmoNlsService(); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_NOT_PRESENT, "", "foo"), is("foo")); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_NOT_PRESENT, "bla", "fallback"), is("fallback")); }
@Test public void testGetLabel_Locale() { TestUiFramework.get().setUiLocale(Locale.GERMAN); DefaultPmoNlsService defaultPmoNlsService = new DefaultPmoNlsService(); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_TEST, "", "foo"), is("Kein Aspekt")); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_TEST, "bla", "fallback"), is("BlaBla")); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, "only", "german", "Subsidiaritätsprinzip"), is("Streichholzschächtelchen")); TestUiFramework.get().setUiLocale(Locale.ENGLISH); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, "only", "german", "Subsidiaritätsprinzip"), is("Subsidiaritätsprinzip")); }
@Test public void testGetLabel_OtherPmoBundleNameGenerator() { DefaultPmoNlsService defaultPmoNlsService = new DefaultPmoNlsService( pmoClass -> "messages." + pmoClass.getName().replace('.', '_')); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_TEST, "", "foo"), is("other no aspect")); assertThat(defaultPmoNlsService.getLabel(DefaultPmoNlsServiceTest.class, PROPERTY_TEST, "bla", "fallback"), is("blubber")); } |
### Question:
TooltipAspectDefinition extends ModelToUiAspectDefinition<String> { @Override public Aspect<String> createAspect() { switch (type) { case AUTO: return StringUtils.isEmpty(value) ? Aspect.of(NAME) : Aspect.of(NAME, value); case STATIC: return Aspect.of(NAME, value); case DYNAMIC: return Aspect.of(NAME); default: throw new IllegalArgumentException("TooltipType " + type + " is not supported."); } } TooltipAspectDefinition(TooltipType type, String value); @Override Aspect<String> createAspect(); @Override Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateAspect_Default_WithValue() { TooltipAspectDefinition aspectDefinition = new TooltipAspectDefinition(TooltipType.AUTO, "Bar"); Aspect<String> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(TooltipAspectDefinition.NAME)); assertThat(createdAspect.isValuePresent(), is(true)); assertThat(createdAspect.getValue(), is("Bar")); }
@Test public void testCreateAspect_Default_WithoutValue() { TooltipAspectDefinition aspectDefinition = new TooltipAspectDefinition(TooltipType.AUTO, ""); Aspect<String> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(TooltipAspectDefinition.NAME)); assertThat(createdAspect.isValuePresent(), is(false)); }
@Test public void testCreateAspect_static() { TooltipAspectDefinition aspectDefinition = new TooltipAspectDefinition(TooltipType.STATIC, "Foo"); Aspect<String> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(TooltipAspectDefinition.NAME)); assertThat(createdAspect.getValue(), is("Foo")); }
@Test public void testCreateAspect_dynamic() { TooltipAspectDefinition aspectDefinition = new TooltipAspectDefinition(TooltipType.DYNAMIC, "Bar"); Aspect<String> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(TooltipAspectDefinition.NAME)); assertThat(createdAspect.isValuePresent(), is(false)); } |
### Question:
TooltipAspectDefinition extends ModelToUiAspectDefinition<String> { @Override public Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper) { return componentWrapper::setTooltip; } TooltipAspectDefinition(TooltipType type, String value); @Override Aspect<String> createAspect(); @Override Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateComponentValueSetterComponentWrapper() { TooltipAspectDefinition aspectDefinition = new TooltipAspectDefinition( TooltipType.STATIC, "test"); Consumer<String> setter = aspectDefinition.createComponentValueSetter(componentWrapper); assertThat(componentWrapper.getComponent().getTooltipText(), is(nullValue())); setter.accept("test"); assertThat(componentWrapper.getComponent().getTooltipText(), is("test")); } |
### Question:
VisibleAspectDefinition extends ModelToUiAspectDefinition<Boolean> { @Override public Aspect<Boolean> createAspect() { switch (visibleType) { case DYNAMIC: return Aspect.of(NAME); case INVISIBLE: return Aspect.of(NAME, false); case VISIBLE: return Aspect.of(NAME, true); default: throw new IllegalStateException("Unknown visible type: " + visibleType); } } VisibleAspectDefinition(VisibleType visibleType); @Override Aspect<Boolean> createAspect(); @Override Consumer<Boolean> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateAspect_visible() { VisibleAspectDefinition aspectDefinition = new VisibleAspectDefinition(VisibleType.VISIBLE); Aspect<Boolean> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(VisibleAspectDefinition.NAME)); assertThat(createdAspect.getValue(), is(true)); }
@Test public void testCreateAspect_dynamic() { VisibleAspectDefinition aspectDefinition = new VisibleAspectDefinition(VisibleType.DYNAMIC); Aspect<Boolean> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(VisibleAspectDefinition.NAME)); assertThat(createdAspect.isValuePresent(), is(false)); } |
### Question:
VisibleAspectDefinition extends ModelToUiAspectDefinition<Boolean> { @Override public Consumer<Boolean> createComponentValueSetter(ComponentWrapper componentWrapper) { return componentWrapper::setVisible; } VisibleAspectDefinition(VisibleType visibleType); @Override Aspect<Boolean> createAspect(); @Override Consumer<Boolean> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateComponentValueSetterComponentWrapper() { VisibleAspectDefinition aspectDefinition = new VisibleAspectDefinition( VisibleType.VISIBLE); Consumer<Boolean> setter = aspectDefinition.createComponentValueSetter(componentWrapper); assertThat(componentWrapper.getComponent().isVisible(), is(false)); setter.accept(true); assertThat(componentWrapper.getComponent().isVisible(), is(true)); } |
### Question:
EnabledAspectDefinition extends ModelToUiAspectDefinition<Boolean> { @Override public Aspect<Boolean> createAspect() { switch (enabledType) { case DISABLED: return Aspect.of(NAME, false); case DYNAMIC: return Aspect.of(NAME); case ENABLED: return Aspect.of(NAME, true); default: throw new IllegalStateException("Unknown enabled type: " + enabledType); } } EnabledAspectDefinition(EnabledType enabledType); @Override Aspect<Boolean> createAspect(); @Override Consumer<Boolean> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateAspect_enabled() { EnabledAspectDefinition aspectDefinition = new EnabledAspectDefinition(EnabledType.ENABLED); Aspect<Boolean> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(EnabledAspectDefinition.NAME)); assertThat(createdAspect.getValue(), is(true)); }
@Test public void testCreateAspect_dynamic() { EnabledAspectDefinition aspectDefinition = new EnabledAspectDefinition(EnabledType.DYNAMIC); Aspect<Boolean> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(EnabledAspectDefinition.NAME)); assertThat(createdAspect.isValuePresent(), is(false)); } |
### Question:
EnabledAspectDefinition extends ModelToUiAspectDefinition<Boolean> { @Override public Consumer<Boolean> createComponentValueSetter(ComponentWrapper componentWrapper) { return componentWrapper::setEnabled; } EnabledAspectDefinition(EnabledType enabledType); @Override Aspect<Boolean> createAspect(); @Override Consumer<Boolean> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateComponentValueSetterComponentWrapper() { EnabledAspectDefinition aspectDefinition = new EnabledAspectDefinition( EnabledType.ENABLED); Consumer<Boolean> setter = aspectDefinition.createComponentValueSetter(componentWrapper); assertThat(componentWrapper.getComponent().isEnabled(), is(false)); setter.accept(true); assertThat(componentWrapper.getComponent().isEnabled(), is(true)); } |
### Question:
AvailableValuesProvider { public static List<Object> booleanPrimitiveToValues() { return Arrays.asList(true, false); } private AvailableValuesProvider(); static List<T> enumToValues(Class<T> valueClass, boolean inclNull); static List<Boolean> booleanWrapperToValues(); static List<Object> booleanPrimitiveToValues(); }### Answer:
@Test public void testBooleanPrimitiveToValues() { assertThat(AvailableValuesProvider.booleanPrimitiveToValues().size(), is(2)); } |
### Question:
AvailableValuesProvider { public static List<Boolean> booleanWrapperToValues() { return Arrays.asList(null, Boolean.TRUE, Boolean.FALSE); } private AvailableValuesProvider(); static List<T> enumToValues(Class<T> valueClass, boolean inclNull); static List<Boolean> booleanWrapperToValues(); static List<Object> booleanPrimitiveToValues(); }### Answer:
@Test public void testBooleanToValues() { assertThat(AvailableValuesProvider.booleanWrapperToValues().size(), is(3)); } |
### Question:
AvailableValuesProvider { public static <T extends Enum<T>> List<T> enumToValues(Class<T> valueClass, boolean inclNull) { List<T> values = Arrays.asList(valueClass.getEnumConstants()); if (inclNull) { ArrayList<T> result = new ArrayList<>(); result.add(null); result.addAll(values); return Collections.unmodifiableList(result); } else { return values; } } private AvailableValuesProvider(); static List<T> enumToValues(Class<T> valueClass, boolean inclNull); static List<Boolean> booleanWrapperToValues(); static List<Object> booleanPrimitiveToValues(); }### Answer:
@SuppressWarnings("unchecked") @Test public void testEnumToValues() { assertThat(AvailableValuesProvider.enumToValues(TestEnum.class, false).size(), is(3)); assertThat(AvailableValuesProvider.enumToValues(TestEnum.class, true).size(), is(4)); assertThat(AvailableValuesProvider.enumToValues(TestEnum.class, true).get(0), is(nullValue())); assertThat(AvailableValuesProvider.enumToValues(TestEnum.VALUE1.getClass().asSubclass(Enum.class), false) .size(), is(3)); } |
### Question:
XmlValidationDelegate implements RequestDelegationHandler { protected void validateRequiredServiceParameter(XmlObject requestDocument) throws OwsException { XmlCursor xmlCursor = requestDocument.newCursor(); xmlCursor.toFirstChild(); String serviceParameter = "service"; if (moveToAttribute(xmlCursor, serviceParameter)) { validateServiceParameter(xmlCursor.getTextValue()); } } XmlValidationDelegate(XmlDelegate toDecorate); XmlObject delegate(); }### Answer:
@Test(expected = MissingParameterValueException.class) public void testMissingServiceInRequest() throws Exception { XmlObject submitDocument = getRequest(REQUEST_MISSING_SERVICE); validatingDelegate.validateRequiredServiceParameter(submitDocument); }
@Test(expected = InvalidParameterValueException.class) public void testInvalidServiceInRequest() throws Exception { XmlObject submitDocument = getRequest(REQUEST_INVALID_SERVICE); validatingDelegate.validateRequiredServiceParameter(submitDocument); } |
### Question:
StatusReportGenerator { public StatusReportType generateWithoutTaskingParameters() throws StatusInformationExpiredException { if (isStatusInformationExpired()) { throw new StatusInformationExpiredException(); } StatusReportType statusReport = StatusReportType.Factory.newInstance(); statusReport.setRequestStatus(sensorTask.getRequestStatusAsString()); setCommonStatusReportParameters(statusReport); if (!isRejected() && !isInPendingState()) { setStatusReportParametersForAcceptedTask(statusReport); } return statusReport; } private StatusReportGenerator(SensorTask sensorTask); static StatusReportGenerator createFor(SensorTask sensorTask); StatusReportType generateWithTaskingParameters(); StatusReportType generateWithoutTaskingParameters(); }### Answer:
@Test public void testGenerateForRejectedTask() throws Exception { StatusReportGenerator statusReporter = getStatusReporter(); validTask.setRequestStatus(TaskingRequestStatus.REJECTED); StatusReportType reportUnderTest = statusReporter.generateWithoutTaskingParameters(); assertSetParametersOfNonAcceptedTask(reportUnderTest); assertFalse(reportUnderTest.isSetEvent()); }
@Test public void testGenerateForPendingTask() throws Exception { StatusReportGenerator statusReporter = getStatusReporter(); StatusReportType reportUnderTest = statusReporter.generateWithoutTaskingParameters(); assertSetParametersOfNonAcceptedTask(reportUnderTest); assertFalse(reportUnderTest.isSetEvent()); }
@Test public void testGenerateForAcceptedTask() throws Exception { StatusReportGenerator statusReporter = getStatusReporter(); validTask.setRequestStatus(TaskingRequestStatus.ACCEPTED); StatusReportType reportUnderTest = statusReporter.generateWithoutTaskingParameters(); assertSetParametersOfAcceptedTask(reportUnderTest); }
@Test(expected = StatusInformationExpiredException.class) public void testGenerationOfAlreadyExpiredSensorTask() throws Exception { validTask.setTaskStatus(SensorTaskStatus.EXPIRED); getStatusReporter().generateWithoutTaskingParameters(); }
@Test public void testGenerate() throws Exception { assertNotNull(getStatusReporter().generateWithoutTaskingParameters()); } |
### Question:
NonBlockingTaskingDecorator extends SensorPlugin { @Override public SensorTask submit(final SubmitTaskingRequest submit, final OwsExceptionReport owsExceptionReport) throws OwsException { try { FutureTask<SensorTask> createSensorTask = new FutureTask<SensorTask>(new Callable<SensorTask>() { public SensorTask call() throws Exception { return sensorPlugin.submit(submit, owsExceptionReport); } }); taskingExecutor.execute(createSensorTask); return createSensorTask.get(NON_BLOCK_TIMEOUT, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { LOGGER.warn("No SensorTask could be created for submit request {}", submit, e); NoApplicableCodeException ex = new NoApplicableCodeException(OwsException.INTERNAL_SERVER_ERROR); ex.addExceptionText("Sensor plugin did not succeed creating a sensor task for submit request."); ex.addExceptionText(e.getMessage()); throw ex; } catch (InterruptedException e) { LOGGER.error("No SensorTask could be created for submit request {}", submit, e); NoApplicableCodeException ex = new NoApplicableCodeException(OwsException.INTERNAL_SERVER_ERROR); ex.addExceptionText("Sensor plugin was interrupted while creating a sensor task for submit request."); ex.addExceptionText(e.getMessage()); throw ex; } catch (TimeoutException e) { LOGGER.error("Unacceptable delay creating sensor task (> {} ms)", NON_BLOCK_TIMEOUT, e); NoApplicableCodeException ex = new NoApplicableCodeException(OwsException.INTERNAL_SERVER_ERROR); ex.addExceptionText("Sensor plugin got stuck in creating sensor task."); throw ex; } } private NonBlockingTaskingDecorator(SensorPlugin sensorPlugin); static SensorPlugin enableNonBlockingTasking(SensorPlugin sensorPlugin); SensorTaskService getSensorTaskService(); void setSensorTaskService(SensorTaskService sensorTaskService); String getSensorPluginType(); SensorConfiguration getSensorConfiguration(); ResultAccessDataServiceReference getResultAccessDataServiceReference(); SensorConfiguration mergeSensorConfigurations(SensorConfiguration sensorConfiguration); String toString(); Availability getResultAccessibility(); boolean isDataAvailable(); @Override SensorTask submit(final SubmitTaskingRequest submit, final OwsExceptionReport owsExceptionReport); @Override void qualifyDataComponent(AbstractDataComponentType componentToQualify); @Override Availability getResultAccessibilityFor(SensorTask sensorTask); }### Answer:
@Test(expected = NoApplicableCodeException.class) public void testSubmit() throws OwsException { SensorPlugin nonBlockInstance = NonBlockingTaskingDecorator.enableNonBlockingTasking(instance); nonBlockInstance.submit(null, null); } |
### Question:
InMemorySensorTaskRepository implements SensorTaskRepository { public SensorTask createNewSensorTask(String procedure) { String taskId = taskIdGenerator.generatePrefixedId(procedure, "/"); SensorTaskKey sensorTaskKey = new SensorTaskKey(procedure, taskId); SensorTask sensorTask = new SensorTask(taskId, procedure); sensorTasks.put(sensorTaskKey, sensorTask); return sensorTask; } SensorTask createNewSensorTask(String procedure); void saveOrUpdateSensorTask(SensorTask sensorTask); void removeSensorTask(SensorTask sensorTask); boolean containsSensorTask(String procedure, String taskId); SensorTask getTask(String taskId); Iterable<String> getSensorTaskIds(String procedure); Iterable<SensorTask> getSensorTasks(String procedure); SensorTask getSensorTask(String procedure, String taskId); IdWithPrefixGenerator getIdGenerator(); long getTaskAmountOf(String procedure); }### Answer:
@Test public void testCreateNewTask() { SensorTask newTask = sensorTaskRepository.createNewSensorTask(PROCEDURE_1); assertEquals("Different procedure id of new task.", PROCEDURE_1, newTask.getProcedure()); assertAmountOfCreatedTasksAvailable(sensorTaskRepository, PROCEDURE_1, 1); } |
### Question:
InMemorySensorTaskRepository implements SensorTaskRepository { public SensorTask getTask(String taskId) { for (SensorTask sensorTask : sensorTasks.values()) { if (sensorTask.getTaskId().equals(taskId)) { return sensorTask; } } return null; } SensorTask createNewSensorTask(String procedure); void saveOrUpdateSensorTask(SensorTask sensorTask); void removeSensorTask(SensorTask sensorTask); boolean containsSensorTask(String procedure, String taskId); SensorTask getTask(String taskId); Iterable<String> getSensorTaskIds(String procedure); Iterable<SensorTask> getSensorTasks(String procedure); SensorTask getSensorTask(String procedure, String taskId); IdWithPrefixGenerator getIdGenerator(); long getTaskAmountOf(String procedure); }### Answer:
@Test public void testGetTask() { SensorTaskRepository sensorTaskRepository = new InMemorySensorTaskRepository(); SensorTask newTask = sensorTaskRepository.createNewSensorTask(PROCEDURE_1); assertEquals("tasks are not equal!", newTask, sensorTaskRepository.getTask(newTask.getTaskId())); } |
### Question:
InMemorySensorTaskRepository implements SensorTaskRepository { public Iterable<String> getSensorTaskIds(String procedure) { List<String> taskIds = new ArrayList<String>(); for (SensorTask sensorTask : sensorTasks.values()) { if (sensorTask.getProcedure().equals(procedure)) { taskIds.add(sensorTask.getTaskId()); } } return taskIds; } SensorTask createNewSensorTask(String procedure); void saveOrUpdateSensorTask(SensorTask sensorTask); void removeSensorTask(SensorTask sensorTask); boolean containsSensorTask(String procedure, String taskId); SensorTask getTask(String taskId); Iterable<String> getSensorTaskIds(String procedure); Iterable<SensorTask> getSensorTasks(String procedure); SensorTask getSensorTask(String procedure, String taskId); IdWithPrefixGenerator getIdGenerator(); long getTaskAmountOf(String procedure); }### Answer:
@Test public void testGetSensorTaskIds() { List<SensorTask> createdSensorTasks = new ArrayList<SensorTask>(); createdSensorTasks.add(sensorTaskRepository.createNewSensorTask(PROCEDURE_1)); createdSensorTasks.add(sensorTaskRepository.createNewSensorTask(PROCEDURE_1)); createdSensorTasks.add(sensorTaskRepository.createNewSensorTask(PROCEDURE_2)); assertAmountOfCreatedTasksAvailable(sensorTaskRepository, PROCEDURE_1, 2); assertAmountOfCreatedTasksAvailable(sensorTaskRepository, PROCEDURE_2, 1); try { assertCorrectSensorTaskIds(sensorTaskRepository, createdSensorTasks); } catch(InvalidParameterValueException e) { fail("Task repository reported an unknown task id."); } } |
### Question:
InMemorySensorTaskRepository implements SensorTaskRepository { public Iterable<SensorTask> getSensorTasks(String procedure) { return getAllSensorTasksFor(procedure); } SensorTask createNewSensorTask(String procedure); void saveOrUpdateSensorTask(SensorTask sensorTask); void removeSensorTask(SensorTask sensorTask); boolean containsSensorTask(String procedure, String taskId); SensorTask getTask(String taskId); Iterable<String> getSensorTaskIds(String procedure); Iterable<SensorTask> getSensorTasks(String procedure); SensorTask getSensorTask(String procedure, String taskId); IdWithPrefixGenerator getIdGenerator(); long getTaskAmountOf(String procedure); }### Answer:
@Test public void testGetSensorTasks() { List<SensorTask> createdSensorTasks = new ArrayList<SensorTask>(); createdSensorTasks.add(sensorTaskRepository.createNewSensorTask(PROCEDURE_1)); createdSensorTasks.add(sensorTaskRepository.createNewSensorTask(PROCEDURE_1)); assertAmountOfCreatedTasksAvailable(sensorTaskRepository, PROCEDURE_1, 2); assertCorrectSensorTaskList(sensorTaskRepository, sensorTaskRepository.getSensorTasks(PROCEDURE_1)); } |
### Question:
InMemorySensorTaskRepository implements SensorTaskRepository { public SensorTask getSensorTask(String procedure, String taskId) throws InvalidParameterValueException { SensorTaskKey sensorTaskKey = new SensorTaskKey(procedure, taskId); if (!sensorTasks.containsKey(sensorTaskKey)) { throw new InvalidParameterValueException("task"); } else { return sensorTasks.get(sensorTaskKey); } } SensorTask createNewSensorTask(String procedure); void saveOrUpdateSensorTask(SensorTask sensorTask); void removeSensorTask(SensorTask sensorTask); boolean containsSensorTask(String procedure, String taskId); SensorTask getTask(String taskId); Iterable<String> getSensorTaskIds(String procedure); Iterable<SensorTask> getSensorTasks(String procedure); SensorTask getSensorTask(String procedure, String taskId); IdWithPrefixGenerator getIdGenerator(); long getTaskAmountOf(String procedure); }### Answer:
@Test public void testGetSensorTask() { SensorTask createdTask = sensorTaskRepository.createNewSensorTask(PROCEDURE_2); assertCorrectGetSensorTaskResponse(sensorTaskRepository, createdTask); assertInValidGetSensorTaskThrowsException(sensorTaskRepository); } |
### Question:
InsertSensorOfferingConverter { String createRandomGmlId() { return "uuid_" + UUID.randomUUID().toString(); } SensorOfferingType convertToSensorOfferingType(final InsertSensorOffering insertSensorOffering); }### Answer:
@Test public void shouldCreateValidNcNameGmlId() { InsertSensorOfferingConverter converter = new InsertSensorOfferingConverter(); String randomGmlId = converter.createRandomGmlId(); assertTrue(randomGmlId + " is not a valid NcName!", isNCName(randomGmlId)); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public void init() throws InternalServiceException { sensorPluginLoader = ServiceLoader.load(SensorInstanceFactory.class); if (isMissingRepository()) { throw new IllegalStateException("SensorInstanceProvider misses a repository."); } Iterable<SensorConfiguration> configs = sensorConfigurationRepository.getSensorConfigurations(); for (SensorConfiguration sensorConfiguration : configs) { sensorInstances.add(initSensorInstance(sensorConfiguration)); } LOGGER.info("Initialised {} with #{} sensor configuration(s).", getClass().getSimpleName(), sensorInstances.size()); } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test(expected = IllegalStateException.class) public void testCreateSensorInstanceProviderWithIncompleteSetup() throws InternalServiceException { new SensorInstanceProvider().init(); }
@Test public void testInit() throws InternalServiceException { SensorInstanceProvider provider = new SensorInstanceProvider(); setEmptyInMemoryRepositories(provider); provider.init(); assertTrue(iterableToCollection(provider.getSensors()).isEmpty()); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { protected void addSensor(SensorPlugin sensorInstance) { sensorInstances.add(sensorInstance); } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testAddSensor() throws InternalServiceException { SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(); assertFalse(getSensorPluginsFrom(sensorInstanceProvider).contains(testPlugin)); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(testPlugin); assertTrue(getSensorPluginsFrom(sensorInstanceProvider).contains(testPlugin)); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public Iterable<SensorPlugin> getSensors() { return sensorInstances; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testGetSensors() throws InternalServiceException { assertTrue(getSensorPluginsFrom(sensorInstanceProvider).isEmpty()); SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(testPlugin); SensorPlugin anotherTestPlugin = SimpleSensorPluginTestInstance.createInstance(); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(anotherTestPlugin); assertTrue( !getSensorPluginsFrom(sensorInstanceProvider).isEmpty()); assertTrue(getSensorPluginsFrom(sensorInstanceProvider).size() == 2); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public boolean containsTaskWith(String taskId) { return getTaskForTaskId(taskId) != null; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testContainsTaskWith() throws InternalServiceException { SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(sensorInstanceProvider); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(testPlugin); SensorTask testTask = testPlugin.getSensorTaskService().createNewTask(); assertTrue(sensorInstanceProvider.containsTaskWith(testTask.getTaskId())); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public SensorTask getTaskForTaskId(String taskId) { return getSensorTaskRepository().getTask(taskId); } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testGetTaskForTaskId() throws InternalServiceException { SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(sensorInstanceProvider); assertByTaskCreationViaGlobalTaskRepository(testPlugin); assertByTaskCreationViaSensorTaskServiceProxy(testPlugin); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public boolean containsSensorWith(String procedure) { return getSensorForProcedure(procedure) != null; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testContainsSensorWith() throws InternalServiceException { SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(sensorInstanceProvider); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(testPlugin); assertTrue(sensorInstanceProvider.containsSensorWith(testPlugin.getProcedure())); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public SensorPlugin getSensorForProcedure(String procedure) { for (SensorPlugin sensorInstance : sensorInstances) { if (sensorInstance.getProcedure().equals(procedure)) { return sensorInstance; } } return null; } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testGetSensorForProcedure() throws InternalServiceException { SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(sensorInstanceProvider); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(testPlugin); assertEquals(sensorInstanceProvider.getSensorForProcedure(testPlugin.getProcedure()), testPlugin); } |
### Question:
SensorInstanceProvider implements InsertSensorOfferingListener { public SensorPlugin getSensorForTaskId(String taskId) { SensorTask sensorTask = sensorTaskRepository.getTask(taskId); return getSensorForProcedure(sensorTask.getProcedure()); } void init(); Iterable<SensorPlugin> getSensors(); boolean containsTaskWith(String taskId); SensorTask getTaskForTaskId(String taskId); boolean containsSensorWith(String procedure); SensorPlugin getSensorForProcedure(String procedure); SensorPlugin getSensorForTaskId(String taskId); SensorConfigurationRepository getSensorConfigurationRepository(); void setSensorConfigurationRepository(SensorConfigurationRepository sensorConfigurationRepository); SensorTaskRepository getSensorTaskRepository(); void setSensorTaskRepository(SensorTaskRepository sensorTaskRepository); void handleInsertSensorOffering(InsertSensorOfferingEvent insertSensorOfferingEvent); }### Answer:
@Test public void testGetSensorForTaskId() throws InternalServiceException { SensorPlugin testPlugin = SimpleSensorPluginTestInstance.createInstance(sensorInstanceProvider); ((SensorInstanceProviderSeam) sensorInstanceProvider).addSensor(testPlugin); SensorTaskService taskService = testPlugin.getSensorTaskService(); SensorTask sensorTask = taskService.createNewTask(); assertEquals(testPlugin, sensorInstanceProvider.getSensorForTaskId(sensorTask.getTaskId())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.