Application.scala 2.4 KB

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