Lift framework lacks the ability to fetch a session creation timestamp by default. This post will provide a short example of how one can do this while working with Lift.
Note: This example uses org.joda.time.DateTime
class for working with date.
Lift provides an ability to customize a session creation flow by injecting a function into the LiftRules.sessionCreator
configuration value during the application bootstrapping. It is a function which accepts an HTTPSession
and a String
with an application context path wrapped in a LiftSession
. And that’s where a session creation timestamp value can be added to the session:
bootstrap.liftweb.Boot
import net.liftweb.common._
import net.liftweb.http._
import org.joda.time.DateTime
class Boot {
def boot {
LiftRules.sessionCreator = {
case (httpSession, contextPath) =>
// set the "creation_timestamp" session attribute as the current date/time
httpSession.setAttribute("creation_timestamp", new DateTime())
// create a new LiftSession based on the HTTPSession and the application context
new LiftSession(contextPath, httpSession.sessionId, Full(httpSession))
}
...
}
}
Code language: JavaScript (javascript)
The following code can be used to extract a creation timestamp from the Lift session:
import net.liftweb.common._
import net.liftweb.http._
import net.liftweb.util.Helpers
import org.joda.time.DateTime
...
val sessionCreationTimestamp: Box[DateTime] = for {
liftSession <- S.session
httpSession <- liftSession.httpSession
timestamp <- Helpers.tryo {
// a value of the "creation_timestamp" session attribute is extracted here
httpSession.attribute("creation_timestamp").asInstanceOf[DateTime]
}
} yield timestamp
...
Code language: JavaScript (javascript)
Here we are extracting the LiftSession
. Then retrieving an underlying instance of the HTTPSession
to be able to extract a value of the session scope attribute by its name. The latter is done by calling the attribute(key: String)
method of the HTTPSession
.
The value of an attribute will be returned as an instance of scala’s Any
. Then it can be casted to the actual type using the asInstanceOf[T]
method. The T
type parameter should be set with the desired result type. In case the specified type mismatches the actual type of a value, a java.lang.ClassCastException
will be thrown.
Hope you find this tip helpful.