Application.scala 2.4 KB

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