public class VaadinSession extends Object implements Serializable
HttpSession
, but others storage mechanisms
might also be used.
Everything inside a VaadinSession
should be serializable to ensure
compatibility with schemes using serialization for persisting the session
data.
Current VaadinSession object which can be accessed by
getCurrent()
is not present before VaadinServlet
starts handling the HTTP request. For example, it cannot be used in any
implementation of Filter
interface.
Modifier and Type | Field and Description |
---|---|
protected WebBrowser |
browser |
static String |
UI_PARAMETER
Deprecated.
Use
InitParameters.UI_PARAMETER instead. |
Constructor and Description |
---|
VaadinSession(VaadinService service)
Creates a new VaadinSession tied to a VaadinService.
|
Modifier and Type | Method and Description |
---|---|
Future<Void> |
access(Command command)
Provides exclusive access to this session from outside a request handling
thread.
|
void |
accessSynchronously(Command command)
Locks this session and runs the provided Command right away.
|
void |
addRequestHandler(RequestHandler handler)
Adds a request handler to this session.
|
void |
addUI(UI ui)
Adds an initialized UI to this session.
|
void |
checkHasLock()
Potentially checks whether this session is currently locked by the
current thread, and fails with a standard error message if not.
|
void |
checkHasLock(String message)
Potentially checks whether this session is currently locked by the
current thread, and fails with the given message if not.
|
void |
close()
Sets this session to be closed and all UI state to be discarded at the
end of the current request, or at the end of the next request if there is
no ongoing one.
|
protected StreamResourceRegistry |
createStreamResourceRegistry()
Creates the StreamResourceRegistry for this session.
|
static Collection<VaadinSession> |
getAllSessions(HttpSession httpSession)
Retrieves all
VaadinSession s which are stored in the given HTTP
session. |
<T> T |
getAttribute(Class<T> type)
Gets a stored attribute value.
|
Object |
getAttribute(String name)
Gets a stored attribute value.
|
WebBrowser |
getBrowser()
Get the web browser associated with this session.
|
DeploymentConfiguration |
getConfiguration()
Gets the configuration for this session.
|
String |
getCsrfToken()
Gets the CSRF token (synchronizer token pattern) that is used to protect
against Cross Site Request Forgery attacks.
|
long |
getCumulativeRequestDuration() |
static VaadinSession |
getCurrent()
Gets the currently used session.
|
ErrorHandler |
getErrorHandler()
Gets the session's error handler.
|
long |
getLastRequestDuration() |
long |
getLastRequestTimestamp()
Returns the time when the last request was serviced in this session.
|
Locale |
getLocale()
Gets the locale for this session.
|
Lock |
getLockInstance()
Gets the
Lock instance that is used for protecting the data of
this session from concurrent access. |
int |
getNextUIid()
Creates a new unique id for a UI.
|
Queue<FutureAccess> |
getPendingAccessQueue()
Gets the queue of tasks submitted using
access(Command) . |
String |
getPushId()
Gets the push connection identifier for this session.
|
Collection<RequestHandler> |
getRequestHandlers()
Gets the request handlers that are registered to the session.
|
StreamResourceRegistry |
getResourceRegistry()
Get resource registry instance.
|
VaadinService |
getService() |
WrappedSession |
getSession()
Gets the underlying session to which this service session is currently
associated.
|
VaadinSessionState |
getState()
Returns the lifecycle state of this session.
|
UI |
getUIById(int uiId)
Returns a UI with the given id.
|
Collection<UI> |
getUIs()
Gets all the UIs of this session.
|
boolean |
hasLock()
Checks if the current thread has exclusive access to this
VaadinSession . |
protected static boolean |
hasLock(VaadinService service,
WrappedSession session)
Checks if the current thread has exclusive access to the given
WrappedSession.
|
void |
lock()
Locks this session to protect its data from concurrent access.
|
void |
refreshTransients(WrappedSession wrappedSession,
VaadinService vaadinService)
Refreshes the transient fields of the session to ensure they are up to
date.
|
void |
removeRequestHandler(RequestHandler handler)
Removes a request handler from the session.
|
void |
removeUI(UI ui)
Called by the framework to remove an UI instance from the session because
it has been closed.
|
<T> void |
setAttribute(Class<T> type,
T value)
Stores a value in this service session.
|
void |
setAttribute(String name,
Object value)
Stores a value in this service session.
|
void |
setBrowser(WebBrowser browser)
Set the web browser associated with this session.
|
void |
setConfiguration(DeploymentConfiguration configuration) |
static void |
setCurrent(VaadinSession session)
Sets the thread local for the current session.
|
void |
setErrorHandler(ErrorHandler errorHandler)
Sets the session error handler.
|
void |
setLastRequestDuration(long time)
Sets the time spent servicing the last request in the session and updates
the total time spent servicing requests in this session.
|
void |
setLastRequestTimestamp(long timestamp)
Sets the time when the last UIDL request was serviced in this session.
|
void |
setLocale(Locale locale)
Sets the default locale for this session.
|
protected void |
setState(VaadinSessionState state)
Sets the lifecycle state of this session.
|
void |
unlock()
Unlocks this session.
|
void |
valueBound(HttpSessionBindingEvent arg0) |
void |
valueUnbound(HttpSessionBindingEvent event) |
@Deprecated public static final String UI_PARAMETER
InitParameters.UI_PARAMETER
instead.protected WebBrowser browser
public VaadinSession(VaadinService service)
service
- the Vaadin service for the new sessionprotected StreamResourceRegistry createStreamResourceRegistry()
public void valueBound(HttpSessionBindingEvent arg0)
javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
public void valueUnbound(HttpSessionBindingEvent event)
javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
public WebBrowser getBrowser()
public void setBrowser(WebBrowser browser)
browser
- the web browser objectpublic long getCumulativeRequestDuration()
public void setLastRequestDuration(long time)
time
- The time spent in the last request, in milliseconds.public long getLastRequestDuration()
public void setLastRequestTimestamp(long timestamp)
timestamp
- The time when the last request was handled, in milliseconds
since the epoch.public long getLastRequestTimestamp()
public WrappedSession getSession()
public static Collection<VaadinSession> getAllSessions(HttpSession httpSession)
VaadinSession
s which are stored in the given HTTP
session.httpSession
- the HTTP sessionpublic void setConfiguration(DeploymentConfiguration configuration)
public DeploymentConfiguration getConfiguration()
public Locale getLocale()
The default locale is 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.
public void setLocale(Locale locale)
Setting the locale of a session will also override any custom locale configured for all UIs in this session.
locale
- the locale to set, not null
public ErrorHandler getErrorHandler()
public void setErrorHandler(ErrorHandler errorHandler)
errorHandler
- the new error handler, not null
public void addRequestHandler(RequestHandler handler)
Handlers are called in reverse order of addition, so the most recently added handler will be called first.
handler
- the request handler to addremoveRequestHandler(RequestHandler)
public void removeRequestHandler(RequestHandler handler)
handler
- the request handler to removepublic Collection<RequestHandler> getRequestHandlers()
addRequestHandler(RequestHandler)
,
removeRequestHandler(RequestHandler)
public static VaadinSession getCurrent()
ThreadLocal
)
and in access(Command)
and
UI.access(Command)
. In other cases, (e.g. from background
threads), the current session is not automatically defined.
The session is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.
null
setCurrent(VaadinSession)
public static void setCurrent(VaadinSession session)
The application developer can also use this method to define the current session outside the normal request handling and treads started from request handling threads, e.g. when initiating custom background threads.
The session is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.
session
- the session to set as currentgetCurrent()
,
ThreadLocal
public Collection<UI> getUIs()
public UI getUIById(int uiId)
This is meant for framework internal use.
uiId
- The UI idpublic boolean hasLock()
VaadinSession
.public void checkHasLock(String message)
When production mode is enabled, the check is only done if assertions are also enabled. This is done to avoid the small performance impact of continuously checking the lock status. The check is always done when production mode is not enabled.
message
- the error message to include when failing if the check is done
and the session is not lockedpublic void checkHasLock()
When production mode is enabled, the check is only done if assertions are also enabled. This is done to avoid the small performance impact of continuously checking the lock status. The check is always done when production mode is not enabled.
protected static boolean hasLock(VaadinService service, WrappedSession session)
service
- the service to checksession
- the session to use for checkingpublic void removeUI(UI ui)
ui
- the UI to removepublic Lock getLockInstance()
Lock
instance that is used for protecting the data of
this session from concurrent access.
The Lock
can be used to gain more control than what is
available only using lock()
and unlock()
. The returned
instance is not guaranteed to support any other features of the
Lock
interface than Lock.lock()
and
Lock.unlock()
.
Lock
that is used for synchronization, it's
never null
for the session which is in use, i.e. if
refreshTransients(WrappedSession, VaadinService)
has
been called for itlock()
,
Lock
public void lock()
UI.access(Command)
(or access(Command)
if you are only touching the
session and not any UI), e.g.:
myUI.access(new Command() { @Override public void run() { // Here it is safe to update the UI. // UI.getCurrent can also be used myUI.getContent().setCaption("Changed safely"); } });If you for whatever reason want to do locking manually, you should do it like:
session.lock(); try { doSomething(); } finally { session.unlock(); }This method will block until the lock can be retrieved.
getLockInstance()
can be used if more control over the locking
is required.
unlock()
,
getLockInstance()
,
hasLock()
public void unlock()
public void setAttribute(String name, Object value)
null
clears the stored value.name
- the name to associate the value with, can not be
null
value
- the value to associate with the name, or null
to
remove a previous association.getAttribute(String)
public <T> void setAttribute(Class<T> type, T value)
null
clears the stored value.
The fully qualified name of the type is used as the name when storing the value. The outcome of calling this method is thus the same as if calling
setAttribute(type.getName(), value);
T
- the type of the stored valuetype
- the type that the stored value represents, can not be nullvalue
- the value to associate with the type, or null
to
remove a previous association.getAttribute(Class)
,
setAttribute(String, Object)
public Object getAttribute(String name)
null
is returned.name
- the name of the value to get, can not be null
.null
if no value has been stored or if
it has been set to null.setAttribute(String, Object)
public <T> T getAttribute(Class<T> type)
null
is returned.
The fully qualified name of the type is used as the name when getting the
value. The outcome of calling this method is thus the same as if calling
getAttribute(type.getName());
T
- the type of the value to gettype
- the type of the value to get, can not be null
.null
if no value has been stored or if
it has been set to null.setAttribute(Class, Object)
,
getAttribute(String)
public int getNextUIid()
public void addUI(UI ui)
ui
- the initialized UI to add.public VaadinService getService()
public void close()
After the session has been discarded, any UIs that have been left open will give a Session Expired error and a new session will be created for serving new UIs.
Note that this method only closes the VaadinSession
which is not
the same as HttpSession
. To invalidate the underlying HTTP
session getSession().invalidate();
needs to be called.
The method is usually called to perform logout. If user data is stored
inside HTTP session then getSession().invalidate();
should be
called instead (most common case). It makes sense to call
close()
only if user data is stored inside a
VaadinSession
. Use the Page.setLocation(String)
method to
navigate to some page after session is closed to avoid session expired
message.
public VaadinSessionState getState()
protected void setState(VaadinSessionState state)
state
- the new statepublic void accessSynchronously(Command command)
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 sessionIllegalStateException
- if the current thread holds the lock for another sessionlock()
,
getCurrent()
,
access(Command)
,
UI.accessSynchronously(Command)
public Future<Void> access(Command command)
The given command is executed while holding the session lock to ensure exclusive access to this session. If this session is not locked, the lock will be acquired and the command is run right away. If this session is currently locked, the command will be run before that lock is released.
RPC handlers for components inside this session 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()
and VaadinService.getCurrent()
are set according to this session 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. To help avoiding deadlocks, Future.get()
throws
an exception if it is detected that the current thread holds the lock for
some other session.
command
- the command which accesses the sessionlock()
,
getCurrent()
,
accessSynchronously(Command)
,
UI.access(Command)
public Queue<FutureAccess> getPendingAccessQueue()
access(Command)
. It is
safe to call this method and access the returned queue without holding
the session lock
.public String getPushId()
public void refreshTransients(WrappedSession wrappedSession, VaadinService vaadinService)
Called internally by the framework.
wrappedSession
- the session this VaadinSession is stored invaadinService
- the service associated with this VaadinSessionpublic StreamResourceRegistry getResourceRegistry()
Use this instance to manage StreamResource
s.
public String getCsrfToken()
Copyright © 2023. All rights reserved.