Class UI

All Implemented Interfaces:
AttachNotifier, DetachNotifier, HasComponents, HasElement, HasEnabled, HasStyle, PollNotifier, RouterLayout, Serializable
Direct Known Subclasses:
WebComponentUI

@JsModule("@vaadin/common-frontend/ConnectionIndicator.js") public class UI extends Component implements PollNotifier, HasComponents, RouterLayout
The topmost component in any component hierarchy. There is one UI for every Vaadin instance in a browser window. A UI may either represent an entire browser window (or tab) or some part of a html page where a Vaadin application is embedded.

The UI is the server side entry point for various client side features that are not represented as components added to a layout, e.g notifications, sub windows, and executing javascript in the browser.

When a new UI instance is needed, typically because the user opens a URL in a browser window which points to e.g. VaadinServlet, the UI mapped to that servlet is opened. The selection is based on the UI init parameter.

After a UI has been created by the application, it is initialized using init(VaadinRequest).

Since:
1.0
See Also:
  • Field Details

  • Constructor Details

    • 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 Details

    • 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:
    • 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

      @Deprecated public void doInit(VaadinRequest request, int uiId)
      Deprecated.
      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:
    • doInit

      public void doInit(VaadinRequest request, int uiId, String appId)
      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
      appId - the application id
      See Also:
    • 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

      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:
    • 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:
    • 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
      • when resynchronizing.

      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

      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:
    • 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

      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
    • setDirection

      public void setDirection(Direction direction)
      Sets the direction for the UI.

      If you need the direction to update automatically upon Locale change, make the main layout implement LocaleChangeObserver and call this method from the LocaleChangeObserver.localeChange(LocaleChangeEvent) implementation.

      Parameters:
      direction - the direction 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
    • isNavigationSupported

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

      public Component getCurrentView()
      Returns the currently active route aka navigation target shown in this UI.

      Note, that certain UIs, like embedded apps, don't support routing and for those an exception will be thrown.

      Also, the current route might not be initialized if this method is called while still building the view chain, for example in the constructor of layouts. Thus, consider postponing the usage of this method to for example AfterNavigationEvent.

      Returns:
      the currently active route instance if available
      Throws:
      IllegalStateException - if current view is not yet available
    • 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

      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
    • addShortcutListener

      public ShortcutRegistration addShortcutListener(Command command, Key key, KeyModifier... keyModifiers)
      Registers a global shortcut tied to the UI which executes the given Command when invoked.

      Returns ShortcutRegistration which can be used to fluently configure the shortcut. The shortcut will be present until ShortcutRegistration.remove() is called.

      Parameters:
      command - code to execute when the shortcut is invoked. Cannot be null
      key - primary Key used to trigger the shortcut. Cannot be null
      keyModifiers - KeyModifiers which also need to be pressed for the shortcut to trigger
      Returns:
      ShortcutRegistration for configuring the shortcut and removing
      See Also:
    • addShortcutListener

      public ShortcutRegistration addShortcutListener(ShortcutEventListener listener, Key key, KeyModifier... keyModifiers)
      Registers a global shortcut tied to the UI which executes the given ComponentEventListener when invoked.

      Returns ShortcutRegistration which can be used to fluently configure the shortcut. The shortcut will be present until ShortcutRegistration.remove() is called.

      Parameters:
      listener - listener to execute when the shortcut is invoked. Receives a ShortcutEvent. Cannot be null
      key - primary Key used to trigger the shortcut
      keyModifiers - KeyModifiers which also need to be pressed for the shortcut to trigger
      Returns:
      ShortcutRegistration for configuring the shortcut and removing
      See Also:
    • 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

      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
    • getChildren

      public Stream<Component> getChildren()
      Description copied from class: Component
      Gets the child components of this component.

      The default implementation finds child components by traversing each child Element tree.

      If the component is injected to a PolymerTemplate using the @Id annotation the getChildren method will only return children added from the server side and will not return any children declared in the template file.

      Overrides:
      getChildren in class Component
      Returns:
      the child components of this component
      See Also:
    • getActiveViewLocation

      public Location getActiveViewLocation()
      Gets the location of the currently shown view. The location is relative the servlet mapping used for serving the related UI.
      Returns:
      the view location, not null
    • getActiveRouterTargetsChain

      public List<HasElement> getActiveRouterTargetsChain()
      Gets the currently active router target and parent layouts.
      Returns:
      a list of active router target and parent layout instances, starting from the innermost part
    • getForwardToClientUrl

      public String getForwardToClientUrl()
      Gets the new forward url.
      Returns:
      the new forward url
    • connectClient

      @ClientCallable public void connectClient(String flowRoutePath, String flowRouteQuery, String appShellTitle, elemental.json.JsonValue historyState, String trigger)
      Connect a client with the server side UI. This method is invoked each time client router navigates to a server route.
      Parameters:
      flowRoutePath - flow route path that should be attached to the client element
      flowRouteQuery - flow route query string
      appShellTitle - client side title of the application shell
      historyState - client side history state value
      trigger - navigation trigger
    • leaveNavigation

      @ClientCallable public void leaveNavigation(String route, String query)
      Check that the view can be leave. This method is invoked when the client router tries to navigate to a client route while the current route is a server route. This is only called when client route navigates from a server to a client view.
      Parameters:
      route - the route that is navigating to.