com.vaadin.flow.component.UI Java Examples

The following examples show how to use com.vaadin.flow.component.UI. 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: BootstrapHandlerPushConfigurationTest.java    From flow with Apache License 2.0 6 votes vote down vote up
private void assertPushConfigurationForComponent(
        Class<? extends Component> annotatedClazz,
        Class<? extends PushConnection> pushConnectionType)
        throws InvalidRouteConfigurationException {
    BootstrapHandler bootstrapHandler = new BootstrapHandler();
    VaadinResponse response = mock(VaadinResponse.class);
    RouteConfiguration routeConfiguration = RouteConfiguration
            .forRegistry(service.getRouteRegistry());
    routeConfiguration.update(() -> {
        routeConfiguration.getHandledRegistry().clean();
        routeConfiguration.setAnnotatedRoute(annotatedClazz);
    });

    final BootstrapHandler.BootstrapContext context = bootstrapHandler
            .createAndInitUI(UI.class, createVaadinRequest(), response,
                    session);
    Push pushAnnotation = annotatedClazz.getAnnotation(Push.class);
    Assert.assertNotNull("Should have @Push annotated component",
            pushAnnotation);
    PushConfiguration pushConfiguration = context.getUI()
            .getPushConfiguration();
    assertPushConfiguration(pushConfiguration, pushAnnotation);
    assertThat(context.getUI().getInternals().getPushConnection(),
            instanceOf(pushConnectionType));
}
 
Example #2
Source File: ElementTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testDetachListener_eventOrder_childFirst() {
    Element body = new UI().getElement();
    Element parent = ElementFactory.createDiv();
    Element child = ElementFactory.createDiv();
    parent.appendChild(child);
    body.appendChild(parent);

    AtomicBoolean parentDetached = new AtomicBoolean();
    AtomicBoolean childDetached = new AtomicBoolean();

    child.addDetachListener(event -> {
        childDetached.set(true);
        Assert.assertFalse(parentDetached.get());
    });
    parent.addDetachListener(event -> {
        parentDetached.set(true);
        Assert.assertTrue(childDetached.get());
    });

    body.removeAllChildren();

    Assert.assertTrue(parentDetached.get());
    Assert.assertTrue(childDetached.get());
}
 
Example #3
Source File: IndexHtmlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_use_client_routing_when_there_is_a_router_call()
        throws IOException {

    deploymentConfiguration.setEagerServerLoad(true);

    indexHtmlRequestHandler.synchronizedHandleRequest(session,
            createVaadinRequest("/"), response);

    Mockito.verify(session, Mockito.times(1)).setAttribute(SERVER_ROUTING,
            Boolean.TRUE);
    Mockito.verify(session, Mockito.times(0)).setAttribute(SERVER_ROUTING,
            Boolean.FALSE);

    ((JavaScriptBootstrapUI) UI.getCurrent()).connectClient("foo", "bar",
            "/foo");

    Mockito.verify(session, Mockito.times(1)).setAttribute(SERVER_ROUTING,
            Boolean.FALSE);
}
 
Example #4
Source File: PolymerTemplateTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void initModel_sendUpdatableProperties() {
    UI ui = UI.getCurrent();
    InitModelTemplate template = new InitModelTemplate();

    ui.add(template);

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

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

    Serializable[] params = executionParams.get(0);
    JsonArray properties = (JsonArray) params[1];
    Assert.assertEquals(2, properties.length());

    Set<String> props = new HashSet<>();
    props.add(properties.get(0).asString());
    props.add(properties.get(1).asString());
    // all model properties except 'list' which has no getter
    Assert.assertTrue(props.contains("message"));
    Assert.assertTrue(props.contains("title"));
}
 
Example #5
Source File: SockJSPushConnection.java    From vertx-vaadin with MIT License 6 votes vote down vote up
/**
 * Pushes pending state changes and client RPC calls to the client. If
 * {@code isConnected()} is false, defers the push until a connection is
 * established.
 *
 * @param async True if this push asynchronously originates from the server,
 *              false if it is a response to a client request.
 */
