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

The following examples show how to use com.vaadin.flow.component.UI#getCurrent() . 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: NotificationHolder.java    From vaadin-app-layout with Apache License 2.0 6 votes vote down vote up
/**
 * Needs to be called from UI Thread otherwise there will be issues.
 *
 * @param notifications
 */
public void add(T... notifications) {
    if (UI.getCurrent() == null) {
        throw new IllegalStateException("It seems like NotificationHolder::add wasn't called from the UI Thread. This should be done by using \"UI.getCurrent().access(() -> {})\"");
    }
    Arrays.stream(notifications).forEach(notification -> {
        recentNotification = notification;
        this.notifications.add(notification);
        notifyAddListeners(notification);
        if (notificationComponents.stream().noneMatch(NotificationComponent::isDisplayingNotifications)) {
            com.vaadin.flow.component.notification.Notification notificationView = new com.vaadin.flow.component.notification.Notification(getComponent(notification));
            notificationView.setPosition(com.vaadin.flow.component.notification.Notification.Position.TOP_END);
            notificationView.setDuration(2000);
            notificationView.open();
        }
    });
    notifyListeners();
    updateBadgeCaptions();
}
 
Example 2
Source File: EventUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void collectAfterNavigationObservers() {
    UI ui = UI.getCurrent();

    Element menu = new Element("menu");
    menu.appendChild(new AfterObserver().getElement());

    Element node = ui.getElement();
    node.appendChild(new Element("main"), menu);
    Element nested = new Element("nested");
    nested.appendChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);
    Component.from(nested, AfterObserver.class);

    List<AfterNavigationObserver> beforeNavigationObservers = EventUtil
            .collectAfterNavigationObservers(ui);

    Assert.assertEquals("Wrong amount of listener instances found", 2,
            beforeNavigationObservers.size());
}
 
Example 3
Source File: EventUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void collectBeforeNavigationObserversFromUI_elementHasVirtualChildren()
        throws Exception {
    UI ui = UI.getCurrent();
    Element node = ui.getElement();
    node.appendChild(new Element("main"), new Element("menu"));
    Element nested = new Element("nested");
    nested.appendVirtualChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);

    node.getStateProvider().appendVirtualChild(node.getNode(),
            new Element("attached-by-id"), NodeProperties.INJECT_BY_ID,
            "id");

    Component.from(nested, LeaveObserver.class);

    List<BeforeLeaveObserver> beforeNavigationObservers = EventUtil
            .collectBeforeLeaveObservers(ui);

    Assert.assertEquals("Wrong amount of listener instances found", 1,
            beforeNavigationObservers.size());
}
 
Example 4
Source File: EventUtilTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void collectBeforeNavigationObserversFromUI() throws Exception {
    UI ui = UI.getCurrent();
    Element node = ui.getElement();
    node.appendChild(new Element("main"), new Element("menu"));
    Element nested = new Element("nested");
    nested.appendChild(new Element("nested-child"),
            new Element("nested-child-2"));

    node.appendChild(nested);
    Component.from(nested, LeaveObserver.class);

    List<BeforeLeaveObserver> beforeNavigationObservers = EventUtil
            .collectBeforeLeaveObservers(ui);

    Assert.assertEquals("Wrong amount of listener instances found", 1,
            beforeNavigationObservers.size());
}
 
Example 5
Source File: JavaScriptBootstrapHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_attachViewTo_UiContainer() throws Exception {
    VaadinRequest request = mocks.createRequest(mocks, "/foo/?v-r=init&foo");
    jsInitHandler.handleRequest(session, request, response);

    JavaScriptBootstrapUI ui = (JavaScriptBootstrapUI) UI.getCurrent();
    ui.connectClient("a-tag", "an-id", "a-route");

    TestNodeVisitor visitor = new TestNodeVisitor(true);
    BasicElementStateProvider.get().visit(ui.getElement().getNode(), visitor);

    Assert.assertTrue(hasNodeTag(visitor, "^<body>.*", ElementType.REGULAR));
    Assert.assertTrue(hasNodeTag(visitor, "^<a-tag>.*", ElementType.VIRTUAL_ATTACHED));
    Assert.assertTrue(hasNodeTag(visitor, "^<div>.*", ElementType.REGULAR));
    Assert.assertTrue(
            hasNodeTag(visitor, "^<div>.*Could not navigate to 'a-route'.*",
                    ElementType.REGULAR));

}
 
Example 6
Source File: JavaScriptBootstrapHandlerTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void should_attachViewTo_Body_when_location() throws Exception {

    VaadinRequest request = mocks.createRequest(mocks, "/foo/?v-r=init&location=%2Fbar%3Fpar1%26par2");

    jsInitHandler.handleRequest(session, request, response);

    JavaScriptBootstrapUI ui = (JavaScriptBootstrapUI) UI.getCurrent();

    TestNodeVisitor visitor = new TestNodeVisitor(true);
    BasicElementStateProvider.get().visit(ui.getElement().getNode(), visitor);

    Assert.assertTrue(hasNodeTag(visitor, "^<body>.*", ElementType.REGULAR));
    Assert.assertTrue(hasNodeTag(visitor, "^<div>.*", ElementType.REGULAR));
    Assert.assertTrue(
            hasNodeTag(visitor, "^<div>.*Could not navigate to 'bar'.*",
                    ElementType.REGULAR));

    Mockito.verify(session, Mockito.times(1)).setAttribute(SERVER_ROUTING, Boolean.TRUE);
}
 
Example 7
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 8
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 9
Source File: UIAttributes.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
/**
 * Needs to be called from the UI Thread.
 * @param type
 * @param <T>
 * @return
 */
