public class UI extends Component implements PollNotifier, HasComponents, RouterLayout
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)
.
init(VaadinRequest)
,
Serialized FormModifier | Constructor and Description |
---|---|
|
UI()
Creates a new empty UI.
|
protected |
UI(UIInternalUpdater internalsHandler)
Create a new empty UI with a custom
UIInternalUpdater
implementation. |
Modifier and Type | Method and Description |
---|---|
Future<Void> |
access(Command command)
Provides exclusive access to this UI from outside a request handling
thread.
|
<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.
|
SerializableRunnable |
accessLater(SerializableRunnable accessTask,
SerializableRunnable detachHandler)
Wraps the given access task as a runnable that runs the given task with
this UI locked.
|
void |
accessSynchronously(Command command)
Locks the session of this UI and runs the provided command right away.
|
void |
add(Component... components)
Adds the given components to the UI.
|
Registration |
addAfterNavigationListener(AfterNavigationListener listener)
Add a listener that will be informed when new components have been
attached and all navigation tasks have resolved.
|
Registration |
addBeforeEnterListener(BeforeEnterListener listener)
Add a listener that will be informed when a new set of components are
going to be attached.
|
Registration |
addBeforeLeaveListener(BeforeLeaveListener listener)
Add a listener that will be informed when old components are detached.
|
ShortcutRegistration |
addShortcutListener(Command command,
Key key,
KeyModifier... keyModifiers)
Registers a global shortcut tied to the
UI which executes the
given Command when invoked. |
ShortcutRegistration |
addShortcutListener(ShortcutEventListener listener,
Key key,
KeyModifier... keyModifiers)
Registers a global shortcut tied to the
UI which executes the
given ComponentEventListener when invoked. |
StateTree.ExecutionRegistration |
beforeClientResponse(Component component,
SerializableConsumer<ExecutionContext> execution)
Registers a task to be executed before the response is sent to the
client.
|
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.) |
void |
doInit(VaadinRequest request,
int uiId)
Internal initialization method, should not be overridden.
|
Component |
getActiveDragSourceComponent()
Gets the drag source of an active HTML5 drag event.
|
String |
getCsrfToken()
Gets the CSRF token (aka double submit cookie) that is used to protect
against Cross Site Request Forgery attacks.
|
static UI |
getCurrent()
Gets the currently used UI.
|
Element |
getElement()
Gets the element for this UI.
|
UIInternals |
getInternals()
Gets the framework data object for this UI.
|
LoadingIndicatorConfiguration |
getLoadingIndicatorConfiguration()
Retrieves the object used for configuring the loading indicator.
|
Locale |
getLocale()
Gets the locale for this UI.
|
<E> List<E> |
getNavigationListeners(Class<E> navigationHandler)
Get all the registered listeners of the given navigation handler type.
|
Page |
getPage()
Gets the object representing the page on which this UI exists.
|
int |
getPollInterval()
Returns the interval with which the UI polls the server.
|
PushConfiguration |
getPushConfiguration()
Retrieves the object used for configuring the push channel.
|
ReconnectDialogConfiguration |
getReconnectDialogConfiguration()
Retrieves the object used for configuring the reconnect dialog.
|
Router |
getRouter()
Gets the router used for navigating in this UI.
|
VaadinSession |
getSession()
Gets the VaadinSession to which this UI is attached.
|
Optional<UI> |
getUI()
Gets the UI this component is attached to.
|
int |
getUIId()
Gets the id of the UI, used to identify this UI within its application
when processing requests.
|
protected void |
init(VaadinRequest request)
Initializes this UI.
|
boolean |
isClosing()
Returns whether this UI is marked as closed and is to be detached.
|
<T,C extends Component & HasUrlParameter<T>> |
navigate(Class<? extends C> navigationTarget,
T parameter)
Updates this UI to show the view corresponding to the given navigation
target with the specified parameter.
|
void |
navigate(Class<? extends Component> navigationTarget)
Updates this UI to show the view corresponding to the given navigation
target.
|
void |
navigate(Class<? extends Component> navigationTarget,
RouteParameters parameters)
Updates this UI to show the view corresponding to the given navigation
target with the specified parameters.
|
void |
navigate(String location)
Updates this UI to show the view corresponding to the given location.
|
void |
navigate(String location,
QueryParameters queryParameters)
Updates this UI to show the view corresponding to the given location and
query parameters.
|
protected void |
onAttach(AttachEvent attachEvent)
Called after the UI is added to the session.
|
protected void |
onDetach(DetachEvent detachEvent)
Called before the UI is removed from the session.
|
void |
push()
Pushes the pending changes and client RPC invocations of this UI to the
client-side.
|
static void |
setCurrent(UI ui)
Sets the thread local for the current UI.
|
void |
setDirection(Direction direction)
Sets the direction for the UI.
|
void |
setLocale(Locale locale)
Sets the locale for this UI.
|
void |
setPollInterval(int intervalInMillis)
Sets the interval with which the UI should poll the server to see if
there are any changes.
|
addListener, fireEvent, from, get, getChildren, getEventBus, getId, getParent, getTranslation, getTranslation, hasListener, isTemplateMapped, isVisible, onEnabledStateChanged, set, setElement, setId, setVisible
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
addPollListener
add, addComponentAsFirst, addComponentAtIndex, remove, removeAll
isEnabled, setEnabled
removeRouterLayoutContent, showRouterLayoutContent
addAttachListener
addDetachListener
public UI()
protected UI(UIInternalUpdater internalsHandler)
UIInternalUpdater
implementation.internalsHandler
- an implementation of UIInternalsHandler.public VaadinSession getSession()
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.
null
.onAttach(AttachEvent)
public int getUIId()
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.
public void doInit(VaadinRequest request, int uiId)
request
- the initialization requestuiId
- the id of the new uigetUIId()
protected void init(VaadinRequest request)
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.
request
- the Vaadin request that caused this UI to be createdpublic static void setCurrent(UI ui)
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.
ui
- the UI to register as the current UIgetCurrent()
,
ThreadLocal
public static UI getCurrent()
The UI is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.
null
setCurrent(UI)
public void close()
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.
public boolean isClosing()
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.
close()
protected void onAttach(AttachEvent attachEvent)
init
method is
called.protected void onDetach(DetachEvent detachEvent)
closed
.
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.
public void accessSynchronously(Command command) throws UIDetachedException
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:
accessSynchronously(Command)
runs the task right away whereas
access(Command)
defers the task to a later point in time.accessSynchronously(Command)
blocks while waiting for the lock
to be available whereas access(Command)
defers the task to a
later point in time.command
- the command which accesses the UIUIDetachedException
- 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 sessionaccess(Command)
,
VaadinSession.accessSynchronously(Command)
public Future<Void> access(Command command)
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.
command
- the command which accesses the UIUIDetachedException
- if the UI is not attached to a session (and locking can
therefore not be done)getCurrent()
,
accessSynchronously(Command)
,
VaadinSession.access(Command)
,
VaadinSession.lock()
public SerializableRunnable accessLater(SerializableRunnable accessTask, SerializableRunnable detachHandler)
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.
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 abovepublic <T> SerializableConsumer<T> accessLater(SerializableConsumer<T> accessTask, SerializableRunnable detachHandler)
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.
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 abovepublic void setPollInterval(int intervalInMillis)
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.
intervalInMillis
- The interval (in ms) with which the UI should poll the server
or -1 to disable pollingpublic int getPollInterval()
public LoadingIndicatorConfiguration getLoadingIndicatorConfiguration()
public void push()
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)
.
IllegalStateException
- if push is disabled.UIDetachedException
- if this UI is not attached to a session.getPushConfiguration()
public PushConfiguration getPushConfiguration()
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.
public ReconnectDialogConfiguration getReconnectDialogConfiguration()
public Locale getLocale()
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.
public void setLocale(Locale locale)
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.
locale
- the locale to use, not nullpublic void setDirection(Direction direction)
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.
direction
- the direction to use, not null
public Element getElement()
The UI element corresponds to the <body>
tag on the page
getElement
in interface HasElement
getElement
in class Component
public UIInternals getInternals()
public Page getPage()
public void navigate(Class<? extends Component> navigationTarget)
Besides the navigation to the location
this method also updates
the browser location (and page history).
navigationTarget
- navigation target to navigate toIllegalArgumentException
- if navigationTarget is a HasUrlParameter
with a
mandatory parameter.NotFoundException
- in case there is no route defined for the given
navigationTarget.navigate(Class, Object)
,
navigate(Class, RouteParameters)
public <T,C extends Component & HasUrlParameter<T>> void navigate(Class<? extends C> navigationTarget, T parameter)
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.
T
- url parameter typeC
- navigation target typenavigationTarget
- navigation target to navigate toparameter
- parameter to pass to viewIllegalArgumentException
- 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.public void navigate(Class<? extends Component> navigationTarget, RouteParameters parameters)
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).
navigationTarget
- navigation target to navigate to.parameters
- parameters to pass to view.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.public void navigate(String location)
Besides the navigation to the location
this method also updates
the browser location (and page history).
location
- the location to navigate to, not null
NullPointerException
- if the location is null.navigate(String, QueryParameters)
,
Router.navigate(UI, Location, NavigationTrigger)
public void navigate(String location, QueryParameters queryParameters)
Besides the navigation to the location
this method also updates
the browser location (and page history).
location
- the location to navigate to, not null
queryParameters
- query parameters that are used for navigation, not
null
NullPointerException
- if the location or queryParameters are null.navigate(String)
,
Router.navigate(UI, Location, NavigationTrigger)
public Router getRouter()
public StateTree.ExecutionRegistration beforeClientResponse(Component component, SerializableConsumer<ExecutionContext> execution)
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.
component
- the Component relevant for the execution. Can not be
null
execution
- the task to be executed. Can not be null
public void add(Component... components)
The components' elements are attached to the UI element (the body tag).
add
in interface HasComponents
components
- the components to addpublic Optional<UI> getUI()
Component
public Registration addBeforeEnterListener(BeforeEnterListener listener)
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.
listener
- the before enter listenerpublic Registration addBeforeLeaveListener(BeforeLeaveListener listener)
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.
listener
- the before leave listenerpublic Registration addAfterNavigationListener(AfterNavigationListener listener)
Listeners will be executed before any found observers.
listener
- the after navigation listenerpublic <E> List<E> getNavigationListeners(Class<E> navigationHandler)
E
- the handler typenavigationHandler
- navigation handler type to get listeners forpublic ShortcutRegistration addShortcutListener(Command command, Key key, KeyModifier... keyModifiers)
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.
command
- code to execute when the shortcut is invoked. Cannot be nullkey
- primary Key
used to trigger the shortcut. Cannot be
nullkeyModifiers
- KeyModifiers
which also need to be pressed
for the shortcut to triggerShortcutRegistration
for configuring the shortcut and
removingfor
registering a listener which receives a {@link ShortcutEvent}
,
for a more generic way to add a shortcut
public ShortcutRegistration addShortcutListener(ShortcutEventListener listener, Key key, KeyModifier... keyModifiers)
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.
listener
- listener to execute when the shortcut is invoked. Receives a
ShortcutEvent
. Cannot be nullkey
- primary Key
used to trigger the shortcutkeyModifiers
- KeyModifiers
which also need to be pressed
for the shortcut to triggerShortcutRegistration
for configuring the shortcut and
removingfor a more generic way to add a shortcut
public Component getActiveDragSourceComponent()
NOTE: the generic drag and drop feature for Flow is available in
another artifact, flow-dnd
for now.
public String getCsrfToken()
Copyright © 2020. All rights reserved.