void push(boolean async) {
    if (!isConnected()) {
        if (async && state != State.RESPONSE_PENDING) {
            state = State.PUSH_PENDING;
        } else {
            state = State.RESPONSE_PENDING;
        }
    } else {
        try {
            UI ui = VaadinSession.getCurrent().getUIById(this.uiId);
            JsonObject response = new UidlWriter().createUidl(ui, async);
            sendMessage("for(;;);[" + response.toJson() + "]");
        } catch (Exception e) {
            throw new PushException("Push failed", e);
        }
    }
}
 
Example #6
Source File: ElementTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void setResourceAttribute_elementIsAttached_setAnotherResource()
        throws URISyntaxException {
    UI ui = createUI();
    UI.setCurrent(ui);
    StreamResource resource = createEmptyResource("resource1");
    ui.getElement().setAttribute("foo", resource);

    String uri = ui.getElement().getAttribute("foo");
    Optional<StreamResource> res = ui.getSession().getResourceRegistry()
            .getResource(StreamResource.class, new URI(uri));
    Assert.assertTrue(res.isPresent());

    String resName = "resource2";
    ui.getElement().setAttribute("foo", createEmptyResource(resName));
    res = ui.getSession().getResourceRegistry()
            .getResource(StreamResource.class, new URI(uri));
    Assert.assertFalse(res.isPresent());

    Assert.assertTrue(ui.getElement().hasAttribute("foo"));
    Assert.assertTrue(
            ui.getElement().getAttribute("foo").endsWith(resName));
}
 
Example #7
Source File: RouterLinkView.java    From flow with Apache License 2.0 6 votes vote down vote up
public RouterLinkView() {
    Element bodyElement = getElement();
    bodyElement.getStyle().set("margin", "1em");

    Element location = ElementFactory.createDiv("no location")
            .setAttribute("id", "location");

    Element queryParams = ElementFactory.createDiv("no queryParams")
            .setAttribute("id", "queryParams");

    bodyElement.appendChild(location, new Element("p"));
    bodyElement.appendChild(queryParams, new Element("p"));

    addLinks();

    getPage().getHistory().setHistoryStateChangeHandler(e -> {
        location.setText(e.getLocation().getPath());
        queryParams.setText(
                e.getLocation().getQueryParameters().getQueryString());
        if (e.getState().isPresent())
            UI.getCurrent().getPage().getHistory().pushState(null,
                    ((JsonObject) e.getState().get()).getString("href"));
    });

    addImageLink();
}
 
Example #8
Source File: CustomScrollCallbacksView.java    From flow with Apache License 2.0 6 votes vote down vote up
public CustomScrollCallbacksView() {
    viewName.setId("view");

    log.setId("log");
    log.getStyle().set("white-space", "pre");

    UI.getCurrent().getPage().executeJs(
            "window.Vaadin.Flow.setScrollPosition = function(xAndY) { $0.textContent += JSON.stringify(xAndY) + '\\n' }",
            log);
    UI.getCurrent().getPage().executeJs(
            "window.Vaadin.Flow.getScrollPosition = function() { return [42, -window.pageYOffset] }");

    RouterLink navigate = new RouterLink("Navigate",
            CustomScrollCallbacksView.class, "navigated");
    navigate.setId("navigate");

    Anchor back = new Anchor("javascript:history.go(-1)", "Back");
    back.setId("back");

    add(viewName, log, new Span("Scroll down to see navigation actions"),
            ScrollView.createSpacerDiv(2000), navigate, back);
}
 
Example #9
Source File: DeploymentConfigurationFactoryTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void servletWithNoEnclosingUI_hasDefaultUiInConfig()
        throws Exception {
    Class<NoSettings> servlet = NoSettings.class;

    Map<String, String> servletConfigParams = new HashMap<>(
            defaultServletParams);

    DeploymentConfiguration config = DeploymentConfigurationFactory
            .createDeploymentConfiguration(servlet, createVaadinConfigMock(
                    servletConfigParams, emptyMap()));

    Class<?> notUiClass = servlet.getEnclosingClass();
    assertFalse(String.format(
            "Servlet '%s' should not have its enclosing class to be UI subclass, but got: '%s'",
            notUiClass, servlet), UI.class.isAssignableFrom(notUiClass));
    assertEquals(String.format(
            "Expected DeploymentConfiguration for servlet '%s' to have its enclosing UI class",
            servlet), UI.class.getName(), config.getUIClassName());
}
 
Example #10
Source File: InitialExtendedClientDetailsView.java    From flow with Apache License 2.0 6 votes vote down vote up
public InitialExtendedClientDetailsView() {
    UI.getCurrent().getPage().retrieveExtendedClientDetails(details ->{
        addSpan("screenWidth", details.getScreenWidth());
        addSpan("screenHeight", details.getScreenHeight());
        addSpan("windowInnerWidth",details.getWindowInnerWidth());
        addSpan("windowInnerHeight",details.getWindowInnerHeight());
        addSpan("bodyClientWidth",details.getBodyClientWidth());
        addSpan("bodyClientHeight",details.getBodyClientHeight());
        addSpan("timezoneOffset", details.getTimezoneOffset());
        addSpan("timeZoneId", details.getTimeZoneId());
        addSpan("rawTimezoneOffset", details.getRawTimezoneOffset());
        addSpan("DSTSavings", details.getDSTSavings());
        addSpan("DSTInEffect", details.isDSTInEffect());
        addSpan("currentDate", details.getCurrentDate());
        addSpan("touchDevice", details.isTouchDevice());
        addSpan("devicePixelRatio", details.getDevicePixelRatio());
        addSpan("windowName", details.getWindowName());
    });
}
 
Example #11
Source File: ElementTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void setResourceAttributeSeveralTimes_elementIsNotAttached_elementHasAttribute() {
    UI.setCurrent(createUI());
    Element element = ElementFactory.createDiv();
    String resName = "resource";
    StreamResource resource = createEmptyResource(resName);
    element.setAttribute("foo", resource);

    Assert.assertTrue(element.hasAttribute("foo"));

    resName = "resource1";
    resource = createEmptyResource(resName);
    element.setAttribute("foo", resource);

    Assert.assertTrue(element.hasAttribute("foo"));

    Assert.assertTrue(element.getAttribute("foo").endsWith(resName));
}
 
Example #12
Source File: DeploymentConfigurationFactoryTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void servletWithEnclosingUI_hasItsNameInConfig() throws Exception {
    Class<TestUI.ServletWithEnclosingUi> servlet = TestUI.ServletWithEnclosingUi.class;

    Map<String, String> servletConfigParams = new HashMap<>(
            new HashMap<>(defaultServletParams));

    DeploymentConfiguration config = DeploymentConfigurationFactory
            .createDeploymentConfiguration(servlet,
                    createVaadinConfigMock(servletConfigParams,
                            Collections.singletonMap(PARAM_TOKEN_FILE,
                                    tokenFile.getPath())));

    Class<?> customUiClass = servlet.getEnclosingClass();
    assertTrue(String.format(
            "Servlet '%s' should have its enclosing class to be UI subclass, but got: '%s'",
            customUiClass, servlet),
            UI.class.isAssignableFrom(customUiClass));
    assertEquals(String.format(
            "Expected DeploymentConfiguration for servlet '%s' to have its enclosing UI class",
            servlet), customUiClass.getName(), config.getUIClassName());
}
 
Example #13
Source File: IndexHtmlRequestHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_initialize_UI_and_add_initialUidl_when_invalid_route()
        throws IOException {
    deploymentConfiguration.setEagerServerLoad(true);

    service.setBootstrapInitialPredicate(request -> {
        return request.getPathInfo().equals("/");
    });

    indexHtmlRequestHandler.synchronizedHandleRequest(session,
            createVaadinRequest("/foo"), response);
    String indexHtml = responseOutput
            .toString(StandardCharsets.UTF_8.name());
    Document document = Jsoup.parse(indexHtml);

    Elements scripts = document.head().getElementsByTag("script");
    Assert.assertEquals(1, scripts.size());
    Assert.assertEquals("window.Vaadin = {TypeScript: {}};",
            scripts.get(0).childNode(0).toString());
    Assert.assertEquals("", scripts.get(0).attr("initial"));
    Assert.assertNull(UI.getCurrent());
}
 