public static <T extends Serializable> T get(Class<T> type) {
    UIAttributes session = getSession();
    UI ui = UI.getCurrent();
    if (!session.map.containsKey(UI.getCurrent())) {
        session.map.put(ui, new HashMap<>());
    }
    return (T) session.map.get(ui).get(type);
}
 
Example 10
Source File: ValueContext.java    From flow with Apache License 2.0 5 votes vote down vote up
private Locale findLocale(Component component) {
    if (component != null && component.getUI().isPresent()) {
        return component.getUI().get().getLocale();
    }
    Locale locale = null;
    if (UI.getCurrent() != null) {
        locale = UI.getCurrent().getLocale();
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    return locale;
}
 
Example 11
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 12
Source File: RouterTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeEnter(BeforeEnterEvent event) {
    events.add(event);
    UI ui = UI.getCurrent();
    ui.getRouter().navigate(ui, new Location("loop"),
            NavigationTrigger.PROGRAMMATIC);
}
 
Example 13
Source File: NotificationHolder.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
public void remove(T notification) {
    if (UI.getCurrent() == null) {
        throw new IllegalStateException("It seems like NotificationHolder::remove wasn't called from the UI Thread. This should be done by using \"UI.getCurrent().access(() -> {})\"");
    }
    notifications.remove(notification);
    notifyListeners();
    notifyRemoveListeners(notification);
    updateBadgeCaptions();
}
 
Example 14
Source File: NotificationHolder.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
public void clearNotifications() {
    if (UI.getCurrent() == null) {
        throw new IllegalStateException("It seems like NotificationHolder::clearNotifications wasn't called from the UI Thread. This should be done by using \"UI.getCurrent().access(() -> {})\"");
    }
    notifications.clear();
    notifyListeners();
    updateBadgeCaptions();
}
 
Example 15
Source File: UIAttributes.java    From vaadin-app-layout with Apache License 2.0 5 votes vote down vote up
/**
 *  Needs to be called from the UI Thread.
 * @param type
 * @param value
 * @param <T>
 */
public static <T extends Serializable> void set(Class<T> type, T value) {
    UIAttributes session = getSession();
    UI ui = UI.getCurrent();
    if (!session.map.containsKey(UI.getCurrent())) {
        session.map.put(ui, new HashMap<>());
    }
    session.map.get(ui).put(type, value);
}
 
Example 16
Source File: MenuTemplate.java    From radman with MIT License 5 votes vote down vote up
@EventHandler
private void logout() {
    SecurityContextHolder.clearContext();
    UI ui = UI.getCurrent();
    ui.getSession().getSession().invalidate();
    ui.getSession().close();
    ui.getPage().reload();
}
 
Example 17
Source File: IndexHtmlRequestHandler.java    From flow with Apache License 2.0 4 votes vote down vote up
@Override
public boolean synchronizedHandleRequest(VaadinSession session,
        VaadinRequest request, VaadinResponse response) throws IOException {
    Document indexDocument = getIndexHtmlDocument(request);

    prependBaseHref(request, indexDocument);

    JsonObject initialJson = Json.createObject();

    if (request.getService().getBootstrapInitialPredicate()
            .includeInitialUidl(request)) {
        includeInitialUidl(initialJson, session, request, response);

        indexHtmlResponse = new IndexHtmlResponse(request, response, indexDocument, UI.getCurrent());

        // App might be using classic server-routing, which is true
        // unless we detect a call to JavaScriptBootstrapUI.connectClient
        session.setAttribute(SERVER_ROUTING, Boolean.TRUE);
    } else {
        indexHtmlResponse = new IndexHtmlResponse(request, response, indexDocument);
    }

    addInitialFlow(initialJson, indexDocument, session);

    configureErrorDialogStyles(indexDocument);

    showWebpackErrors(indexDocument);

    response.setContentType(CONTENT_TYPE_TEXT_HTML_UTF_8);

    VaadinContext context = session.getService().getContext();
    AppShellRegistry registry = AppShellRegistry.getInstance(context);

    DeploymentConfiguration config = session.getConfiguration();
    if (!config.isProductionMode()) {
        UsageStatisticsExporter.exportUsageStatisticsToDocument(indexDocument);
    }

    // modify the page based on the @PWA annotation
    setupPwa(indexDocument, session.getService());

    // modify the page based on the @Meta, @ViewPort, @BodySize and @Inline annotations
    // and on the AppShellConfigurator
    registry.modifyIndexHtml(indexDocument, request);

    // modify the page based on registered IndexHtmlRequestListener:s
    request.getService().modifyIndexHtmlResponse(indexHtmlResponse);

    try {
        response.getOutputStream()
                .write(indexDocument.html().getBytes(UTF_8));
    } catch (IOException e) {
        getLogger().error("Error writing 'index.html' to response", e);
        return false;
    }
    return true;
}
 
Example 18
Source File: NotificationHolder.java    From vaadin-app-layout with Apache License 2.0 4 votes vote down vote up
public void updateBadgeCaptions() {
    if (UI.getCurrent() == null) {
        throw new IllegalStateException("It seems like NotificationHolder::updateBadgeCaptions wasn't called from the UI Thread. This should be done by using \"UI.getCurrent().access(() -> {})\"");
    }
    badgeHolderComponents.forEach(this::updateBadgeCaption);
}
 
Example 19
Source File: MakeComponentVisibleWithPushUI.java    From flow with Apache License 2.0 3 votes vote down vote up
private void doUpdate() {

        cancelSuggestThread();

        input.setVisible(false);

        UI ui = UI.getCurrent();
        searchThread = new SearchThread(ui);
        searchThread.start();
    }