Andrii Fedorenko
Andrii Fedorenko

Reputation: 152

Invoke bean method on Vaadin component from Singleton

I'm trying to update simple Vaadin UI Component from Singleton:

Here is component:

public class MaintenanceModeLogoutMessageLayout extends HorizontalLayout {

    public MaintenanceModeLogoutMessageLayout() {
       addComponent(new Label("test"));
    }

    public void changeVisibility(final Boolean visible) {
        setVisible(visible);
    }

Here is my singleton, which i need to run on startup

@Singleton
@Startup
public class SingletonTest {

    private void executeMaintenanceModeChange(final Boolean maintenance) {

        try {
            final BeanManager beanManager = InitialContext.doLookup("java:comp/BeanManager");
            final Set<Bean<?>> beans = beanManager.getBeans(MaintenanceModeLogoutMessageLayout.class);
            final Bean<?> bean = beanManager.resolve(beans);

            final CreationalContext<?> cc = beanManager.createCreationalContext(bean);
            final MaintenanceModeLogoutMessageLayout object = (MaintenanceModeLogoutMessageLayout) beanManager.getReference(bean,
                    MaintenanceModeLogoutMessageLayout.class, cc);

            if (object == null) {
                LOG.warning("Cant find any bean for class " + MaintenanceModeLogoutMessageLayout.class.getSimpleName());
                return;
            }

            Method method = bean.getBeanClass().getDeclaredMethod("changeVisibility", Boolean.class);
            method.invoke(object, maintenance);

        } catch (final NamingException | IllegalArgumentException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            LOG.log(Level.SEVERE, "Can't lookup object ");
        }

    }

}

As you can see I'm firing event, trying to find existing bean and invoke method of this object. But the problem is that even if it's current bean there the UI.getCurrent() is null.

if i will make component @UIScoped i'm getting exception

Caused by: java.lang.IllegalStateException: Session data not recoverable for Managed Bean

How can i access UI? And how can i update Vaadin component this way?

Upvotes: 0

Views: 183

Answers (1)

Andr&#233; Schild
Andr&#233; Schild

Reputation: 4754

Your question is a variant of this question, solution is the same.

Vaadin: get reference of UI to change data

Basically you will have multiple UI instances running in your tomcat/servlet engine. (At least one per user/browser)

So you have to broadcast the message to all instances of the UI and then handle it appropriatly.

If it should haven async (Without user action), then you also need to enable push, so that the message is pushed to the client webbrowsers. Otherwise it will only show up on the next user interaction with the vaadin app.

Upvotes: 3

Related Questions