Application.scala 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package controllers
  2. import play.api.Play.current
  3. import play.api.db.DB
  4. import play.api.mvc._
  5. import play.api.libs.json.Json
  6. import java.util.concurrent._
  7. import scala.concurrent._
  8. import models.{World, Fortune}
  9. import utils._
  10. import utils.DbOperation._
  11. import scala.concurrent.Future
  12. import play.api.libs.concurrent.Execution.Implicits._
  13. import play.core.NamedThreadFactory
  14. object Application extends Controller {
  15. // Anorm code
  16. def getRandomWorlds(n: Int): Future[Seq[World]] = asyncDbOp { implicit connection =>
  17. val random = ThreadLocalRandom.current()
  18. for (_ <- 1 to n) yield {
  19. val randomId: Long = random.nextInt(TestDatabaseRows) + 1
  20. World.findById(randomId)
  21. }
  22. }
  23. def getFortunes(): Future[Seq[Fortune]] = asyncDbOp { implicit connection =>
  24. Fortune.getAll()
  25. }
  26. def updateWorlds(n: Int): Future[Seq[World]] = asyncDbOp { implicit connection =>
  27. val random = ThreadLocalRandom.current()
  28. for(_ <- 1 to n) yield {
  29. val randomId: Long = random.nextInt(TestDatabaseRows) + 1
  30. val world = World.findById(random.nextInt(TestDatabaseRows) + 1)
  31. val randomNumber: Long = random.nextInt(10000) + 1
  32. val updatedWorld = world.copy(randomNumber = randomNumber)
  33. World.updateRandom(updatedWorld)
  34. updatedWorld
  35. }
  36. }
  37. // Common code between Scala database code
  38. protected val TestDatabaseRows = 10000
  39. def db = Action.async {
  40. getRandomWorlds(1).map { worlds =>
  41. Ok(Json.toJson(worlds.head))
  42. }
  43. }
  44. def queries(countString: String) = Action.async {
  45. val n = parseCount(countString)
  46. getRandomWorlds(n).map { worlds =>
  47. Ok(Json.toJson(worlds))
  48. }
  49. }
  50. def fortunes() = Action.async {
  51. getFortunes().map { dbFortunes =>
  52. val appendedFortunes = Fortune(0, "Additional fortune added at request time.") :: (dbFortunes.to[List])
  53. Ok(views.html.fortune(appendedFortunes))
  54. }
  55. }
  56. def update(queries: String) = Action.async {
  57. val n = parseCount(queries)
  58. updateWorlds(n).map { worlds =>
  59. Ok(Json.toJson(worlds))
  60. }
  61. }
  62. private def parseCount(s: String): Int = {
  63. try {
  64. val parsed = java.lang.Integer.parseInt(s, 10)
  65. parsed match {
  66. case i if i < 1 => 1
  67. case i if i > 500 => 500
  68. case i => i
  69. }
  70. } catch {
  71. case _: NumberFormatException => 1
  72. }
  73. }
  74. }