Example #14
Source File: ElementTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void testAttachDetach_elementMoved_bothEventsTriggered() {
    Element body = new UI().getElement();
    Element parent = ElementFactory.createDiv();
    Element child = ElementFactory.createDiv();

    parent.appendChild(child);
    body.appendChild(parent);

    AtomicBoolean attached = new AtomicBoolean();
    AtomicBoolean detached = new AtomicBoolean();

    child.addAttachListener(event -> {
        attached.set(true);
        Assert.assertTrue(detached.get());
    });
    child.addDetachListener(event -> {
        detached.set(true);
        Assert.assertFalse(attached.get());
    });

    body.appendChild(child);

    Assert.assertTrue(attached.get());
    Assert.assertTrue(detached.get());
}
 
Example #15
Source File: RendererUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void registerEventHandlers_elementsAreAlreadyAttached_setupEvenHandlers() {
    UI ui = new TestUI();

    Element contentTemplate = new Element(Tag.DIV);
    Element templateDataHost = new Element(Tag.SPAN);
    attachElements(ui, contentTemplate, templateDataHost);

    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    Renderer<String> renderer = new Renderer<>();

    renderer.setEventHandler("foo", value -> {
    });

    RendererUtil.registerEventHandlers(renderer, contentTemplate,
            templateDataHost, ValueProvider.identity());

    assertJSExecutions(ui, internals, contentTemplate, templateDataHost);
}
 
Example #16
Source File: BootstrapHandler.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
        VaadinRequest request, VaadinResponse response) throws IOException {
    // Find UI class
    Class<? extends UI> uiClass = getUIClass(request);

    BootstrapContext context = createAndInitUI(uiClass, request, response,
            session);

    HandlerHelper.setResponseNoCacheHeaders(response::setHeader,
            response::setDateHeader);

    Document document = pageBuilder.getBootstrapPage(context);

    writeBootstrapPage(response, document.outerHtml());

    return true;
}
 
