Skip to content

Instantly share code, notes, and snippets.

@cvrabie
Created Aug 2, 2012
Embed
What would you like to do?
Transaction wrapper for ORBroker in LiftWeb
class Boot extends Loggable {
/* ORBROKER JDBC CONNECTION */
val broker = (for{
dbDriver <- Props.get("db.driver") ?~! "Need the db.driver property"
dbUrl <- Props.get("db.url") ?~! "Need the db.url property"
dbUser <- Props.get("db.user") ?~! "Need the db.user property"
dbPass <- Props.get("db.password") ?~! "Need the db.password property"
}yield {
val cf = new File(classOf[Boot].getResource("/sql").toURI)
ORBrokerHelper(dbDriver,dbUrl,dbUser,dbPass,cf)
}) match {
case Full(b) => b
case f:Failure => throw new InitializationError(f.messageChain)
case _ => throw new InitializationError("Could not initialize ORBroker")
}
S.addAround(broker.transactionWrapper)
LiftRules.statelessDispatchTable.append(RestEndpoint)
}
package schema
import net.liftweb.util.LoanWrapper
import org.orbroker.{Transactional, Broker}
import org.orbroker.config.{FileSystemRegistrant, BrokerConfig, SimpleDataSource}
import java.io.File
import net.liftweb.http.RequestVar
import net.liftweb.common.Loggable
/**
* User: cvrabie1
* Date: 02/08/2012
*/
object ORBrokerHelper extends Loggable{
def apply(broker:Broker):ORBrokerHelper = new ORBrokerHelper(broker)
def apply(dbDriver:String, dbUrl:String, dbUser:String, dbPass:String, configFolder:File):ORBrokerHelper = {
val dataSource = new SimpleDataSource(dbUrl, dbDriver)
val brokerConfig = new BrokerConfig(dataSource)
brokerConfig.setUser(dbUser, dbPass)
FileSystemRegistrant(configFolder).register(brokerConfig)
brokerConfig.verify(TokensDriverScore.idSet)
apply(Broker(brokerConfig))
}
object session extends RequestVar[Transactional](null)
}
class ORBrokerHelper(val broker:Broker) {
val transactionWrapper = new LoanWrapper {
def apply[T](f: => T) = {
broker.transactional(){ session =>
var txOk = false
ORBrokerHelper.session(session)
try{
val res = f
txOk = true
res
}catch {
case e => {
txOk = false
throw e
}
}finally{
if(txOk) session.commit()
else session.rollback()
}
}
}
}
}
object BotRest extends RestEndpoint {
serve{
case Get("test" :: Nil, _) => {
val resp = ORBrokerHelper.session.selectAll(TokensTest.selectTest, "id" -> 1)
InMemoryResponse(resp.toString().getBytes(),Nil,Nil,200)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment