Class UI

    • Constructor Detail

      • UI

        public UI()
        Creates a new empty UI.
      • UI

        protected UI​(UIInternalUpdater internalsHandler)
        Create a new empty UI with a custom UIInternalUpdater implementation.
        Parameters:
        internalsHandler - an implementation of UIInternalsHandler.
    • Method Detail

      • getSession

        public VaadinSession getSession()
        Gets the VaadinSession to which this UI is attached.

        The method will return null if the UI is not currently attached to a VaadinSession.

        Getting a null value is often a problem in constructors of regular components and in the initializers of custom composite components. A standard workaround is to use VaadinSession.getCurrent() to retrieve the application instance that the current request relates to. Another way is to move the problematic initialization to onAttach(AttachEvent), as described in the documentation of the method.

        Returns:
        the parent application of the component or null.
        See Also:
        onAttach(AttachEvent)
      • getUIId

        public int getUIId()
        Gets the id of the UI, used to identify this UI within its application when processing requests. The UI id should be present in every request to the server that originates from this UI. VaadinService.findUI(VaadinRequest) uses this id to find the route to which the request belongs.

        This method is not intended to be overridden. If it is overridden, care should be taken since this method might be called in situations where getCurrent() does not return this UI.

        Returns:
        the id of this UI
      • doInit

        public void doInit​(VaadinRequest request,
                           int uiId)
        Internal initialization method, should not be overridden. This method is not declared as final because that would break compatibility with e.g. CDI.
        Parameters:
        request - the initialization request
        uiId - the id of the new ui
        See Also:
        getUIId()
      • init

        protected void init​(VaadinRequest request)
        Initializes this UI. This method is intended to be overridden by subclasses to build the view if Router is not used. The method can also be used to configure non-component functionality. Performing the initialization in a constructor is not suggested as the state of the UI is not properly set up when the constructor is invoked.

        The provided VaadinRequest can be used to get information about the request that caused this UI to be created.

        Parameters:
        request - the Vaadin request that caused this UI to be created
      • setCurrent

        public static void setCurrent​(UI ui)
        Sets the thread local for the current UI. This method is used by the framework to set the current application whenever a new request is processed and it is cleared when the request has been processed.

        The application developer can also use this method to define the current UI outside the normal request handling, e.g. when initiating custom background threads.

        The UI is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.

        Parameters:
        ui - the UI to register as the current UI
        See Also:
        getCurrent(), ThreadLocal
      • getCurrent

        public static UI getCurrent()
        Gets the currently used UI. The current UI is automatically defined when processing requests to the server. In other cases, (e.g. from background threads), the current UI is not automatically defined.

        The UI is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.

        Returns:
        the current UI instance if available, otherwise null
        See Also:
        setCurrent(UI)
      • close

        public void close()
        Marks this UI to be detached from the session at the end of the current request, or the next request if there is no current request (if called from a background thread, for instance.)

        The UI is detached after the response is sent, so in the current request it can still update the client side normally. However, after the response any new requests from the client side to this UI will cause an error, so usually the client should be asked, for instance, to reload the page (serving a fresh UI instance), to close the page, or to navigate somewhere else.

        Note that this method is strictly for users to explicitly signal the framework that the UI should be detached. Overriding it is not a reliable way to catch UIs that are to be detached. Instead, #onDetach(DetachEvent) should be overridden.

      • isClosing

        public boolean isClosing()
        Returns whether this UI is marked as closed and is to be detached.

        This method is not intended to be overridden. If it is overridden, care should be taken since this method might be called in situations where getCurrent() does not return this UI.

        Returns:
        whether this UI is closing.
        See Also:
        close()
      • onAttach

        protected void onAttach​(AttachEvent attachEvent)
        Called after the UI is added to the session. A UI instance is attached exactly once, before its init method is called.
        Overrides:
        onAttach in class Component
        Parameters:
        attachEvent - the attach event
      • onDetach

        protected void onDetach​(DetachEvent detachEvent)
        Called before the UI is removed from the session. A UI instance is detached exactly once, either:
        • after it is explicitly closed.
        • when its session is closed or expires
        • after three missed heartbeat requests.

        Note that when a UI is detached, any changes made in the detach methods of any children that would be communicated to the client are silently ignored.

        Overrides:
        onDetach in class Component
        Parameters:
        detachEvent - the detach event
      • accessSynchronously

        public void accessSynchronously​(Command command)
                                 throws UIDetachedException
        Locks the session of this UI and runs the provided command right away.

        It is generally recommended to use access(Command) instead of this method for accessing a session from a different thread as access(Command) can be used while holding the lock of another session. To avoid causing deadlocks, this methods throws an exception if it is detected than another session is also locked by the current thread.

        This method behaves differently than access(Command) in some situations:

        Parameters:
        command - the command which accesses the UI
        Throws:
        UIDetachedException - if the UI is not attached to a session (and locking can therefore not be done)
        IllegalStateException - if the current thread holds the lock for another session
        See Also:
        access(Command), VaadinSession.accessSynchronously(Command)
      • access

        public Future<Void> access​(Command command)
        Provides exclusive access to this UI from outside a request handling thread.

        The given command is executed while holding the session lock to ensure exclusive access to this UI. If the session is not locked, the lock will be acquired and the command is run right away. If the session is currently locked, the command will be run before that lock is released.

        RPC handlers for components inside this UI do not need to use this method as the session is automatically locked by the framework during RPC handling.

        Please note that the command might be invoked on a different thread or later on the current thread, which means that custom thread locals might not have the expected values when the command is executed. getCurrent(), VaadinSession.getCurrent() and VaadinService.getCurrent() are set according to this UI before executing the command. Other standard CurrentInstance values such as VaadinService.getCurrentRequest() and VaadinService.getCurrentResponse() will not be defined.

        The returned future can be used to check for task completion and to cancel the task.

        Parameters:
        command - the command which accesses the UI
        Returns:
        a future that can be used to check for task completion and to cancel the task
        Throws:
        UIDetachedException - if the UI is not attached to a session (and locking can therefore not be done)
        See Also:
        getCurrent(), accessSynchronously(Command), VaadinSession.access(Command), VaadinSession.lock()
      • accessLater

        public SerializableRunnable accessLater​(SerializableRunnable accessTask,
                                                SerializableRunnable detachHandler)
        Wraps the given access task as a runnable that runs the given task with this UI locked. The wrapped task may be run synchronously or asynchronously. If the UI is detached when the returned runnable is run, the provided detach handler is run instead. If the provided detach handler is null, the returned runnable may throw an UIDetachedException.

        This method can be used to create a callback that can be passed to an external notifier that isn't aware of the synchronization needed to update a UI instance.

        Parameters:
        accessTask - the task that updates this UI, not null
        detachHandler - the callback that will be invoked if the UI is detached, or null as described above
        Returns:
        a runnable that will run either the access task or the detach handler, possibly asynchronously
      • accessLater

        public <T> SerializableConsumer<T> accessLater​(SerializableConsumer<T> accessTask,
                                                       SerializableRunnable detachHandler)
        Wraps the given access task as a consumer that passes a value to the given task with this UI locked. The wrapped task may be run synchronously or asynchronously. If the UI is detached when the returned consumer is run, the provided detach handler is run instead. If the provided detach handler is null, the returned runnable may throw an UIDetachedException.

        This method can be used to create a callback that can be passed to an external notifier that isn't aware of the synchronization needed to update a UI instance.

        Parameters:
        accessTask - the task that updates this UI, not null
        detachHandler - the callback that will be invoked if the UI is detached, or null as described above
        Returns:
        a consumer that will run either the access task or the detach handler, possibly asynchronously
      • setPollInterval

        public void setPollInterval​(int intervalInMillis)
        Sets the interval with which the UI should poll the server to see if there are any changes. Polling is disabled by default.

        Note that it is possible to enable push and polling at the same time but it should not be done to avoid excessive server traffic.

        Add-on developers should note that this method is only meant for the application developer. An add-on should not set the poll interval directly, rather instruct the user to set it.

        Parameters:
        intervalInMillis - The interval (in ms) with which the UI should poll the server or -1 to disable polling
      • getPollInterval

        public int getPollInterval()
        Returns the interval with which the UI polls the server.
        Returns:
        The interval (in ms) with which the UI polls the server or -1 if polling is disabled
      • getLoadingIndicatorConfiguration

        public LoadingIndicatorConfiguration getLoadingIndicatorConfiguration()
        Retrieves the object used for configuring the loading indicator.
        Returns:
        The instance used for configuring the loading indicator
      • push

        public void push()
        Pushes the pending changes and client RPC invocations of this UI to the client-side.

        If push is enabled, but the push connection is not currently open, the push will be done when the connection is established.

        As with all UI methods, the session must be locked when calling this method. It is also recommended that getCurrent() is set up to return this UI since writing the response may invoke logic in any attached component or extension. The recommended way of fulfilling these conditions is to use access(Command).

        Throws:
        IllegalStateException - if push is disabled.
        UIDetachedException - if this UI is not attached to a session.
        See Also:
        getPushConfiguration()
      • getPushConfiguration

        public PushConfiguration getPushConfiguration()
        Retrieves the object used for configuring the push channel.

        Note that you cannot change push parameters on the fly, you need to configure the push channel at the same time (in the same request) it is enabled.

        Returns:
        The instance used for push configuration
      • getReconnectDialogConfiguration

        public ReconnectDialogConfiguration getReconnectDialogConfiguration()
        Retrieves the object used for configuring the reconnect dialog.
        Returns:
        The instance used for reconnect dialog configuration
      • getLocale

        public Locale getLocale()
        Gets the locale for this UI. The default locale is based on the session's locale, which is in turn determined in different ways depending on whether a I18NProvider is available.

        If a i18n provider is available, the locale is determined by selecting the locale from I18NProvider.getProvidedLocales() that best matches the user agent preferences (i.e. the Accept-Language header). If an exact match is found, then that locale is used. Otherwise, the matching logic looks for the first provided locale that uses the same language regardless of the country. If no other match is found, then the first item from I18NProvider.getProvidedLocales() is used.

        If no i18n provider is available, then the default JVM locale is used as the default locale.

        Overrides:
        getLocale in class Component
        Returns:
        the locale in use, not null
      • setLocale

        public void setLocale​(Locale locale)
        Sets the locale for this UI.

        Note that VaadinSession.setLocale(Locale) will set the locale for all UI instances in that session, and might thus override any custom locale previous set for a specific UI.

        Parameters:
        locale - the locale to use, not null
      • getElement

        public Element getElement()
        Gets the element for this UI.

        The UI element corresponds to the <body> tag on the page

        Specified by:
        getElement in interface HasElement
        Overrides:
        getElement in class Component
        Returns:
        the element for this UI
      • getInternals

        public UIInternals getInternals()
        Gets the framework data object for this UI. This method is for internal use only.
        Returns:
        the framework data object
      • getPage

        public Page getPage()
        Gets the object representing the page on which this UI exists.
        Returns:
        an object representing the page on which this UI exists
      • navigate

        public <T extends ComponentOptional<T> navigate​(Class<T> navigationTarget)
        Updates this UI to show the view corresponding to the given navigation target.

        Besides the navigation to the location this method also updates the browser location (and page history).

        If the view change actually happens (e.g. the view itself doesn't cancel the navigation), all navigation listeners are notified and a reference of the new view is returned for additional configuration.

        Parameters:
        navigationTarget - navigation target to navigate to
        Returns:
        the view instance, if navigation actually happened
        Throws:
        IllegalArgumentException - if navigationTarget is a HasUrlParameter with a mandatory parameter.
        NotFoundException - in case there is no route defined for the given navigationTarget.
        See Also:
        navigate(Class, Object), navigate(Class, RouteParameters)
      • navigate

        public <T,​C extends Component & HasUrlParameter<T>> Optional<C> navigate​(Class<? extends C> navigationTarget,
                                                                                       T parameter)
        Updates this UI to show the view corresponding to the given navigation target with the specified parameter. The parameter needs to be the same as defined in the route target HasUrlParameter.

        Besides the navigation to the location this method also updates the browser location (and page history).

        Note! A null parameter will be handled the same as navigate(navigationTarget) and will throw an exception if HasUrlParameter is not @OptionalParameter or @WildcardParameter.

        If the view change actually happens (e.g. the view itself doesn't cancel the navigation), all navigation listeners are notified and a reference of the new view is returned for additional configuration.

        Type Parameters:
        T - url parameter type
        C - navigation target type
        Parameters:
        navigationTarget - navigation target to navigate to
        parameter - parameter to pass to view
        Returns:
        the view instance, if navigation actually happened
        Throws:
        IllegalArgumentException - if a null parameter is given while navigationTarget's parameter is not annotated with @OptionalParameter or @WildcardParameter.
        NotFoundException - in case there is no route defined for the given navigationTarget matching the parameters.
      • navigate

        public <T extends ComponentOptional<T> navigate​(Class<T> navigationTarget,
                                                          RouteParameters parameters)
        Updates this UI to show the view corresponding to the given navigation target with the specified parameters. The parameters needs to comply with the ones defined in one of the Route or RouteAlias annotating the navigationTarget and with any RoutePrefix annotating the parent layouts of the navigationTarget.

        Besides the navigation to the location this method also updates the browser location (and page history).

        If the view change actually happens (e.g. the view itself doesn't cancel the navigation), all navigation listeners are notified and a reference of the new view is returned for additional configuration.

        Parameters:
        navigationTarget - navigation target to navigate to.
        parameters - parameters to pass to view.
        Returns:
        the view instance, if navigation actually happened
        Throws:
        IllegalArgumentException - if navigationTarget is a HasUrlParameter with a mandatory parameter, but parameters argument doesn't provide HasUrlParameterFormat.PARAMETER_NAME parameter.
        NotFoundException - in case there is no route defined for the given navigationTarget matching the parameters.
      • navigate

        public <T,​C extends Component & HasUrlParameter<T>> Optional<C> navigate​(Class<? extends C> navigationTarget,
                                                                                       T parameter,
                                                                                       QueryParameters queryParameters)
        Updates this UI to show the view corresponding to the given navigation target with the specified parameter. The parameter needs to be the same as defined in the route target HasUrlParameter.

        Besides the navigation to the location this method also updates the browser location (and page history).

        Note! A null parameter will be handled the same as navigate(navigationTarget) and will throw an exception if HasUrlParameter is not @OptionalParameter or @WildcardParameter.

        If the view change actually happens (e.g. the view itself doesn't cancel the navigation), all navigation listeners are notified and a reference of the new view is returned for additional configuration.

        Type Parameters:
        T - url parameter type
        C - navigation target type
        Parameters:
        navigationTarget - navigation target to navigate to
        parameter - route parameter to pass to view
        queryParameters - additional query parameters to pass to view
        Returns:
        the view instance, if navigation actually happened
        Throws:
        IllegalArgumentException - if a null parameter is given while navigationTarget's parameter is not annotated with @OptionalParameter or @WildcardParameter.
        NotFoundException - in case there is no route defined for the given navigationTarget matching the parameters.
      • navigate

        public <T extends ComponentOptional<T> navigate​(Class<? extends T> navigationTarget,
                                                          QueryParameters queryParameters)
        Updates this UI to show the view corresponding to the given navigation target and query parameters.

        Besides the navigation to the location this method also updates the browser location (and page history).

        If the view change actually happens (e.g. the view itself doesn't cancel the navigation), all navigation listeners are notified and a reference of the new view is returned for additional configuration.

        Type Parameters:
        T - navigation target type
        Parameters:
        navigationTarget - navigation target to navigate to
        queryParameters - additional query parameters to pass to view
        Returns:
        the view instance, if navigation actually happened
        Throws:
        NotFoundException - in case there is no route defined for the given navigationTarget matching the parameters.
      • navigate

        public void navigate​(String location,
                             QueryParameters queryParameters)
        Updates this UI to show the view corresponding to the given location and query parameters. The location must be a relative path without any ".." segments.

        Besides the navigation to the location this method also updates the browser location (and page history).

        Parameters:
        location - the location to navigate to, not null
        queryParameters - query parameters that are used for navigation, not null
        Throws:
        NullPointerException - if the location or queryParameters are null.
        See Also:
        navigate(String), Router.navigate(UI, Location, NavigationTrigger)
      • isNavigationSupported

        public boolean isNavigationSupported()
        Returns true if this UI instance supports navigation.
        Returns:
        true if this UI instance supports navigation, otherwise false.
      • getRouter

        @Deprecated
        public Router getRouter()
        Deprecated.
        For internal use only. Will be removed in the future.
        Gets the router used for navigating in this UI.
        Returns:
        a router
      • beforeClientResponse

        public StateTree.ExecutionRegistration beforeClientResponse​(Component component,
                                                                    SerializableConsumer<ExecutionContext> execution)
                                                             throws IllegalArgumentException
        Registers a task to be executed before the response is sent to the client. The tasks are executed in order of registration. If tasks register more tasks, they are executed after all already registered tasks for the moment.

        Example: three tasks are submitted, A, B and C, where B produces two more tasks during execution, D and E. The resulting execution would be ABCDE.

        If the Component related to the task is not attached to the document by the time the task is evaluated, the execution is postponed to before the next response.

        The task receives a ExecutionContext as parameter, which contains information about the component state before the response.

        Parameters:
        component - the Component relevant for the execution. Can not be null
        execution - the task to be executed. Can not be null
        Returns:
        a registration that can be used to cancel the execution of the task
        Throws:
        IllegalArgumentException - if the given component doesn't belong to this UI
      • add

        public void add​(Component... components)
        Adds the given components to the UI.

        The components' elements are attached to the UI element (the body tag).

        Specified by:
        add in interface HasComponents
        Parameters:
        components - the components to add
      • getUI

        public Optional<UI> getUI()
        Description copied from class: Component
        Gets the UI this component is attached to.
        Overrides:
        getUI in class Component
        Returns:
        an optional UI component, or an empty optional if this component is not attached to a UI
      • addBeforeEnterListener

        public Registration addBeforeEnterListener​(BeforeEnterListener listener)
        Add a listener that will be informed when a new set of components are going to be attached.

        By the time the components are going to be attached, their state is already calculated, consider this when using the listener.

        Listeners will be executed before any found observers.

        Parameters:
        listener - the before enter listener
        Returns:
        handler to remove the event listener
      • addBeforeLeaveListener

        public Registration addBeforeLeaveListener​(BeforeLeaveListener listener)
        Add a listener that will be informed when old components are detached.

        Listeners will be executed before any found observers.

        If a route target is left for reasons not under the control of the navigator (for instance using Page.setLocation(URI), typing a URL into the address bar, or closing the browser), listeners are not called.

        Parameters:
        listener - the before leave listener
        Returns:
        handler to remove the event listener
      • addAfterNavigationListener

        public Registration addAfterNavigationListener​(AfterNavigationListener listener)
        Add a listener that will be informed when new components have been attached and all navigation tasks have resolved.

        Listeners will be executed before any found observers.

        Parameters:
        listener - the after navigation listener
        Returns:
        handler to remove the event listener
      • getNavigationListeners

        public <E> List<E> getNavigationListeners​(Class<E> navigationHandler)
        Get all the registered listeners of the given navigation handler type.
        Type Parameters:
        E - the handler type
        Parameters:
        navigationHandler - navigation handler type to get listeners for
        Returns:
        unmodifiable list of registered listeners for navigation handler
      • addHeartbeatListener

        public Registration addHeartbeatListener​(HeartbeatListener listener)
        Add a listener that will be informed when this UI received a heartbeat from the client-side.

        Heartbeat requests are periodically sent by the client-side to inform the server that the UI sending the heartbeat is still alive (the browser window is open, the connection is up) even when there are no UIDL requests for a prolonged period of time. UIs that do not receive either heartbeat or UIDL requests are eventually removed from the session and garbage collected.

        Parameters:
        listener - the heartbeat listener
        Returns:
        handler to remove the heartbeat listener
      • getActiveDragSourceComponent

        public Component getActiveDragSourceComponent()
        Gets the drag source of an active HTML5 drag event.

        NOTE: the generic drag and drop feature for Flow is available in another artifact, flow-dnd for now.

        Returns:
        Extension of the drag source component if the drag event is active and originated from this UI, null otherwise.
        Since:
        2.0
      • getCsrfToken

        public String getCsrfToken()
        Gets the CSRF token (synchronizer token pattern) that is used to protect against Cross Site Request Forgery attacks.
        Returns:
        the csrf token string
        Since:
        2.0
      • addModal

        public void addModal​(Component component)
        Adds the given component as a modal child to the UI, making the UI and all other (existing) components added to the UI impossible for the user to interact with. This is useful for modal dialogs which should make the UI in the background inert. Note that this only prevents user interaction, but doesn't show a modality curtain or change the visible state of the components in the UI - that should be handled by the component separately. Thus this is purely a server side feature.

        When the modal component is removed the UI and its other children are no longer inert, unless there was another component added as modal before.

        Parameters:
        component - the modal component to add
        See Also:
        setChildComponentModal(Component, boolean)
      • setChildComponentModal

        public void setChildComponentModal​(Component childComponent,
                                           boolean modal)
        Makes the child component modal or modeless. The component needs to be a child of this UI. By default all child components are modeless.
        Parameters:
        childComponent - the child component to change state for
        modal - true for modal, false for modeless
      • hasModalComponent

        public boolean hasModalComponent()
        Check if UI has a defined modal component.
        Returns:
        true if a modal component has been set
      • addToModalComponent

        public void addToModalComponent​(Component component)
        Add component as child to modal component if one is active. Else it will be added to the UI normally.

        This is meant to be used with components that are not added as part of a layout, like dialog, so that they are interactive when a modal component opens up an overlay component.

        Parameters:
        component - component to add to modal component