Example #17
Source File: VaadinService.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the {@link UI} that belongs to the provided request. This is
 * generally only supported for UIDL requests as other request types are not
 * related to any particular UI or have the UI information encoded in a
 * non-standard way. The returned UI is also set as the current UI (
 * {@link UI#setCurrent(UI)}).
 *
 * @param request
 *            the request for which a UI is desired
 * @return the UI belonging to the request or null if no UI is found
 */
public UI findUI(VaadinRequest request) {
    // getForSession asserts that the lock is held
    VaadinSession session = loadSession(request.getWrappedSession());

    // Get UI id from the request
    String uiIdString = request
            .getParameter(ApplicationConstants.UI_ID_PARAMETER);
    UI ui = null;
    if (uiIdString != null && session != null) {
        int uiId = Integer.parseInt(uiIdString);
        ui = session.getUIById(uiId);
    }

    UI.setCurrent(ui);
    return ui;
}
 
Example #18
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 #19
Source File: Binder.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Finds an appropriate locale to be used in conversion and validation.
 *
 * @return the found locale, not null
 */
protected static Locale findLocale() {
    Locale locale = null;
    if (UI.getCurrent() != null) {
        locale = UI.getCurrent().getLocale();
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    return locale;
}
 
Example #20
Source File: ComponentRendererTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void templateRenderered_childAttachedBeforeParent() {
    UI ui = new TestUI();
    TestUIInternals internals = (TestUIInternals) ui.getInternals();

    ComponentRenderer<TestLabel, String> renderer = new ComponentRenderer<>(
            e -> (new TestLabel()));

    Element containerParent = new Element("div");
    Element container = new Element("div");
    KeyMapper<String> keyMapper = new KeyMapper<>();

    ComponentDataGenerator<String> rendering = (ComponentDataGenerator<String>) renderer
            .render(container, keyMapper);

    containerParent.getNode().runWhenAttached(
            ui2 -> ui2.getInternals().getStateTree()
                    .beforeClientResponse(containerParent.getNode(),
                            context -> {
                                // if nodeid is null then the component won't be rendered correctly
                                Assert.assertNotNull(
                                        "NodeIdPropertyName should not be null",
                                        rendering.getNodeIdPropertyName());
                                JsonObject value = Json.createObject();
                                rendering.generateData("item", value);
                                Assert.assertEquals(
                                        "generateData should add one element in the jsonobject",
                                        1, value.keys().length);
                            }));
    // attach the child (ex: container) before the parent (ex: grid)
    attachElement(ui, container);
    attachElement(ui, containerParent);

    internals.getStateTree().runExecutionsBeforeClientResponse();

}
 
Example #21
Source File: MyUIInitListener.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void uiInit(UIInitEvent event) {
    event.getSource().addUIInitListener(uiEvent -> {
        final UI ui = uiEvent.getUI();
        ui.add(new MyComponent());
    });
}
 
Example #22
Source File: RouteUtil.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Get the top most parent layout for navigation target according to the
 * {@link Route} or {@link RouteAlias} annotation. Also handles non route
 * targets with {@link ParentLayout}.
 *
 * @param component
 *            navigation target to get top most parent for
 * @param path
 *            path used to get navigation target so we know which annotation
 *            to handle or null for error views.
 * @return top parent layout for target or null if none found
 */
public static Class<? extends RouterLayout> getTopParentLayout(
        final Class<?> component, final String path) {
    if (path == null) {
        Optional<ParentLayout> parentLayout = AnnotationReader
                .getAnnotationFor(component, ParentLayout.class);
        if (parentLayout.isPresent()) {
            return recurseToTopLayout(parentLayout.get().value());
        }
        // No need to check for Route or RouteAlias as the path is null
        return null;
    }

    Optional<Route> route = AnnotationReader.getAnnotationFor(component,
            Route.class);
    List<RouteAlias> routeAliases = AnnotationReader
            .getAnnotationsFor(component, RouteAlias.class);
    if (route.isPresent()
            && path.equals(getRoutePath(component, route.get()))
            && !route.get().layout().equals(UI.class)) {
        return recurseToTopLayout(route.get().layout());
    } else {
        Optional<RouteAlias> matchingRoute = getMatchingRouteAlias(
                component, path, routeAliases);
        if (matchingRoute.isPresent()) {
            return recurseToTopLayout(matchingRoute.get().layout());
        }
    }

    return null;
}
 
Example #23
Source File: NodeMapTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void put_sameValue_alwaysProduceChange_nodeIsDirty() {
    UI ui = new UI();
    StateNode node = new StateNode(ElementPropertyMap.class);
    StateTree tree = ui.getInternals().getStateTree();
    tree.getRootNode().getFeature(ElementChildrenList.class).add(node);
    AlwaysProduceChangeMap map = new AlwaysProduceChangeMap(node);

    // clear dirty nodes
    tree.collectChanges(change -> {
    });

    map.put("foo", "bar");

    Set<StateNode> nodes = tree.collectDirtyNodes();
    Assert.assertTrue(nodes.contains(node));

    // clear dirty nodes
    tree.collectChanges(change -> {
    });

    Assert.assertTrue(tree.collectDirtyNodes().isEmpty());

    // set once again the same value
    map.put("foo", "bar");

    nodes = tree.collectDirtyNodes();
    Assert.assertTrue(nodes.contains(node));
}
 
Example #24
Source File: PreserveOnRefreshView.java    From flow with Apache License 2.0 5 votes vote down vote up
public PreserveOnRefreshView() {
    // create unique content for this instance
    final String uniqueId = Long.toString(new Random().nextInt());

    final Div componentId = new Div();
    componentId.setId(COMPONENT_ID);
    componentId.setText(uniqueId);
    add(componentId);

    // add an element to keep track of number of attach events
    attachCounter = new Div();
    attachCounter.setId(ATTACHCOUNTER_ID);
    attachCounter.setText("0");
    add(attachCounter);

    // also add an element as a separate UI child. This is expected to be
    // transferred on refresh (mimicking dialogs and notifications)
    final Element looseElement = new Element("div");
    looseElement.setProperty("id", NOTIFICATION_ID);
    looseElement.setText(uniqueId);
    UI.getCurrent().getElement().insertChild(0, looseElement);

    StreamResource resource = new StreamResource("filename",
            () -> new ByteArrayInputStream(
                    "foo".getBytes(StandardCharsets.UTF_8)));
    Anchor download = new Anchor("", "Download file");
    download.setHref(resource);
    download.setId("link");
    add(download);
}
 
Example #25
Source File: ElementTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void setResourceAttribute_elementIsAttached_setRawAttribute()
        throws URISyntaxException, InterruptedException {
    UI ui = createUI();
    UI.setCurrent(ui);
    StreamResource resource = createEmptyResource("resource");
    ui.getElement().setAttribute("foo", resource);

    String uri = ui.getElement().getAttribute("foo");
    Optional<StreamResource> res = ui.getSession().getResourceRegistry()
            .getResource(StreamResource.class, new URI(uri));
    Assert.assertTrue(res.isPresent());
    res = null;

    WeakReference<StreamResource> ref = new WeakReference<>(resource);
    resource = null;

    ui.getElement().setAttribute("foo", "bar");

    TestUtil.isGarbageCollected(ref);
    res = ui.getSession().getResourceRegistry()
            .getResource(StreamResource.class, new URI(uri));

    Assert.assertFalse(res.isPresent());
    Assert.assertTrue(ui.getElement().hasAttribute("foo"));
    Assert.assertTrue(ui.getElement().getAttribute("foo").equals("bar"));
}
 
Example #26
Source File: ContextInlineApiView.java    From flow with Apache License 2.0 5 votes vote down vote up
public ContextInlineApiView() {
    setId("template");
    UI.getCurrent().getPage().addJavaScript("/components/context-inline.js",
            LoadMode.INLINE);
    UI.getCurrent().getPage().addStyleSheet(
            "/components/context-inline.css", LoadMode.INLINE);
}
 
Example #27
Source File: ElementTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void setResourceAttribute_attachElement_setAnotherResource()
        throws URISyntaxException, InterruptedException {
    UI ui = createUI();
    UI.setCurrent(ui);

    StreamResource resource = createEmptyResource("resource1");
    Element element = ElementFactory.createDiv();
    element.setAttribute("foo", resource);

    WeakReference<StreamResource> ref = new WeakReference<>(resource);
    resource = null;

    String resName = "resource2";
    element.setAttribute("foo", createEmptyResource(resName));

    ui.getElement().appendChild(element);

    Assert.assertTrue(element.hasAttribute("foo"));

    String uri = element.getAttribute("foo");
    Optional<StreamResource> res = ui.getSession().getResourceRegistry()
            .getResource(StreamResource.class, new URI(uri));
    Assert.assertTrue(res.isPresent());
    Assert.assertTrue(uri.endsWith(resName));

    // allow GC to collect element and all its (detach) listeners
    element = null;

    TestUtil.isGarbageCollected(ref);
}
 
Example #28
Source File: AbstractRpcInvocationHandlerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void handleVisibleAndEnabledNode_nodeIsHandled() {
    UI ui = new UI();

    Element element = createRpcInvocationData(ui, null);

    Assert.assertSame(element.getNode(), handler.node);
}
 
Example #29
Source File: ShadowRootTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void detachListener_parentDetach_childListenersTriggered() {
    Element body = new UI().getElement();
    Element parent = ElementFactory.createDiv();
    Element child = ElementFactory.createDiv();
    Element grandChild = ElementFactory.createDiv();

    AtomicInteger triggered = new AtomicInteger();

    Registration registrationHandle = child.addDetachListener(event -> {
        triggered.addAndGet(1);
        Assert.assertEquals(child, event.getSource());
    });

    grandChild.addDetachListener(event -> {
        triggered.addAndGet(1);
        Assert.assertEquals(grandChild, event.getSource());
    });

    child.appendChild(grandChild);
    parent.attachShadow().appendChild(child);
    body.appendChild(parent);

    Assert.assertEquals(triggered.get(), 0);

    body.removeAllChildren();
    Assert.assertEquals(triggered.get(), 2);

    body.appendChild(parent);
    body.removeAllChildren();

    Assert.assertEquals(triggered.get(), 4);

    body.appendChild(parent);
    registrationHandle.remove();

    body.removeAllChildren();

    Assert.assertEquals(triggered.get(), 5);
}
 
Example #30
Source File: ElementTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void callFunctionOnProperty() {
    UI ui = new MockUI();
    Element element = ElementFactory.createDiv();
    element.callJsFunction("property.method");
    ui.getElement().appendChild(element);
    ui.getInternals().getStateTree().runExecutionsBeforeClientResponse();

    assertPendingJs(ui, "return $0.property.method()", element);
}