Java Code Examples for com.vaadin.flow.component.UI#add()

The following examples show how to use com.vaadin.flow.component.UI#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HtmlComponentSmokeTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private static void smokeTestComponent(
        Class<? extends HtmlComponent> clazz) {
    try {
        // Test that an instance can be created
        HtmlComponent instance = createInstance(clazz);

        // Tests that a String constructor sets the text and not the tag
        // name for a component with @Tag
        if (!ignoredStringConstructors.contains(clazz)) {
            testStringConstructor(clazz);
        }

        // Component must be attached for some checks to work
        UI ui = new UI();
        ui.add(instance);

        // Test that all setters produce a result
        testSetters(instance);
    } catch (InstantiationException | IllegalAccessException
            | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void initModel_requestPopulateModel_onlyUnsetPropertiesAreSent() {
    UI ui = UI.getCurrent();
    InitModelTemplate template = new InitModelTemplate();

    template.getModel().setMessage("foo");

    ui.add(template);

    ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();

    Assert.assertEquals(2, executionOrder.size());
    Assert.assertEquals("this.populateModelProperties($0, $1)",
            executionOrder.get(1));

    Serializable[] params = executionParams.get(1);
    JsonArray properties = (JsonArray) params[1];
    Assert.assertEquals(1, properties.length());
    Assert.assertEquals("title", properties.get(0).asString());
}
 
Example 3
Source File: UidlWriterTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private void addInitialComponentDependencies(UI ui, UidlWriter uidlWriter) {
    ui.add(new ActualComponent());

    JsonObject response = uidlWriter.createUidl(ui, false);
    Map<String, JsonObject> dependenciesMap = getDependenciesMap(response);

    assertEquals(4, dependenciesMap.size());

    // UI parent first, then UI, then super component's dependencies, then
    // the interfaces and then the component
    assertDependency("super-" + CSS_STYLE_NAME, CSS_STYLE_NAME,
            dependenciesMap);

    assertDependency("anotherinterface-" + CSS_STYLE_NAME, CSS_STYLE_NAME,
            dependenciesMap);

    assertDependency("interface-" + CSS_STYLE_NAME, CSS_STYLE_NAME,
            dependenciesMap);

    assertDependency(CSS_STYLE_NAME, CSS_STYLE_NAME, dependenciesMap);
}
 
Example 4
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void disabledElement_eventHandlerIsNotInvoked() {
    UI ui = new UI();
    ComponentWithMethod component = new ComponentWithMethod();
    ui.add(component);

    component.getElement().setEnabled(false);

    requestInvokeMethod(component);

    Assert.assertFalse(component.isInvoked);
}
 
Example 5
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void doParseTemplate_hasChildTemplateOutsideDomRepeat_elementIsCreated(
        TemplateWithDomRepeat template) {
    UI ui = new UI();
    ui.add(template);

    VirtualChildrenList feature = template.getStateNode()
            .getFeature(VirtualChildrenList.class);
    List<StateNode> templateNodes = new ArrayList<>();
    feature.forEachChild(templateNodes::add);

    assertEquals(1, templateNodes.size());
}
 
Example 6
Source File: ClientCallableHandlersTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void nonTemplateComponentWithoutEventHandler() {
    UI ui = new UI();
    NonTemplateComponentWithoutEventHandler component = new NonTemplateComponentWithoutEventHandler();
    ui.add(component);

    ClientCallableHandlers feature = component.getElement().getNode()
            .getFeature(ClientCallableHandlers.class);
    assertListFeature(feature);
}
 
Example 7
Source File: ClientCallableHandlersTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void nonTemplateComponentWithEventHandler() {
    UI ui = new UI();
    NonTemplateComponentWithEventHandler component = new NonTemplateComponentWithEventHandler();
    ui.add(component);

    ClientCallableHandlers feature = component.getElement().getNode()
            .getFeature(ClientCallableHandlers.class);
    assertListFeature(feature, "publishedMethod1");
}
 
Example 8
Source File: BinderTestBase.java    From flow with Apache License 2.0 5 votes vote down vote up
@Before
public void setUpBase() {
    UI ui = new UI() {
        @Override
        public Locale getLocale() {
            return Locale.US;
        }

    };
    nameField = new TestTextField();
    ageField = new TestTextField();
    ui.add(nameField, ageField);
}
 
Example 9
Source File: EventRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void testElementEventData() throws Exception {
    TestComponent c = new TestComponent();
    Element element = c.getElement();
    UI ui = new UI();
    ui.add(c);
    AtomicInteger invocationData = new AtomicInteger(0);

    element.addEventListener("test-event", e -> invocationData
            .addAndGet((int) e.getEventData().getNumber("nr")));
    JsonObject eventData = Json.createObject();
    eventData.put("nr", 123);
    sendElementEvent(element, ui, "test-event", eventData);
    Assert.assertEquals(123, invocationData.get());
}
 
Example 10
Source File: BinderTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void conversionWithLocaleBasedErrorMessage() {
    TestTextField ageField = new TestTextField();

    String fiError = "VIRHE";
    String otherError = "ERROR";

    StringToIntegerConverter converter = new StringToIntegerConverter(
            context -> context.getLocale().map(Locale::getLanguage)
                    .orElse("en").equals("fi") ? fiError : otherError);

    binder.forField(ageField).withConverter(converter).bind(Person::getAge,
            Person::setAge);
    binder.setBean(item);

    UI testUI = new UI();
    UI.setCurrent(testUI);

    testUI.add(ageField);

    ageField.setValue("not a number");
    assertEquals(otherError, ageField.getErrorMessage());

    testUI.setLocale(new Locale("fi", "FI"));

    // Re-validate to get the error message with correct locale
    binder.validate();
    assertEquals(fiError, ageField.getErrorMessage());
}
 
Example 11
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void syncJSON_jsonIsNotListItemAndNotPropertyValue_propertySetToJSON()
        throws Exception {
    // Let's use element's ElementPropertyMap for testing.
    TestComponent component = new TestComponent();
    Element element = component.getElement();
    UI ui = new UI();
    ui.add(component);

    StateNode node = element.getNode();

    TestComponent anotherComonent = new TestComponent();
    StateNode anotherNode = anotherComonent.getElement().getNode();

    ElementPropertyMap.getModel(node)
            .setUpdateFromClientFilter(name -> true);

    // Use the model node id for JSON object which represents a value to
    // update
    JsonObject json = Json.createObject();
    json.put("nodeId", anotherNode.getId());

    // send sync request
    sendSynchronizePropertyEvent(element, ui, "foo", json);

    Serializable testPropertyValue = node
            .getFeature(ElementPropertyMap.class).getProperty("foo");

    Assert.assertNotSame(anotherNode, testPropertyValue);
    Assert.assertTrue(testPropertyValue instanceof JsonValue);
}
 
Example 12
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void syncJSON_jsonIsPropertyValueOfStateNode_propertySetToNode()
        throws Exception {
    // Let's use element's ElementPropertyMap for testing.
    TestComponent component = new TestComponent();
    Element element = component.getElement();
    UI ui = new UI();
    ui.add(component);

    StateNode node = element.getNode();

    // Set model value directly via ElementPropertyMap
    ElementPropertyMap propertyMap = node
            .getFeature(ElementPropertyMap.class);
    propertyMap.setUpdateFromClientFilter(name -> true);

    ElementPropertyMap modelMap = propertyMap.resolveModelMap("foo");
    // fake StateNode has been created for the model
    StateNode model = modelMap.getNode();
    modelMap.setProperty("bar", "baz");

    // Use the model node id for JSON object which represents a value to
    // update
    JsonObject json = Json.createObject();
    json.put("nodeId", model.getId());

    // send sync request
    sendSynchronizePropertyEvent(element, ui, "foo", json);

    Serializable testPropertyValue = propertyMap.getProperty("foo");

    Assert.assertTrue(testPropertyValue instanceof StateNode);

    StateNode newNode = (StateNode) testPropertyValue;
    Assert.assertSame(model, newNode);
}
 
Example 13
Source File: AbstractListDataViewListenerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void addSizeChangeListener_sizeChanged_listenersAreNotified() {
    String[] items = new String[] { "item1", "item2", "item3", "item4" };
    HasListDataView<String, ? extends AbstractListDataView<String>> component =
            getVerifiedComponent();
    AbstractListDataView<String> dataView = component
            .setItems(new ArrayList<>(Arrays.asList(items)));

    AtomicInteger invocationCounter = new AtomicInteger(0);

    dataView.addSizeChangeListener(
            event -> invocationCounter.incrementAndGet());

    UI ui = new MockUI();
    ui.add((Component) component);

    dataView.setFilter("one"::equals);
    dataView.setFilter(null);
    dataView.addItemAfter("item5", "item4");
    dataView.addItemBefore("item0", "item1");
    dataView.addItem("last");
    dataView.removeItem("item0");

    fakeClientCall(ui);

    Assert.assertEquals(
            "Unexpected count of size change listener invocations occurred",
            1, invocationCounter.get());
}
 
Example 14
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void disabledElement_clientDelegateAllowsRPC_methodIsInvoked() {
    UI ui = new UI();
    EnabledHandler component = new EnabledHandler();
    ui.add(component);

    component.getElement().setEnabled(false);

    Assert.assertFalse(component.isInvoked);

    requestInvokeMethod(component, "operation");

    Assert.assertTrue(component.isInvoked);
}
 
Example 15
Source File: ValueContextTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void getLocale_localeComesFromComponentUI() {
    UI.setCurrent(null);

    UI ui = new UI();
    ui.setLocale(Locale.GERMAN);

    Text text = new Text("");
    ui.add(text);
    ValueContext context = new ValueContext(text);

    Assert.assertEquals(Locale.GERMAN, context.getLocale().get());
}
 
Example 16
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void implicitelyDisabledElement_eventHandlerIsNotInvoked() {
    UI ui = new UI();
    ComponentWithMethod component = new ComponentWithMethod();
    ui.add(component);

    ui.setEnabled(false);

    requestInvokeMethod(component);

    Assert.assertFalse(component.isInvoked);
}
 
Example 17
Source File: PublishedServerEventHandlerRpcHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void enabledElement_methodIsInvoked() {
    UI ui = new UI();
    ComponentWithMethod component = new ComponentWithMethod();
    ui.add(component);

    requestInvokeMethod(component);

    Assert.assertTrue(component.isInvoked);
}
 
Example 18
Source File: UidlWriterTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void checkAllTypesOfDependencies_npmMode() throws Exception {
    UI ui = initializeUIForDependenciesTest(new TestUI());
    UidlWriter uidlWriter = new UidlWriter();
    addInitialComponentDependencies(ui, uidlWriter);

    ui.add(new ComponentWithAllDependencyTypes());
    JsonObject response = uidlWriter.createUidl(ui, false);
    Map<LoadMode, List<JsonObject>> dependenciesMap = Stream
            .of(LoadMode.values())
            .map(mode -> response.getArray(mode.name()))
            .flatMap(JsonUtils::<JsonObject> stream)
            .collect(Collectors.toMap(
                    jsonObject -> LoadMode.valueOf(
                            jsonObject.getString(Dependency.KEY_LOAD_MODE)),
                    Collections::singletonList, (list1, list2) -> {
                        List<JsonObject> result = new ArrayList<>(list1);
                        result.addAll(list2);
                        return result;
                    }));

    assertThat(
            "Dependencies with all types of load mode should be present in this response",
            dependenciesMap.size(), is(LoadMode.values().length));

    List<JsonObject> eagerDependencies = dependenciesMap
            .get(LoadMode.EAGER);
    assertThat("Should have an eager dependency", eagerDependencies,
            hasSize(1));
    assertThat("Eager dependencies should not have inline contents",
            eagerDependencies.stream()
                    .filter(json -> json.hasKey(Dependency.KEY_CONTENTS))
                    .collect(Collectors.toList()),
            hasSize(0));

    JsonObject eagerDependency = eagerDependencies.get(0);
    assertEquals("eager.css",
            eagerDependency.getString(Dependency.KEY_URL));
    assertEquals(Dependency.Type.STYLESHEET, Dependency.Type
            .valueOf(eagerDependency.getString(Dependency.KEY_TYPE)));

    List<JsonObject> lazyDependencies = dependenciesMap.get(LoadMode.LAZY);
    JsonObject lazyDependency = lazyDependencies.get(0);
    assertEquals("lazy.css", lazyDependency.getString(Dependency.KEY_URL));
    assertEquals(Dependency.Type.STYLESHEET, Dependency.Type
            .valueOf(lazyDependency.getString(Dependency.KEY_TYPE)));

    List<JsonObject> inlineDependencies = dependenciesMap
            .get(LoadMode.INLINE);
    assertInlineDependencies(inlineDependencies);
}
 
Example 19
Source File: MapSyncRpcHandlerTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test
public void syncJSON_jsonIsForStateNodeInList_propertySetToStateNodeCopy()
        throws Exception {
    // Let's use element's ElementPropertyMap for testing.
    TestComponent component = new TestComponent();
    Element element = component.getElement();
    UI ui = new UI();
    ui.add(component);

    StateNode node = element.getNode();

    // Set model value directly via ElementPropertyMap
    ElementPropertyMap propertyMap = node
            .getFeature(ElementPropertyMap.class);
    propertyMap.setUpdateFromClientFilter(name -> true);
    ModelList modelList = propertyMap.resolveModelList("foo");
    // fake StateNode has been created for the model
    StateNode item = new StateNode(ElementPropertyMap.class);
    modelList.add(item);
    item.getFeature(ElementPropertyMap.class).setProperty("bar", "baz");

    // Use the model node id for JSON object which represents a value to
    // update
    JsonObject json = Json.createObject();
    json.put("nodeId", item.getId());

    // send sync request
    sendSynchronizePropertyEvent(element, ui, TEST_PROPERTY, json);

    // Now the model node should be copied and available as the
    // TEST_PROPERTY value
    Serializable testPropertyValue = propertyMap.getProperty(TEST_PROPERTY);

    Assert.assertTrue(testPropertyValue instanceof StateNode);

    StateNode newNode = (StateNode) testPropertyValue;
    Assert.assertNotEquals(item.getId(), newNode.getId());

    Assert.assertEquals("baz", newNode.getFeature(ElementPropertyMap.class)
            .getProperty("bar"));
}
 
Example 20
Source File: RouterLinkTest.java    From flow with Apache License 2.0 3 votes vote down vote up
@Test
public void setRoute_attachedLink() {
    UI ui = new UI();

    RouterLink link = new RouterLink();

    ui.add(link);
    link.setRoute(router, TestView.class, "foo");

    Assert.assertTrue(link.getElement().hasAttribute("href"));

    Assert.assertEquals("bar/foo", link.getElement().getAttribute("href"));
}