Application.scala 2.2 KB

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