Class OorianSession
- All Implemented Interfaces:
OorianThreadListener
OorianSession wraps a OorianHttpSession and provides Oorian-specific session behavior,
including page caching, client profile management, and worker thread coordination. It serves
as the primary mechanism for accessing session data throughout an Oorian application.
Key Features:
- Thread-local storage for accessing the current session from anywhere in the application
- Page caching for maintaining page state across AJAX requests
- Client profile management for device and browser information
- Worker thread coordination for background processing
- Typed attribute accessors for convenient session data retrieval
Usage:
// Get the current session from anywhere in the application
OorianSession session = OorianSession.get();
// Store and retrieve typed attributes
session.setAttribute("userId", 12345);
Integer userId = session.getAttributeAsInt("userId");
// Access client profile information
ClientProfile profile = session.getClientProfile();
- Since:
- 2021
- Version:
- 1.0
- Author:
- Marvin P. Warble Jr.
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionbooleanChecks whether the current request is within the configured rate limit.static voidDispatches an ApplicationEvent to all active sessions.voiddispatchEvent(SessionEvent event) Dispatches a SessionEvent to all listeners registered on this session for that event type.static OorianSessionget()Returns the OorianSession registered to the current thread.static AppContextReturns the application context.getAttribute(String name) Returns the session attribute with the specified name.getAttributeAsBoolean(String name) Returns an attribute as a Boolean.getAttributeAsBoolean(String name, Boolean defValue) Returns an attribute as a Boolean with a default value.getAttributeAsDouble(String name) Returns an attribute as a Double.getAttributeAsDouble(String name, Double defValue) Returns an attribute as a Double with a default value.getAttributeAsFloat(String name) Returns an attribute as a Float.getAttributeAsFloat(String name, Float defValue) Returns an attribute as a Float with a default value.getAttributeAsInt(String name) Returns an attribute as an Integer.getAttributeAsInt(String name, Integer defValue) Returns an attribute as an Integer with a default value.getAttributeAsLong(String name) Returns an attribute as a Long.getAttributeAsLong(String name, Long defValue) Returns an attribute as a Long with a default value.getAttributeAsShort(String name) Returns an attribute as a Short.getAttributeAsShort(String name, Short defValue) Returns an attribute as a Short with a default value.getAttributeAsString(String name) Returns an attribute as a String.getAttributeAsString(String name, String defValue) Returns an attribute as a String with a default value.Returns an enumeration of all attribute names in this session.Returns the client profile for this session.Returns the context path of the web application.longReturns the time the session was created.Returns the CSRF token for this session, creating one if it doesn't exist.Returns the current page for this session.getId()Returns the unique session identifier.longReturns the time of last client access.intReturns the maximum inactive interval for this session.Returns a cached page by its unique identifier.Returns the authenticated user principal for this session.getRealPath(String path) Returns the real filesystem path for the specified virtual path.getResourceAsStream(String path) Returns an input stream for reading the specified application resource.static Collection<OorianSession> Returns all active OorianSessions.Returns the user identifier associated with this session.voidInvalidates this session and unbinds all objects bound to it.voidInvalidates this session.booleanChecks whether a user is currently authenticated in this session.booleanChecks whether this session has expired based on the application-wide timeout settings.booleanisNew()Checks if the session was newly created.static booleanisValid()Checks if a valid OorianSession is registered to the current thread.voidlogin(UserPrincipal principal) Logs in the specified user principal, marking this session as authenticated.voidlogout()Logs out the current user and invalidates this session.voidCalled when the current thread's request processing is complete.Regenerates the CSRF token for this session.static voidregister(OorianHttpRequest request) Registers the OorianSession for a web request to the current thread.static OorianSessionregister(OorianHttpSession webSession) Registers the OorianSession for a session to the current thread.voidregisterListener(ApplicationEventListener listener, Class<? extends ApplicationEvent>... eventTypes) Registers a listener for one or more ApplicationEvent types on this session.voidregisterListener(SessionEventListener listener, Class<? extends SessionEvent>... eventTypes) Registers a listener for one or more SessionEvent types on this session.voidremoveAttribute(String name) Removes a session attribute.static voidremoveSession(String sessionId) Removes a session from the active sessions map.voidRotates the session ID and regenerates the CSRF token to prevent session fixation attacks.static voidsetAppContext(AppContext context) Sets the application context for resource access.voidsetAttribute(String name, Object value) Sets a session attribute.voidsetCurrentPage(HtmlPage page) Sets the specified page as the current page.setCurrentPage(String pageId) Sets the current page by its unique identifier and returns it.voidsetMaxInactiveInterval(int interval) Sets the maximum time interval between requests before the session expires.voidSets the user identifier for this session, enabling concurrent session control.booleanvalidateCsrfToken(String token) Validates a CSRF token against the session's stored token.
-
Method Details
-
setAppContext
Sets the application context for resource access.Called once during application initialization by the thin library.
- Parameters:
context- the application context
-
getAppContext
Returns the application context.- Returns:
- the application context
-
register
Registers the OorianSession for a web request to the current thread.This method creates or retrieves the OorianSession for the request's session and registers it to the current thread for later retrieval via
get(). It also updates the client profile with information from the request.- Parameters:
request- the web request
-
register
Registers the OorianSession for a session to the current thread.If an OorianSession doesn't exist for this session, a new one is created and stored as a session attribute. The session is then registered to the current thread for later retrieval.
- Parameters:
webSession- the web session- Returns:
- the OorianSession for this session
-
isValid
public static boolean isValid()Checks if a valid OorianSession is registered to the current thread.- Returns:
- true if a session is available, false otherwise
-
get
Returns the OorianSession registered to the current thread.This method provides thread-safe access to the session for the current request. It should be called after
register(HttpServletRequest)has been invoked for the current thread.- Returns:
- the current OorianSession, or null if none is registered
-
getSessions
Returns all active OorianSessions.The returned collection is a live view backed by a
ConcurrentHashMap, so it is safe to iterate while sessions are being added or removed concurrently.- Returns:
- a collection of all active sessions
-
removeSession
Removes a session from the active sessions map.Called by the session monitor when a session is destroyed (timeout or invalidation) to ensure the session is cleaned up from the active sessions map.
- Parameters:
sessionId- the ID of the session to remove
-
setCurrentPage
Sets the current page by its unique identifier and returns it.- Parameters:
pageId- the unique identifier of the page- Returns:
- the HtmlPage instance, or null if not found
-
setCurrentPage
Sets the specified page as the current page.- Parameters:
page- the page to set as current
-
getClientProfile
Returns the client profile for this session.The client profile contains information about the user's device, browser, screen dimensions, and other client-side details.
- Returns:
- the client profile
-
getCreationTime
public long getCreationTime()Returns the time the session was created.- Returns:
- the creation time in milliseconds since epoch
-
getId
Returns the unique session identifier.- Returns:
- the session ID string
-
getLastAccessedTime
public long getLastAccessedTime()Returns the time of last client access.- Returns:
- the last access time in milliseconds since epoch
-
getContextPath
Returns the context path of the web application.- Returns:
- the context path
-
getResourceAsStream
Returns an input stream for reading the specified application resource.- Parameters:
path- the resource path (e.g., "/WEB-INF/config.xml")- Returns:
- an input stream for the resource, or null if not found
-
getRealPath
Returns the real filesystem path for the specified virtual path.- Parameters:
path- the virtual path (e.g., "/WEB-INF/config.xml")- Returns:
- the real path, or null if the translation cannot be performed
-
setMaxInactiveInterval
public void setMaxInactiveInterval(int interval) Sets the maximum time interval between requests before the session expires.- Parameters:
interval- the interval in seconds
-
getMaxInactiveInterval
public int getMaxInactiveInterval()Returns the maximum inactive interval for this session.- Returns:
- the interval in seconds
-
getAttribute
Returns the session attribute with the specified name.- Parameters:
name- the attribute name- Returns:
- the attribute value, or null if not found
-
getAttributeAsString
Returns an attribute as a String.- Parameters:
name- the attribute name- Returns:
- the String value, or null if not found
-
getAttributeAsString
Returns an attribute as a String with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the String value, or defValue if not found
-
getAttributeAsInt
Returns an attribute as an Integer.- Parameters:
name- the attribute name- Returns:
- the Integer value, or null if not found
-
getAttributeAsInt
Returns an attribute as an Integer with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the Integer value, or defValue if not found
-
getAttributeAsLong
Returns an attribute as a Long.- Parameters:
name- the attribute name- Returns:
- the Long value, or null if not found
-
getAttributeAsLong
Returns an attribute as a Long with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the Long value, or defValue if not found
-
getAttributeAsShort
Returns an attribute as a Short.- Parameters:
name- the attribute name- Returns:
- the Short value, or null if not found
-
getAttributeAsShort
Returns an attribute as a Short with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the Short value, or defValue if not found
-
getAttributeAsFloat
Returns an attribute as a Float.- Parameters:
name- the attribute name- Returns:
- the Float value, or null if not found
-
getAttributeAsFloat
Returns an attribute as a Float with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the Float value, or defValue if not found
-
getAttributeAsDouble
Returns an attribute as a Double.- Parameters:
name- the attribute name- Returns:
- the Double value, or null if not found
-
getAttributeAsDouble
Returns an attribute as a Double with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the Double value, or defValue if not found
-
getAttributeAsBoolean
Returns an attribute as a Boolean.- Parameters:
name- the attribute name- Returns:
- the Boolean value, or null if not found
-
getAttributeAsBoolean
Returns an attribute as a Boolean with a default value.- Parameters:
name- the attribute namedefValue- the default value if attribute is not found- Returns:
- the Boolean value, or defValue if not found
-
getAttributeNames
Returns an enumeration of all attribute names in this session.- Returns:
- enumeration of attribute names
-
setAttribute
Sets a session attribute.- Parameters:
name- the attribute namevalue- the attribute value
-
removeAttribute
Removes a session attribute.- Parameters:
name- the attribute name to remove
-
login
Logs in the specified user principal, marking this session as authenticated.This method stores the principal in the session and regenerates the CSRF token to prevent session fixation attacks. For full session ID rotation, use
rotateSession()before calling this method (requires OOR-303).Usage:
OorianAuthenticator auth = Application.getAuthenticator(); UserPrincipal principal = auth.authenticate(username, password); if (principal != null) { OorianSession.get().login(principal); navigateTo("/dashboard"); }- Parameters:
principal- the authenticated user principal (must not be null)- Throws:
IllegalArgumentException- if the principal is null- See Also:
-
logout
public void logout()Logs out the current user and invalidates this session.This method clears the authenticated principal and invalidates the underlying HTTP session, removing all session attributes and unbinding all objects. After calling this method, the session can no longer be used.
- See Also:
-
getPrincipal
Returns the authenticated user principal for this session.- Returns:
- the
UserPrincipal, ornullif no user is authenticated - See Also:
-
isAuthenticated
public boolean isAuthenticated()Checks whether a user is currently authenticated in this session.- Returns:
trueif a user is logged in,falseotherwise- See Also:
-
invalidate
public void invalidate()Invalidates this session and unbinds all objects bound to it. -
isNew
public boolean isNew()Checks if the session was newly created.- Returns:
- true if the session is new, false otherwise
-
getCurrentPage
Returns the current page for this session.- Returns:
- the current HtmlPage, or null if none is set
-
getPage
Returns a cached page by its unique identifier.- Parameters:
pageId- the page identifier- Returns:
- the HtmlPage, or null if not found
-
onThreadComplete
public void onThreadComplete()Called when the current thread's request processing is complete.This method performs cleanup operations in the following order:
- Releases the page cache thread lock
- Starts any queued worker threads
- Removes this session from thread-local storage
- Specified by:
onThreadCompletein interfaceOorianThreadListener
-
getCsrfToken
Returns the CSRF token for this session, creating one if it doesn't exist.The CSRF token is a unique identifier that is generated once per session and used to validate that requests originate from pages served by this application. The token is included in the page as a meta tag and must be sent with all AJAX and WebSocket requests when CSRF protection is enabled.
This method is thread-safe and will always return the same token for a given session.
- Returns:
- The CSRF token for this session.
- See Also:
-
validateCsrfToken
Validates a CSRF token against the session's stored token.This method compares the provided token with the session's CSRF token using a constant-time comparison to prevent timing attacks.
- Parameters:
token- The token to validate (typically from a request parameter).- Returns:
trueif the token is valid,falseotherwise.- See Also:
-
regenerateCsrfToken
Regenerates the CSRF token for this session.This method should be called after sensitive operations such as login or privilege escalation to prevent session fixation attacks. After calling this method, any pages loaded before the regeneration will have an invalid token and will need to be refreshed.
- Returns:
- The new CSRF token.
-
rotateSession
public void rotateSession()Rotates the session ID and regenerates the CSRF token to prevent session fixation attacks.This method should be called after successful authentication (login) to ensure that an attacker who obtained a session ID before authentication cannot use it afterward. The session attributes and internal Oorian state (page cache, client profile, etc.) are preserved.
What happens:
- The servlet container generates a new session ID (attributes are preserved)
- The active sessions map is updated with the new ID
- The CSRF token is regenerated
Usage:
// After successful login OorianSession.get().rotateSession();This method must be called during request processing (e.g., from a page event handler). Calling it outside of a request context will throw an
IllegalStateException.- Throws:
IllegalStateException- if called outside of a request context- See Also:
-
isExpired
public boolean isExpired()Checks whether this session has expired based on the application-wide timeout settings.A session is considered expired if either:
- The idle timeout is configured and the session has been inactive longer than
ApplicationDefaults.getIdleTimeoutMillis() - The absolute timeout is configured and the session has existed longer than
ApplicationDefaults.getAbsoluteTimeoutMillis()
If both timeouts are set to 0 (the default), this method always returns
false, deferring to the servlet container's session timeout.- Returns:
trueif the session has expired,falseotherwise
- The idle timeout is configured and the session has been inactive longer than
-
setUserId
Sets the user identifier for this session, enabling concurrent session control.When a user ID is set, the session is tracked in the user-to-sessions map. If
ApplicationDefaults.getMaxConcurrentSessions()is configured and the user exceeds the limit, the oldest session for that user is automatically invalidated.Call this method after successful authentication. To clear the user association (e.g., on logout), pass
null.- Parameters:
userId- the user identifier, ornullto clear- See Also:
-
getUserId
Returns the user identifier associated with this session.- Returns:
- the user ID, or
nullif no user is associated
-
invalidateSession
public void invalidateSession()Invalidates this session.Removes the session from the active sessions map and the user session tracking map, then invalidates the underlying HTTP session.
-
checkRateLimit
public boolean checkRateLimit()Checks whether the current request is within the configured rate limit.If rate limiting is disabled (max requests = 0), this method always returns
true. The rate limiter is created lazily on first use, using the application-wide rate limit configuration fromApplicationDefaults.- Returns:
trueif the request is allowed,falseif the rate limit is exceeded
-
registerListener
public void registerListener(SessionEventListener listener, Class<? extends SessionEvent>... eventTypes) Registers a listener for one or more SessionEvent types on this session.When a matching SessionEvent is dispatched to this session, the listener's
onEventmethod will be called.- Parameters:
listener- The listener to register.eventTypes- One or more SessionEvent classes to listen for.
-
registerListener
public void registerListener(ApplicationEventListener listener, Class<? extends ApplicationEvent>... eventTypes) Registers a listener for one or more ApplicationEvent types on this session.When a matching ApplicationEvent is dispatched application-wide, the listener's
onEventmethod will be called for this session.- Parameters:
listener- The listener to register.eventTypes- One or more ApplicationEvent classes to listen for.
-
dispatchEvent
Dispatches a SessionEvent to all listeners registered on this session for that event type.- Parameters:
event- The SessionEvent to dispatch.
-
dispatchApplicationEvent
Dispatches an ApplicationEvent to all active sessions.Iterates over all active
OorianSessioninstances and dispatches the event to each session's registered listeners. This enables application-wide broadcasting of events across all user sessions.- Parameters:
event- The ApplicationEvent to dispatch.
-