B4J Code Snippet [Server] Persistent sessions

Session are usually stored in memory so if you restart the server all the sessions (including their attributes) will be lost. So if you want to save sessions data on disk place the code below in the code module and call the sub ServerUsePersistentSessions.

StoreDirectory - where the sessions data will be stored
SavePeriod - the period in seconds at which sessions are periodically saved to disk
LazyLoad - Setting this to True will make server load sessions when it receives the first request for a session or the session scavenger(Finds sessions that have timed out and invalidates them) runs for the first time.

B4X:
'Sets the server to use persisten sessions saved on the disk rather then in memory
Public Sub ServerUsePersistentSessions(ServerObject As Server, StoreDirectory As String, SavePeriod As Int, LazyLoad As Boolean)
    If ServerObject <> Null Then
        Dim joMe As JavaObject = Me
        joMe.RunMethod("initializeSessionStoreDirectory", Array(StoreDirectory))
        Dim joServer As JavaObject = ServerObject
        joServer.GetFieldJO("context").RunMethodJO("getSessionHandler", Null).RunMethodJO("getSessionManager", Null).RunMethod("setStoreDirectory", Array(joMe.GetFieldJO("sessionStoreDirectory")))
        joServer.GetFieldJO("context").RunMethodJO("getSessionHandler", Null).RunMethodJO("getSessionManager", Null).RunMethod("setSavePeriod", Array(SavePeriod))
        joServer.GetFieldJO("context").RunMethodJO("getSessionHandler", Null).RunMethodJO("getSessionManager", Null).RunMethod("setLazyLoad", Array(LazyLoad))
        joServer.GetFieldJO("context").RunMethodJO("getSessionHandler", Null).RunMethodJO("getSessionManager", Null).RunMethod("restoreSessions", Null)
    End If   
End Sub

#IF JAVA
import java.io.File;

public static File sessionStoreDirectory;

public static void initializeSessionStoreDirectory(String pathname) {
    sessionStoreDirectory = new File(pathname);
}
#END IF
 

mindful

Active Member
Licensed User
There is a problem with setting persisten session... take the following scenario:

1. start the server
2. set persistent sessions (like above)
3. connect to the server - it will create the session which will be saved on disk
4. stop the server
5. start the server
6. connect to the server again when it connects again the session maxInactiveInterval shows -1393754107 instead of 10800 ..

So the session will never expire :(
 
Top