Class VaadinService
- java.lang.Object
-
- com.vaadin.flow.server.VaadinService
-
- All Implemented Interfaces:
Serializable
- Direct Known Subclasses:
VaadinServletService
public abstract class VaadinService extends Object implements Serializable
An abstraction of the underlying technology, e.g. servlets, for handling browser requests.- Since:
- 1.0.
- Author:
- Vaadin Ltd
- See Also:
- Serialized Form
-
-
Field Summary
Fields Modifier and Type Field Description static String
ATMOSPHERE_MISSING_ERROR
static String
CANNOT_ACQUIRE_CLASSLOADER_SEVERE
static String
INVALID_ATMOSPHERE_VERSION_WARNING
-
Constructor Summary
Constructors Modifier Constructor Description protected
VaadinService()
Creates a service.VaadinService(DeploymentConfiguration deploymentConfiguration)
Creates a new vaadin service based on a deployment configuration.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description Future<Void>
accessSession(VaadinSession session, Command command)
Implementation forVaadinSession.access(Command)
.Registration
addServiceDestroyListener(ServiceDestroyListener listener)
Adds a service destroy listener that gets notified when this service is destroyed.Registration
addSessionDestroyListener(SessionDestroyListener listener)
Adds a listener that gets notified when a Vaadin service session that has been initialized for this service is destroyed.Registration
addSessionInitListener(SessionInitListener listener)
Adds a listener that gets notified when a new Vaadin service session is initialized for this service.Registration
addUIInitListener(UIInitListener listener)
Adds a listener that gets notified when a new UI has been initialized.void
closeSession(VaadinSession session)
Sets the given session to be closed and all its 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 abstract VaadinContext
constructVaadinContext()
ConstructsVaadinContext
for this service.static String
createCriticalNotificationJSON(String caption, String message, String details, String url)
Creates a JSON message which, when sent to client as-is, will cause a critical error to be shown with the given details.static String
createCriticalNotificationJSON(String caption, String message, String details, String url, String querySelector)
Creates a JSON message which, when sent to client as-is, will cause a critical error to be shown with the given details.protected Instantiator
createInstantiator()
Creates an instantiator to use with this service.protected List<RequestHandler>
createRequestHandlers()
Called during initialization to add the request handlers for the service.static String
createSessionExpiredJSON(boolean async)
Creates the JSON to send to the client when the session has expired.static String
createUINotFoundJSON(boolean async)
Creates the JSON to send to the client when the UI cannot be found.protected VaadinSession
createVaadinSession(VaadinRequest request)
Creates a new Vaadin session for this service and request.void
destroy()
Called when the servlet or similar for this service is being destroyed.void
ensureAccessQueuePurged(VaadinSession session)
Makes sure the pending access queue is purged for the provided session.boolean
ensurePushAvailable()
Enables push if push support is available and push has not yet been enabled.UI
findUI(VaadinRequest request)
Finds theUI
that belongs to the provided request.VaadinSession
findVaadinSession(VaadinRequest request)
Attempts to find a Vaadin service session associated with this request.void
fireSessionDestroy(VaadinSession vaadinSession)
Handles destruction of the given session.void
fireUIInitListeners(UI ui)
Fire UI initialization event to all registeredUIInitListener
s.BootstrapInitialPredicate
getBootstrapInitialPredicate()
Get the predicate for including the initial Uidl fragment in the bootstrap page.BootstrapUrlPredicate
getBootstrapUrlPredicate()
Get the predicate for testing whether the request has a valid URL for rendering the bootstrap page.ClassLoader
getClassLoader()
Gets the class loader to use for loading classes loaded by name, e.g.VaadinContext
getContext()
ReturnsVaadinContext
for this service.abstract String
getContextRootRelativePath(VaadinRequest request)
Returns relative context path for given request.static String
getCsrfTokenAttributeName()
Get the name of the CSRF Token attribute in HTTP session.static VaadinService
getCurrent()
Gets the currently used Vaadin service.static VaadinRequest
getCurrentRequest()
Gets the currently processed Vaadin request.static VaadinResponse
getCurrentResponse()
Gets the currently processed Vaadin response.Iterable<DependencyFilter>
getDependencyFilters()
Gets the filters which all resource dependencies are passed through before being sent to the client for loading.DeploymentConfiguration
getDeploymentConfiguration()
Gets the deployment configuration.protected VaadinSession
getExistingSession(VaadinRequest request, boolean allowSessionCreation)
Instantiator
getInstantiator()
Gets the instantiator used by this service.abstract String
getMainDivId(VaadinSession session, VaadinRequest request)
Creates and returns a unique ID for the DIV where the UI is to be rendered.abstract String
getMimeType(String resourceName)
Returns the MIME type of the specified file, or null if the MIME type is not known.protected abstract PwaRegistry
getPwaRegistry()
Iterable<RequestHandler>
getRequestHandlers()
Returns the request handlers that are registered with this service.abstract URL
getResource(String url)
Returns a URL to the resource at the given Vaadin URI.abstract InputStream
getResourceAsStream(String url)
Opens a stream to to the resource at the given Vaadin URI.Router
getRouter()
Gets the router used for UIs served by this service.protected abstract RouteRegistry
getRouteRegistry()
Find a route registry to use for this service.abstract String
getServiceName()
Gets a unique name for this service.protected String
getSessionAttributeName()
Returns the name used for storing the VaadinSession in the underlying HTTP session.protected Lock
getSessionLock(WrappedSession wrappedSession)
Gets the lock instance used to lock the VaadinSession associated with the given wrapped session.abstract URL
getStaticResource(String url)
Returns a URL to the static resource at the given URI or null if no file found.SystemMessages
getSystemMessages(Locale locale, VaadinRequest request)
Gets the system message to use for a specific locale.SystemMessagesProvider
getSystemMessagesProvider()
Gets the system messages provider currently defined for this service.void
handleRequest(VaadinRequest request, VaadinResponse response)
Handles the incoming request and writes the response into the response object.protected void
handleSessionExpired(VaadinRequest request, VaadinResponse response)
Called when the session has expired and the request handling is therefore aborted.void
init()
Initializes this service.protected boolean
isAtmosphereAvailable()
Checks whether Atmosphere is available for use.static boolean
isCsrfTokenValid(UI ui, String requestToken)
Verifies that the given CSRF token (synchronizer token pattern) is valid for the given UI.static boolean
isOtherSessionLocked(VaadinSession session)
Checks whether there might be someVaadinSession
other than the provided one for which the current thread holds a lock.boolean
isResourceAvailable(String url)
Checks if a resource is available at the given Vaadin URI.boolean
isUIActive(UI ui)
Returns whether the given UI is active (the client-side actively communicates with the server) or whether it can be removed from the session and eventually collected.protected Optional<Instantiator>
loadInstantiators()
Loads and initializes instantiators.protected VaadinSession
loadSession(WrappedSession wrappedSession)
Called when the VaadinSession should be loaded from the underlying HTTP session.protected Lock
lockSession(WrappedSession wrappedSession)
Locks the given session for this service instance.void
modifyBootstrapPage(BootstrapPageResponse response)
Deprecated.Since 3.0, this API is deprecated in favor ofmodifyIndexHtmlResponse(IndexHtmlResponse)
when using client-side bootstrappingvoid
modifyIndexHtmlResponse(IndexHtmlResponse response)
Fires theIndexHtmlRequestListener.modifyIndexHtmlResponse(IndexHtmlResponse)
event to all registeredIndexHtmlRequestListener
.protected VaadinSession
readFromHttpSession(WrappedSession wrappedSession)
Performs the actual read of the VaadinSession from the underlying HTTP session after sanity checks have been performed.static void
reinitializeSession(VaadinRequest request)
Discards the current session and creates a new session with the same contents.protected void
removeFromHttpSession(WrappedSession wrappedSession)
Performs the actual removal of the VaadinSession from the underlying HTTP session after sanity checks have been performed.void
removeSession(WrappedSession wrappedSession)
Called when the VaadinSession should be removed from the underlying HTTP session.protected abstract boolean
requestCanCreateSession(VaadinRequest request)
Checks whether it's valid to create a new service session as a result of the given request.void
requestEnd(VaadinRequest request, VaadinResponse response, VaadinSession session)
Called after the framework has handled a request and the response has been written.void
requestStart(VaadinRequest request, VaadinResponse response)
Called before the framework starts handling a request.abstract String
resolveResource(String url)
Resolves the givenurl
resource to be useful forgetResource(String)
andgetResourceAsStream(String )
.void
runPendingAccessTasks(VaadinSession session)
Purges the queue of pending access invocations enqueued withVaadinSession.access(Command)
.void
setBootstrapInitialPredicate(BootstrapInitialPredicate bootstrapInitialPredicate)
Set the predicate that decides whether to include the initial Uidl fragment in the bootstrap page.void
setBootstrapUrlPredicate(BootstrapUrlPredicate bootstrapUrlPredicate)
Set the predicate that decides whether the request has a valid URL for rendering the bootstrap page.void
setClassLoader(ClassLoader classLoader)
Sets the class loader to use for loading classes loaded by name, e.g.static void
setCurrent(VaadinService service)
Sets the given Vaadin service as the current service.void
setCurrentInstances(VaadinRequest request, VaadinResponse response)
Sets the this Vaadin service as the current service and also sets the current Vaadin request and Vaadin response.protected void
setDefaultClassLoader()
Tries to acquire default class loader and sets it as a class loader for thisVaadinService
if found.void
setSystemMessagesProvider(SystemMessagesProvider systemMessagesProvider)
Sets the system messages provider to use for getting system messages to display to users of this service.protected void
storeSession(VaadinSession session, WrappedSession wrappedSession)
Called when the VaadinSession should be stored.protected void
unlockSession(WrappedSession wrappedSession, Lock lock)
Releases the lock for the given session for this service instance.static void
verifyNoOtherSessionLocked(VaadinSession session)
Checks that anotherVaadinSession
instance is not locked.void
writeStringResponse(VaadinResponse response, String contentType, String responseString)
Writes the given string as a response using the given content type.protected void
writeToHttpSession(WrappedSession wrappedSession, VaadinSession session)
Performs the actual write of the VaadinSession to the underlying HTTP session after sanity checks have been performed.void
writeUncachedStringResponse(VaadinResponse response, String contentType, String responseString)
Writes the given string as a response with headers to prevent caching and using the given content type.
-
-
-
Field Detail
-
INVALID_ATMOSPHERE_VERSION_WARNING
public static final String INVALID_ATMOSPHERE_VERSION_WARNING
- See Also:
- Constant Field Values
-
ATMOSPHERE_MISSING_ERROR
public static final String ATMOSPHERE_MISSING_ERROR
-
CANNOT_ACQUIRE_CLASSLOADER_SEVERE
public static final String CANNOT_ACQUIRE_CLASSLOADER_SEVERE
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
VaadinService
public VaadinService(DeploymentConfiguration deploymentConfiguration)
Creates a new vaadin service based on a deployment configuration.- Parameters:
deploymentConfiguration
- the deployment configuration for the service
-
VaadinService
protected VaadinService()
Creates a service. This method is for use by dependency injection frameworks etc. and must be followed by a call tosetClassLoader(ClassLoader)
orsetDefaultClassLoader()
before use. FurthermoregetDeploymentConfiguration()
andgetContext()
should be overridden (or otherwise intercepted) not to returnnull
.
-
-
Method Detail
-
init
public void init() throws ServiceException
Initializes this service. The service should be initialized before it is used.- Throws:
ServiceException
- if a problem occurs when creating the service
-
getRouteRegistry
protected abstract RouteRegistry getRouteRegistry()
Find a route registry to use for this service.- Returns:
- the route registry to use, not
null
-
getPwaRegistry
protected abstract PwaRegistry getPwaRegistry()
-
getContextRootRelativePath
public abstract String getContextRootRelativePath(VaadinRequest request)
Returns relative context path for given request. Override this method in subclasses.- Parameters:
request
- Request.- Returns:
- Relative context root path for that request.
-
createRequestHandlers
protected List<RequestHandler> createRequestHandlers() throws ServiceException
Called during initialization to add the request handlers for the service. Note that the returned list will be reversed so the last handler will be called first. This enables overriding this method and using add on the returned list to add a custom request handler which overrides any predefined handler.- Returns:
- The list of request handlers used by this service.
- Throws:
ServiceException
- if a problem occurs when creating the request handlers
-
createInstantiator
protected Instantiator createInstantiator() throws ServiceException
Creates an instantiator to use with this service.A custom Vaadin service implementation can override this method to pick an instantiator. The method
loadInstantiators()
is used to find a custom instantiator. If there is no one found then the default is used. You may override this method orloadInstantiators()
in your custom service.- Returns:
- an instantiator to use, not
null
- Throws:
ServiceException
- if there are multiple applicable instantiators- See Also:
loadInstantiators()
,Instantiator
-
loadInstantiators
protected Optional<Instantiator> loadInstantiators() throws ServiceException
Loads and initializes instantiators.A custom Vaadin service implementation can override this method to pick an instantiator in some other way instead of the default implementation that uses
ServiceLoader
.There may be only one applicable instantiator. Otherwise
ServiceException
will be thrown.- Returns:
- an optional instantator, or an empty optional if no instantiator found
- Throws:
ServiceException
- if there are multiple applicable instantiators- See Also:
createInstantiator()
,Instantiator
-
getInstantiator
public Instantiator getInstantiator()
Gets the instantiator used by this service.- Returns:
- the used instantiator, or
null
if this service has not yet been initialized - See Also:
createInstantiator()
,Instantiator
-
getClassLoader
public ClassLoader getClassLoader()
Gets the class loader to use for loading classes loaded by name, e.g. custom UI classes. This is by default the class loader that was used to load the Servlet class to which this service belongs.- Returns:
- the class loader to use, or
null
- See Also:
setClassLoader(ClassLoader)
-
setClassLoader
public void setClassLoader(ClassLoader classLoader)
Sets the class loader to use for loading classes loaded by name, e.g. custom UI classes. Invokers of this method should be careful to not break any existing class loader hierarchy, e.g. by ensuring that a class loader set for this service delegates to the previously set class loader if the class is not found.- Parameters:
classLoader
- the new class loader to set, notnull
.- See Also:
getClassLoader()
-
getMimeType
public abstract String getMimeType(String resourceName)
Returns the MIME type of the specified file, or null if the MIME type is not known. The MIME type is determined by the configuration of the container, and may be specified in a deployment descriptor. Common MIME types are "text/html" and "image/gif".- Parameters:
resourceName
- a String specifying the name of a file- Returns:
- a String specifying the file's MIME type
- See Also:
ServletContext.getMimeType(String)
-
getDeploymentConfiguration
public DeploymentConfiguration getDeploymentConfiguration()
Gets the deployment configuration. Should be overridden (or otherwise intercepted) if the no-arg constructor is used in order to prevent NPEs.- Returns:
- the deployment configuration
-
setSystemMessagesProvider
public void setSystemMessagesProvider(SystemMessagesProvider systemMessagesProvider)
Sets the system messages provider to use for getting system messages to display to users of this service.- Parameters:
systemMessagesProvider
- the system messages provider;null
is not allowed.- See Also:
getSystemMessagesProvider()
-
getSystemMessagesProvider
public SystemMessagesProvider getSystemMessagesProvider()
Gets the system messages provider currently defined for this service.By default, the
DefaultSystemMessagesProvider
which always provides the built-in defaultSystemMessages
is used.- Returns:
- the system messages provider; not
null
- See Also:
setSystemMessagesProvider(SystemMessagesProvider)
,SystemMessagesProvider
,SystemMessages
-
getSystemMessages
public SystemMessages getSystemMessages(Locale locale, VaadinRequest request)
Gets the system message to use for a specific locale. This method may also be implemented to use information from current instances of various objects, which means that this method might return different values for the same locale under different circumstances.- Parameters:
locale
- the desired locale for the system messagesrequest
- the request being processed- Returns:
- the system messages to use
-
addSessionInitListener
public Registration addSessionInitListener(SessionInitListener listener)
Adds a listener that gets notified when a new Vaadin service session is initialized for this service.Because of the way different service instances share the same session, the listener is not necessarily notified immediately when the session is created but only when the first request for that session is handled by this service.
- Parameters:
listener
- the Vaadin service session initialization listener- Returns:
- a handle that can be used for removing the listener
- See Also:
SessionInitListener
-
addUIInitListener
public Registration addUIInitListener(UIInitListener listener)
Adds a listener that gets notified when a new UI has been initialized.- Parameters:
listener
- the UI initialization listener- Returns:
- a handle that can be used for removing the listener
- See Also:
UIInitListener
-
addSessionDestroyListener
public Registration addSessionDestroyListener(SessionDestroyListener listener)
Adds a listener that gets notified when a Vaadin service session that has been initialized for this service is destroyed.The session being destroyed is locked and its UIs have been removed when the listeners are called.
- Parameters:
listener
- the vaadin service session destroy listener- Returns:
- a handle that can be used for removing the listener
- See Also:
addSessionInitListener(SessionInitListener)
-
modifyBootstrapPage
@Deprecated public void modifyBootstrapPage(BootstrapPageResponse response)
Deprecated.Since 3.0, this API is deprecated in favor ofmodifyIndexHtmlResponse(IndexHtmlResponse)
when using client-side bootstrappingFires theBootstrapListener.modifyBootstrapPage(BootstrapPageResponse)
event to all registeredBootstrapListener
. This is called internally when the bootstrap page is created, so listeners can intercept the creation and change the result HTML.- Parameters:
response
- The object containing all relevant info needed by listeners to change the bootstrap page.
-
modifyIndexHtmlResponse
public void modifyIndexHtmlResponse(IndexHtmlResponse response)
Fires theIndexHtmlRequestListener.modifyIndexHtmlResponse(IndexHtmlResponse)
event to all registeredIndexHtmlRequestListener
. This is called internally when the Index HTML response is created, so listeners can intercept the creation and change the result HTML.- Parameters:
response
- The object containing all relevant info needed by listeners to change the Index HTML response.
-
fireSessionDestroy
public void fireSessionDestroy(VaadinSession vaadinSession)
Handles destruction of the given session. Internally ensures proper locking is done.- Parameters:
vaadinSession
- The session to destroy
-
findVaadinSession
public VaadinSession findVaadinSession(VaadinRequest request) throws SessionExpiredException
Attempts to find a Vaadin service session associated with this request.Handles locking of the session internally to avoid creation of duplicate sessions by two threads simultaneously.
- Parameters:
request
- the request to get a vaadin service session for.- Returns:
- the vaadin service session for the request, or
null
if no session is found and this is a request for which a new session shouldn't be created. - Throws:
SessionExpiredException
- if the session has already expired- See Also:
VaadinSession
-
getSessionLock
protected Lock getSessionLock(WrappedSession wrappedSession)
Gets the lock instance used to lock the VaadinSession associated with the given wrapped session.This method uses the wrapped session instead of VaadinSession to be able to lock even before the VaadinSession has been initialized.
- Parameters:
wrappedSession
- The wrapped session- Returns:
- A lock instance used for locking access to the wrapped session
-
lockSession
protected Lock lockSession(WrappedSession wrappedSession)
Locks the given session for this service instance. Typically you want to callVaadinSession.lock()
instead of this method.Note: The method and its signature has been changed to return lock instance in Vaadin X.X.X. If you have overriden this method, you need to update your implementation.
Note: Overriding this method is not recommended, for custom lock storage strategy override
getSessionLock(WrappedSession)
andsetSessionLock(WrappedSession,Lock)
instead.- Parameters:
wrappedSession
- The session to lock- Returns:
- Lock instance
- Throws:
IllegalStateException
- if the session is invalidated before it can be locked
-
unlockSession
protected void unlockSession(WrappedSession wrappedSession, Lock lock)
Releases the lock for the given session for this service instance. Typically you want to callVaadinSession.unlock()
instead of this method.Note: The method and its signature has been changed to get lock instance as parameter in Vaadin X.X.0. If you have overriden this method, you need to update your implementation.
Note: Overriding this method is not recommended, for custom lock storage strategy override
getSessionLock(WrappedSession)
andsetSessionLock(WrappedSession,Lock)
instead.- Parameters:
wrappedSession
- The session to unlocklock
- Lock instance to unlock
-
createVaadinSession
protected VaadinSession createVaadinSession(VaadinRequest request)
Creates a new Vaadin session for this service and request.- Parameters:
request
- The request for which to create a VaadinSession- Returns:
- A new VaadinSession
-
getExistingSession
protected VaadinSession getExistingSession(VaadinRequest request, boolean allowSessionCreation) throws SessionExpiredException
- Throws:
SessionExpiredException
-
requestCanCreateSession
protected abstract boolean requestCanCreateSession(VaadinRequest request)
Checks whether it's valid to create a new service session as a result of the given request.- Parameters:
request
- the request- Returns:
true
if it's valid to create a new service session for the request; elsefalse
-
getCurrent
public static VaadinService getCurrent()
Gets the currently used Vaadin service. The current service is automatically defined when processing requests related to the service (seeThreadLocal
) and inVaadinSession.access(Command)
andUI.access(Command)
. In other cases, (e.g. from background threads), the current service is not automatically defined.- Returns:
- the current Vaadin service instance if available, otherwise
null
- See Also:
setCurrentInstances(VaadinRequest, VaadinResponse)
-
setCurrentInstances
public void setCurrentInstances(VaadinRequest request, VaadinResponse response)
Sets the this Vaadin service as the current service and also sets the current Vaadin request and Vaadin response. This method is used by the framework to set the current instances when a request related to the service is processed and they are cleared when the request has been processed.The application developer can also use this method to define the current instances outside the normal request handling, e.g. when initiating custom background threads.
- Parameters:
request
- the Vaadin request to set as the current request, ornull
if no request should be set.response
- the Vaadin response to set as the current response, ornull
if no response should be set.- See Also:
getCurrent()
,getCurrentRequest()
,getCurrentResponse()
-
setCurrent
public static void setCurrent(VaadinService service)
Sets the given Vaadin service as the current service.- Parameters:
service
- the service to set
-
getCurrentRequest
public static VaadinRequest getCurrentRequest()
Gets the currently processed Vaadin request. The current request is automatically defined when the request is started. The current request can not be used in e.g. background threads because of the way server implementations reuse request instances.- Returns:
- the current Vaadin request instance if available, otherwise
null
- See Also:
setCurrentInstances(VaadinRequest, VaadinResponse)
-
getCurrentResponse
public static VaadinResponse getCurrentResponse()
Gets the currently processed Vaadin response. The current response is automatically defined when the request is started. The current response can not be used in e.g. background threads because of the way server implementations reuse response instances.- Returns:
- the current Vaadin response instance if available, otherwise
null
- See Also:
setCurrentInstances(VaadinRequest, VaadinResponse)
-
getServiceName
public abstract String getServiceName()
Gets a unique name for this service. The name should be unique among different services of the same type but the same for corresponding instances running in different JVMs in a cluster. This is typically based on e.g. the configured servlet's name.- Returns:
- the unique name of this service instance.
-
findUI
public UI findUI(VaadinRequest request)
Finds theUI
that belongs to the provided request. This is generally only supported for UIDL requests as other request types are not related to any particular UI or have the UI information encoded in a non-standard way. The returned UI is also set as the current UI (UI.setCurrent(UI)
).- Parameters:
request
- the request for which a UI is desired- Returns:
- the UI belonging to the request or null if no UI is found
-
reinitializeSession
public static void reinitializeSession(VaadinRequest request)
Discards the current session and creates a new session with the same contents. The purpose of this is to introduce a new session key in order to avoid session fixation attacks.Please note that this method makes certain assumptions about how data is stored in the underlying session and may thus not be compatible with some environments.
- Parameters:
request
- The Vaadin request for which the session should be reinitialized
-
getMainDivId
public abstract String getMainDivId(VaadinSession session, VaadinRequest request)
Creates and returns a unique ID for the DIV where the UI is to be rendered.- Parameters:
session
- The service session to which the bootstrapped UI will belong.request
- The request for which a div id is needed- Returns:
- the id to use in the DOM
-
closeSession
public void closeSession(VaadinSession session)
Sets the given session to be closed and all its 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.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.
- Parameters:
session
- the session to close- See Also:
SystemMessages.getSessionExpiredCaption()
-
isUIActive
public boolean isUIActive(UI ui)
Returns whether the given UI is active (the client-side actively communicates with the server) or whether it can be removed from the session and eventually collected.A UI is active if and only if its
isClosing
returns false andgetHeartbeatTimeout
is negative or has not yet expired.- Parameters:
ui
- The UI whose status to check- Returns:
- true if the UI is active, false if it could be removed.
-
requestStart
public void requestStart(VaadinRequest request, VaadinResponse response)
Called before the framework starts handling a request.- Parameters:
request
- The requestresponse
- The response
-
requestEnd
public void requestEnd(VaadinRequest request, VaadinResponse response, VaadinSession session)
Called after the framework has handled a request and the response has been written.- Parameters:
request
- The request objectresponse
- The response objectsession
- The session which was used during the request or null if the request did not use a session
-
getRequestHandlers
public Iterable<RequestHandler> getRequestHandlers()
Returns the request handlers that are registered with this service. The iteration order of the returned collection is the same as the order in which the request handlers will be invoked when a request is handled.- Returns:
- a collection of request handlers in the order they are invoked
- See Also:
createRequestHandlers()
-
getDependencyFilters
public Iterable<DependencyFilter> getDependencyFilters()
Gets the filters which all resource dependencies are passed through before being sent to the client for loading.- Returns:
- the dependency filters to pass resources dependencies through before loading
-
handleRequest
public void handleRequest(VaadinRequest request, VaadinResponse response) throws ServiceException
Handles the incoming request and writes the response into the response object. UsesgetRequestHandlers()
for handling the request.If a session expiration is detected during request handling then each
request handler
has an opportunity to handle the expiration event if it implementsSessionExpiredHandler
. If no request handler handles session expiration a default expiration message will be written.- Parameters:
request
- The incoming requestresponse
- The outgoing response- Throws:
ServiceException
- Any exception that occurs during response handling will be wrapped in a ServiceException
-
writeStringResponse
public void writeStringResponse(VaadinResponse response, String contentType, String responseString) throws IOException
Writes the given string as a response using the given content type.- Parameters:
response
- The response referencecontentType
- The content type of the responseresponseString
- The actual response- Throws:
IOException
- If an error occurred while writing the response
-
writeUncachedStringResponse
public void writeUncachedStringResponse(VaadinResponse response, String contentType, String responseString) throws IOException
Writes the given string as a response with headers to prevent caching and using the given content type.- Parameters:
response
- The response referencecontentType
- The content type of the responseresponseString
- The actual response- Throws:
IOException
- If an error occurred while writing the response
-
handleSessionExpired
protected void handleSessionExpired(VaadinRequest request, VaadinResponse response) throws ServiceException
Called when the session has expired and the request handling is therefore aborted.- Parameters:
request
- The requestresponse
- The response- Throws:
ServiceException
- Thrown if there was any problem handling the expiration of the session
-
createCriticalNotificationJSON
public static String createCriticalNotificationJSON(String caption, String message, String details, String url)
Creates a JSON message which, when sent to client as-is, will cause a critical error to be shown with the given details.- Parameters:
caption
- The caption of the error or null to omitmessage
- The error message or null to omitdetails
- Additional error details or null to omiturl
- A url to redirect to. If no other details are given then the user will be immediately redirected to this URL. Otherwise the message will be shown and the browser will redirect to the given URL only after the user acknowledges the message. If null then the browser will refresh the current page.- Returns:
- A JSON string to be sent to the client
-
createCriticalNotificationJSON
public static String createCriticalNotificationJSON(String caption, String message, String details, String url, String querySelector)
Creates a JSON message which, when sent to client as-is, will cause a critical error to be shown with the given details.- Parameters:
caption
- The caption of the error or null to omitmessage
- The error message or null to omitdetails
- Additional error details or null to omiturl
- A url to redirect to. If no other details are given then the user will be immediately redirected to this URL. Otherwise the message will be shown and the browser will redirect to the given URL only after the user acknowledges the message. If null then the browser will refresh the current page.querySelector
- Query selector to find the element under which the error will be added. If the element is not found the message is not shown. If the selector isnull
, the body element is used.- Returns:
- A JSON string to be sent to the client
-
createSessionExpiredJSON
public static String createSessionExpiredJSON(boolean async)
Creates the JSON to send to the client when the session has expired.- Parameters:
async
- a boolean indicating whether the message is sent synchronously or asynchronously.- Returns:
- the JSON used to inform the client about a session expiration, as a string
-
createUINotFoundJSON
public static String createUINotFoundJSON(boolean async)
Creates the JSON to send to the client when the UI cannot be found.- Parameters:
async
- a boolean indicating whether the message is sent synchronously or asynchronously.- Returns:
- the JSON used to inform the client that the UI cannot be found, as a string
-
ensurePushAvailable
public boolean ensurePushAvailable()
Enables push if push support is available and push has not yet been enabled. If push support is not available, a warning explaining the situation will be logged at least the first time this method is invoked.- Returns:
true
if push can be used;false
if push is not available.
-
isAtmosphereAvailable
protected boolean isAtmosphereAvailable()
Checks whether Atmosphere is available for use.- Returns:
- true if Atmosphere is available, false otherwise
-
verifyNoOtherSessionLocked
public static void verifyNoOtherSessionLocked(VaadinSession session)
Checks that anotherVaadinSession
instance is not locked. This is internally used byVaadinSession.accessSynchronously(Command)
andUI.accessSynchronously(Command)
to help avoid causing deadlocks.- Parameters:
session
- the session that is being locked- Throws:
IllegalStateException
- if the current thread holds the lock for another session
-
isOtherSessionLocked
public static boolean isOtherSessionLocked(VaadinSession session)
Checks whether there might be someVaadinSession
other than the provided one for which the current thread holds a lock. This method might not detect all cases where some other session is locked, but it should cover the most typical situations.- Parameters:
session
- the session that is expected to be locked- Returns:
true
if another session is also locked by the current thread;false
if no such session was found
-
isCsrfTokenValid
public static boolean isCsrfTokenValid(UI ui, String requestToken)
Verifies that the given CSRF token (synchronizer token pattern) is valid for the given UI. This is used to protect against Cross Site Request Forgery attacks.This protection is enabled by default, but it might need to be disabled to allow a certain type of testing. For these cases, the check can be disabled by setting the init parameter
disable-xsrf-protection
totrue
.- Parameters:
ui
- the UI for which the check should be donerequestToken
- the CSRF token provided in the request- Returns:
true
if the token is valid or if the protection is disabled;false
if protection is enabled and the token is invalid- See Also:
AbstractConfiguration.isXsrfProtectionEnabled()
-
accessSession
public Future<Void> accessSession(VaadinSession session, Command command)
Implementation forVaadinSession.access(Command)
. This method is implemented here instead of inVaadinSession
to enable overriding the implementation without using a custom subclass of VaadinSession.- Parameters:
session
- the vaadin session to accesscommand
- the command to run with the session locked- Returns:
- a future that can be used to check for task completion and to cancel the task
- See Also:
VaadinSession.access(Command)
-
ensureAccessQueuePurged
public void ensureAccessQueuePurged(VaadinSession session)
Makes sure the pending access queue is purged for the provided session. If the session is currently locked by the current thread or some other thread, the queue will be purged when the session is unlocked. If the lock is not held by any thread, it is acquired and the queue is purged right away.- Parameters:
session
- the session for which the access queue should be purged
-
runPendingAccessTasks
public void runPendingAccessTasks(VaadinSession session)
Purges the queue of pending access invocations enqueued withVaadinSession.access(Command)
.This method is automatically run by the framework at appropriate situations and is not intended to be used by application developers.
- Parameters:
session
- the vaadin session to purge the queue for
-
addServiceDestroyListener
public Registration addServiceDestroyListener(ServiceDestroyListener listener)
Adds a service destroy listener that gets notified when this service is destroyed.The listeners may be invoked in a non-deterministic order. In particular, it is not guaranteed that listeners will be invoked in the order they were added.
- Parameters:
listener
- the service destroy listener to add- Returns:
- a handle that can be used for removing the listener
- See Also:
destroy()
,ServiceDestroyListener
-
destroy
public void destroy()
Called when the servlet or similar for this service is being destroyed. After this method has been called, no more requests will be handled by this service.- See Also:
addServiceDestroyListener(ServiceDestroyListener)
,Servlet.destroy()
-
setDefaultClassLoader
protected void setDefaultClassLoader()
Tries to acquire default class loader and sets it as a class loader for thisVaadinService
if found. If current security policy disallows acquiring class loader instance it will log a message and re-throwSecurityException
- Throws:
SecurityException
- If current security policy forbids acquiring class loader
-
storeSession
protected void storeSession(VaadinSession session, WrappedSession wrappedSession)
Called when the VaadinSession should be stored.By default stores the VaadinSession in the underlying HTTP session.
- Parameters:
session
- the VaadinSession to storewrappedSession
- the underlying HTTP session
-
writeToHttpSession
protected void writeToHttpSession(WrappedSession wrappedSession, VaadinSession session)
Performs the actual write of the VaadinSession to the underlying HTTP session after sanity checks have been performed.- Parameters:
wrappedSession
- the underlying HTTP sessionsession
- the VaadinSession to store
-
loadSession
protected VaadinSession loadSession(WrappedSession wrappedSession)
Called when the VaadinSession should be loaded from the underlying HTTP session.- Parameters:
wrappedSession
- the underlying HTTP session- Returns:
- the VaadinSession in the HTTP session or null if not found
-
readFromHttpSession
protected VaadinSession readFromHttpSession(WrappedSession wrappedSession)
Performs the actual read of the VaadinSession from the underlying HTTP session after sanity checks have been performed.If a VaadinSession that was ignored during serialization is found, it is removed from the session and
null
is returned so a new, proper session can be created.Called by
loadSession(WrappedSession)
.- Parameters:
wrappedSession
- the underlying HTTP session- Returns:
- the VaadinSession or null if no session was found
-
removeSession
public void removeSession(WrappedSession wrappedSession)
Called when the VaadinSession should be removed from the underlying HTTP session.- Parameters:
wrappedSession
- the underlying HTTP session
-
removeFromHttpSession
protected void removeFromHttpSession(WrappedSession wrappedSession)
Performs the actual removal of the VaadinSession from the underlying HTTP session after sanity checks have been performed.- Parameters:
wrappedSession
- the underlying HTTP session
-
getSessionAttributeName
protected String getSessionAttributeName()
Returns the name used for storing the VaadinSession in the underlying HTTP session.- Returns:
- the attribute name used for storing the VaadinSession
-
getRouter
public Router getRouter()
Gets the router used for UIs served by this service.- Returns:
- the router, not
null
-
fireUIInitListeners
public void fireUIInitListeners(UI ui)
Fire UI initialization event to all registeredUIInitListener
s.- Parameters:
ui
- the initializedUI
-
getStaticResource
public abstract URL getStaticResource(String url)
Returns a URL to the static resource at the given URI or null if no file found.- Parameters:
url
- the URL for the resource- Returns:
- the resource located at the named path, or
null
if there is no resource at that path
-
getResource
public abstract URL getResource(String url)
Returns a URL to the resource at the given Vaadin URI.- Parameters:
url
- the untranslated Vaadin URL for the resource- Returns:
- the resource located at the named path, or
null
if there is no resource at that path
-
getResourceAsStream
public abstract InputStream getResourceAsStream(String url)
Opens a stream to to the resource at the given Vaadin URI.- Parameters:
url
- the untranslated Vaadin URL for the resource- Returns:
- a stream for the resource or
null
if no resource exists at the specified path
-
isResourceAvailable
public boolean isResourceAvailable(String url)
Checks if a resource is available at the given Vaadin URI.- Parameters:
url
- the untranslated Vaadin URL for the resource- Returns:
true
if a resource is found and can be read usinggetResourceAsStream(String)
,false
if it is not found
-
resolveResource
public abstract String resolveResource(String url)
Resolves the givenurl
resource to be useful forgetResource(String)
andgetResourceAsStream(String )
.- Parameters:
url
- the resource to resolve, notnull
- Returns:
- the resolved URL or the same as the input url if no translation was performed
-
constructVaadinContext
protected abstract VaadinContext constructVaadinContext()
ConstructsVaadinContext
for this service. This method will be called only once, upon first call togetContext()
.- Returns:
- Context. This may never be
null
.
-
getContext
public VaadinContext getContext()
ReturnsVaadinContext
for this service.- Returns:
- A non-null context instance.
-
getBootstrapInitialPredicate
public BootstrapInitialPredicate getBootstrapInitialPredicate()
Get the predicate for including the initial Uidl fragment in the bootstrap page.By default it returns an instance that instruct to include the fragment in the case
- Returns:
- a non-null instance.
-
setBootstrapInitialPredicate
public void setBootstrapInitialPredicate(BootstrapInitialPredicate bootstrapInitialPredicate)
Set the predicate that decides whether to include the initial Uidl fragment in the bootstrap page.- Parameters:
bootstrapInitialPredicate
- the predicate.
-
getBootstrapUrlPredicate
public BootstrapUrlPredicate getBootstrapUrlPredicate()
Get the predicate for testing whether the request has a valid URL for rendering the bootstrap page.By default it returns an instance that returns true for all requests.
- Returns:
- a non-null instance.
-
setBootstrapUrlPredicate
public void setBootstrapUrlPredicate(BootstrapUrlPredicate bootstrapUrlPredicate)
Set the predicate that decides whether the request has a valid URL for rendering the bootstrap page.- Parameters:
bootstrapUrlPredicate
- the predicate.
-
getCsrfTokenAttributeName
public static String getCsrfTokenAttributeName()
Get the name of the CSRF Token attribute in HTTP session.- Returns:
- the attribute name string
-
-