Application.scala 2.3 KB

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