play.api.ApplicationLoader.Context Scala Examples

The following examples show how to use play.api.ApplicationLoader.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: AppLoader.scala    From OAuth2-mock-play   with MIT License 5 votes vote down vote up
import models.{AuthorizeStoreCache, PendingContentStoreCache}
import play.api.ApplicationLoader.Context
import play.api.cache.EhCacheComponents
import play.api.mvc.EssentialFilter
import play.api.routing.Router
import play.api._
import play.filters.gzip.GzipFilter
import router.Routes

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = {
    LoggerConfigurator(context.environment.classLoader)
      .foreach(_.configure(context.environment))
    new AppComponents(context).application
  }
}

class AppComponents(context: Context)
    extends BuiltInComponentsFromContext(context)
    with EhCacheComponents {

  implicit val executionContext =
    play.api.libs.concurrent.Execution.Implicits.defaultContext
  implicit lazy val authorizeStoreCache = AuthorizeStoreCache(
    cacheApi("authorizeStore"))
  implicit lazy val pendingConsentStoreCache = PendingContentStoreCache(
    cacheApi("pendingConsentStore"))
  implicit val config = configuration.underlying

  lazy val applicationController = new controllers.Application
  lazy val assets                = new controllers.Assets(httpErrorHandler)

  // Routes is a generated class
  override def router: Router =
    new Routes(httpErrorHandler, applicationController, assets)

  val gzipFilter = new GzipFilter(shouldGzip = (request, response) => {
    val contentType = response.header.headers.get("Content-Type")
    contentType.exists(_.startsWith("text/html")) ||
    request.path.endsWith("jsroutes.js")
  })

  override lazy val httpFilters: Seq[EssentialFilter] = Seq(gzipFilter)
} 
Example 2
Source File: ClippyApplicationLoader.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
import api.UiApiImpl
import com.softwaremill.id.DefaultIdGenerator
import controllers._
import dal.AdvicesRepository
import play.api.ApplicationLoader.Context
import play.api._
import play.api.i18n.I18nComponents
import play.api.mvc.EssentialFilter
import router.Routes
import util.{DatabaseConfig, SqlDatabase}
import util.email.{DummyEmailService, SendgridEmailService}

class ClippyApplicationLoader extends ApplicationLoader {
  def load(context: Context) = {
    Logger.configure(context.environment)
    val c = new ClippyComponents(context)
    c.database.updateSchema()
    c.application
  }
}

class ClippyComponents(context: Context) extends BuiltInComponentsFromContext(context) with I18nComponents {

  implicit val ec = scala.concurrent.ExecutionContext.Implicits.global

  lazy val router =
    new Routes(httpErrorHandler, applicationController, assets, webJarAssets, advicesController, autowireController)

  lazy val contactEmail = configuration.getString("email.contact").getOrElse("?")
  lazy val emailService = SendgridEmailService
    .createFromEnv(contactEmail)
    .getOrElse(new DummyEmailService)

  lazy val webJarAssets = new WebJarAssets(httpErrorHandler, configuration, environment)
  lazy val assets       = new controllers.Assets(httpErrorHandler)

  lazy val idGenerator = new DefaultIdGenerator()

  lazy val applicationController = new ApplicationController()

  lazy val database          = SqlDatabase.create(new DatabaseConfig { override val rootConfig = configuration.underlying })
  lazy val advicesRepository = new AdvicesRepository(database, idGenerator)

  lazy val uiApiImpl          = new UiApiImpl(advicesRepository, emailService, contactEmail)
  lazy val autowireController = new AutowireController(uiApiImpl)

  lazy val advicesController = new AdvicesController(advicesRepository)

  override lazy val httpFilters: Seq[EssentialFilter] = List(new HttpsFilter())
} 
Example 3
Source File: SpringApplicationLoader.scala    From play-spring-loader   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.play.spring

import controllers.Assets
import play.api.ApplicationLoader.Context
import play.api._
import play.api.inject._
import play.core.WebCommands


  def defaultOverrides(context: ApplicationLoader.Context) = {
    Seq(
      new Module {
        def bindings(environment: Environment, configuration: Configuration) = Seq(
          bind[OptionalSourceMapper] to new OptionalSourceMapper(context.sourceMapper),
          bind[WebCommands] to context.webCommands,
          bind[Assets].to[Assets],
          bind[play.Configuration].to[play.Configuration])
      })
  }

} 
Example 4
Source File: ServerSpec.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Millis, Second, Span}
import org.scalatestplus.play._
import play.api.ApplicationLoader.Context
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.mvc.Results
import play.api.test.Helpers._

class ServerSpec
    extends PlaySpec
    with OneServerPerSuiteWithComponents[MockApiComponents with AhcWSComponents]
    with Results
    with ScalaFutures {

  override implicit def patienceConfig: PatienceConfig = PatienceConfig(Span(1, Second), Span(50, Millis))
  override def createComponents(context: Context) = new MockApiComponents(context) with AhcWSComponents

  "Server query" should {
    "work" in {
      implicit val ec = app.materializer.executionContext
      val wsClient = components.wsClient

      whenReady(wsUrl("/ping")(portNumber, wsClient).get) { response =>
        response.status mustBe OK
        response.body mustBe "pong"
      }
    }
  }
} 
Example 5
Source File: ApplicationSpec.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import org.scalatestplus.play.PlaySpec
import play.api.ApplicationLoader.Context
import play.api.test.Helpers._
import play.api.test._


class ApplicationSpec extends PlaySpec with OneAppPerTestWithComponents[MockApiComponents] {

  override def createComponents(context: Context) = new MockApiComponents(context)

  "Routes" should {
    "send 404 on a bad request" in {
      route(app, FakeRequest(GET, "/boum")).map(status) mustBe Some(NOT_FOUND)
    }
  }

  "HomeController" should {
    "render the index page" in {
      val home = route(app, FakeRequest(GET, "/ping")).get
      status(home) mustBe OK
      contentType(home) mustBe Some("text/plain")
      contentAsString(home) must include("pong")
    }
  }
} 
Example 6
Source File: LaunchQueueControllerTest.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api.v1.controllers

import dcos.metronome.api.v1.models.QueuedJobRunMapWrites
import dcos.metronome.api.{MockApiComponents, OneAppPerTestWithComponents, TestAuthFixture}
import dcos.metronome.model.{JobId, JobRunSpec, QueuedJobRunInfo}
import dcos.metronome.queue.LaunchQueueService
import mesosphere.marathon.core.plugin.PluginManager
import mesosphere.marathon.state.Timestamp
import org.mockito.Mockito._
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.mockito.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.ApplicationLoader.Context
import play.api.test.FakeRequest
import play.api.test.Helpers.{GET, route, _}

class LaunchQueueControllerTest
    extends PlaySpec
    with OneAppPerTestWithComponents[MockApiComponents]
    with ScalaFutures
    with MockitoSugar
    with BeforeAndAfter {

  private val queueServiceMock = mock[LaunchQueueService]

  "GET /queue" should {
    "return list of jobs in the queue" in {
      val queuedJobRun = QueuedJobRunInfo(JobId("job"), Timestamp.zero, JobRunSpec())
      val queuedJobList = List(queuedJobRun)
      when(queueServiceMock.list()).thenReturn(queuedJobList)
      val response = route(app, FakeRequest(GET, "/v1/queue")).get

      status(response) mustBe OK
      contentType(response) mustBe Some("application/json")
      contentAsJson(response) mustBe QueuedJobRunMapWrites.writes(queuedJobList.groupBy(_.jobId))
    }

    "return nothing when not authorized to see the job" in {
      auth.authorized = false
      val queuedJobList = List(QueuedJobRunInfo(JobId("job"), Timestamp.zero, JobRunSpec()))
      when(queueServiceMock.list()).thenReturn(queuedJobList)
      val response = route(app, FakeRequest(GET, "/v1/queue")).get

      contentAsJson(response) mustBe QueuedJobRunMapWrites.writes(Map.empty)
    }
  }

  val auth = new TestAuthFixture

  before {
    auth.authorized = true
    auth.authenticated = true
  }

  override def createComponents(context: Context): MockApiComponents =
    new MockApiComponents(context) {
      override lazy val queueService: LaunchQueueService = queueServiceMock
      override lazy val pluginManager: PluginManager = auth.pluginManager
    }
} 
Example 7
Source File: ApplicationControllerTest.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api.v1.controllers

import dcos.metronome.api.{MockApiComponents, OneAppPerTestWithComponents}
import mesosphere.marathon.core.election.ElectionService
import org.mockito.Mockito._
import org.scalatestplus.play.PlaySpec
import org.scalatest.Matchers._
import org.scalatestplus.mockito.MockitoSugar
import play.api.ApplicationLoader.Context
import play.api.test.FakeRequest
import play.api.test.Helpers._

class ApplicationControllerTest extends PlaySpec with OneAppPerTestWithComponents[MockApiComponents] with MockitoSugar {

  val electionServiceMock = mock[ElectionService]

  "ping" should {
    "send a pong" in {
      val ping = route(app, FakeRequest(GET, "/ping")).get
      status(ping) mustBe OK
      contentType(ping) mustBe Some("text/plain")
      contentAsString(ping) must include("pong")
    }
  }

  "metrics" should {
    "give metrics as json" in {
      val metrics = route(app, FakeRequest(GET, "/v1/metrics")).get
      status(metrics) mustBe OK
      contentType(metrics) mustBe Some("application/json")
    }
  }

  "info" should {
    "send version info" in {
      val info = route(app, FakeRequest(GET, "/info")).get
      status(info) mustBe OK
      contentType(info) mustBe Some("application/json")
      (contentAsJson(info) \ "version").as[String] should include regex "\\d+.\\d+.\\d+".r
      (contentAsJson(info) \ "libVersion").as[String] should include regex "\\d+.\\d+.\\d+".r
    }
  }

  "leader" should {
    "send leader info" in {
      when(electionServiceMock.leaderHostPort).thenReturn(Some("localhost:8080"))
      val info = route(app, FakeRequest(GET, "/leader")).get
      status(info) mustBe OK
      contentType(info) mustBe Some("application/json")
      (contentAsJson(info) \ "leader").as[String] should be("localhost:8080")
    }

    "send not found" in {
      when(electionServiceMock.leaderHostPort).thenReturn(None)
      val info = route(app, FakeRequest(GET, "/leader")).get
      status(info) mustBe NOT_FOUND
      contentType(info) mustBe Some("application/json")
      (contentAsJson(info) \ "message").as[String] should be("There is no leader")
    }
  }

  override def createComponents(context: Context): MockApiComponents =
    new MockApiComponents(context) {
      override lazy val electionService = electionServiceMock
    }
} 
Example 8
Source File: SampleApplicationLoader.scala    From monix-sample   with Apache License 2.0 5 votes vote down vote up
package config

import controllers.{ApplicationController, Assets}
import play.api.ApplicationLoader.Context
import play.api._
import play.api.i18n.I18nComponents
import router.Routes

class SampleApplicationLoader extends ApplicationLoader {
  def load(context: Context) = {
    new SampleComponents(context).application
  }
}

class SampleComponents(context: Context) extends BuiltInComponentsFromContext(context)
  with I18nComponents {

  lazy val router = new Routes(httpErrorHandler, applicationController, assets)

  lazy val assets = new Assets(httpErrorHandler)
  lazy val applicationController = new ApplicationController()(environment, actorSystem, materializer)
} 
Example 9
Source File: WebGatewayLoader.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
import javax.inject.Inject
import com.lightbend.lagom.internal.client.CircuitBreakerMetricsProviderImpl
import com.lightbend.lagom.scaladsl.api.ServiceLocator.NoServiceLocator
import com.lightbend.lagom.scaladsl.api.{ServiceAcl, ServiceInfo}
import com.lightbend.lagom.scaladsl.client.LagomServiceClientComponents
import com.lightbend.lagom.scaladsl.devmode.LagomDevModeComponents
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.consumer.api.WFConsumerService
import com.softwaremill.macwire._
import controllers.{Assets, WFConsumerController, WFController}
import play.api.ApplicationLoader.Context
import play.api.i18n.I18nComponents
import play.api.libs.ws.ahc.AhcWSComponents
import play.api._
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import router.Routes
import scala.collection.immutable
import scala.concurrent.ExecutionContext
import com.typesafe.conductr.bundlelib.lagom.scaladsl.ConductRApplicationComponents

abstract class WebGateway @Inject()(context: Context) extends BuiltInComponentsFromContext(context)
  with I18nComponents
  with AhcWSComponents
  with LagomServiceClientComponents {

  override lazy val serviceInfo: ServiceInfo = ServiceInfo(
    "wf-frontend",
    Map(
      "wf-frontend" -> immutable.Seq(ServiceAcl.forPathRegex("(?!/api/).*"))
    )
  )
  override implicit lazy val executionContext: ExecutionContext = actorSystem.dispatcher
  override lazy val router = {
    val prefix = "/"
    wire[Routes]
  }

  lazy val wfService = serviceClient.implement[WFService]
  lazy val wfConsumerService = serviceClient.implement[WFConsumerService]
  lazy val wfController = wire[WFController]
  lazy val wfConsumerController = wire[WFConsumerController]
  lazy val assets = wire[Assets]
}

class WebGatewayLoader extends ApplicationLoader {
  override def load(context: Context): Application = context.environment.mode match {
    case Mode.Dev =>
      new WebGateway(context) with LagomDevModeComponents {}.application
    case _ =>
      (new WebGateway(context) with ConductRApplicationComponents {
        override lazy val circuitBreakerMetricsProvider = new CircuitBreakerMetricsProviderImpl(actorSystem)
      }).application
  }
} 
Example 10
Source File: WebGatewayLoader.scala    From Scala-Reactive-Programming   with MIT License 5 votes vote down vote up
import javax.inject.Inject
import com.lightbend.lagom.scaladsl.api.ServiceLocator.NoServiceLocator
import com.lightbend.lagom.scaladsl.api.{ServiceAcl, ServiceInfo}
import com.lightbend.lagom.scaladsl.client.LagomServiceClientComponents
import com.lightbend.lagom.scaladsl.devmode.LagomDevModeComponents
import com.packt.publishing.wf.api.WFService
import com.packt.publishing.wf.consumer.api.WFConsumerService
import com.softwaremill.macwire._
import controllers.{Assets, WFConsumerController, WFController}
import play.api.ApplicationLoader.Context
import play.api.i18n.I18nComponents
import play.api.libs.ws.ahc.AhcWSComponents
import play.api._
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import router.Routes

import scala.collection.immutable
import scala.concurrent.ExecutionContext

abstract class WebGateway @Inject()(context: Context) extends BuiltInComponentsFromContext(context)
  with I18nComponents
  with AhcWSComponents
  with LagomServiceClientComponents{

  override lazy val serviceInfo: ServiceInfo = ServiceInfo(
    "wf-frontend",
    Map(
      "wf-frontend" -> immutable.Seq(ServiceAcl.forPathRegex("(?!/api/).*"))
    )
  )
  override implicit lazy val executionContext: ExecutionContext = actorSystem.dispatcher
  override lazy val router = {
    val prefix = "/"
    wire[Routes]
  }

  lazy val wfService = serviceClient.implement[WFService]
  lazy val wfConsumerService = serviceClient.implement[WFConsumerService]
  lazy val wfController = wire[WFController]
  lazy val wfConsumerController = wire[WFConsumerController]
  lazy val assets = wire[Assets]
}

class WebGatewayLoader extends ApplicationLoader {
  override def load(context: Context): Application = context.environment.mode match {
    case Mode.Dev =>
      new WebGateway(context) with LagomDevModeComponents {}.application
    case _ =>
      new WebGateway(context) {
        override def serviceLocator = NoServiceLocator
      }.application
  }
} 
Example 11
Source File: MyApplicationLoader.scala    From get-you-a-license   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import controllers.{AssetsComponents, Main}
import filters.OnlyHttpsFilter
import org.webjars.play.{RequireJS, WebJarAssets, WebJarsUtil}
import play.api.{Application, ApplicationLoader, BuiltInComponentsFromContext}
import play.api.ApplicationLoader.Context
import play.api.libs.concurrent.{DefaultFutures, Futures}
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.mvc.EssentialFilter
import play.api.routing.Router
import play.filters.HttpFiltersComponents
import play.filters.csrf.CSRFFilter
import router.Routes
import utils.GitHub

class MyApplicationLoader extends ApplicationLoader {
  def load(context: Context): Application = {
    new MyComponents(context).application
  }
}

class MyComponents(context: Context) extends BuiltInComponentsFromContext(context) with AhcWSComponents with AssetsComponents with HttpFiltersComponents {

  override def httpFilters: Seq[EssentialFilter] = {
    super.httpFilters.filterNot(_.isInstanceOf[CSRFFilter]) :+ new OnlyHttpsFilter(environment)
  }

  lazy val futures = new DefaultFutures(actorSystem)

  lazy val webJarsUtil = new WebJarsUtil(context.initialConfiguration, context.environment)

  lazy val indexView = new views.html.index(webJarsUtil)
  lazy val setupView = new views.html.setup(webJarsUtil)
  lazy val orgView = new views.html.org(webJarsUtil)

  lazy val gitHub = new GitHub(context.initialConfiguration, wsClient, futures)
  lazy val main = new Main(gitHub, controllerComponents)(indexView, orgView, setupView)

  lazy val requireJs = new RequireJS(webJarsUtil)
  lazy val webJarAssets = new WebJarAssets(httpErrorHandler, assetsMetadata)
  lazy val webJarsRoutes = new webjars.Routes(httpErrorHandler, requireJs, webJarAssets)

  lazy val router: Router = new Routes(httpErrorHandler, main, assets, webJarsRoutes)
} 
Example 12
Source File: AppLoader.scala    From play-quill-jdbc   with MIT License 5 votes vote down vote up
import java.io.Closeable
import javax.sql.DataSource

import controllers.UsersController
import io.getquill._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.Evolutions
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.api.routing.sird._
import models.{Users}

class AppLoader extends ApplicationLoader {
  override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {

    lazy val db = new H2JdbcContext[SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])


    lazy val users = new Users(db)
    lazy val usersController = new UsersController(users)

    val router = Router.from {
      case GET(p"/users/${long(id)}")    => usersController.get(id)
      case POST(p"/users")               => usersController.create
      case DELETE(p"/users/${long(id)}") => usersController.delete(id)
      case PUT(p"/users/${long(id)}")    => usersController.update(id)
    }

    override lazy val injector: Injector =
      new SimpleInjector(NewInstanceInjector) + users + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global

    Evolutions.applyEvolutions(dbApi.database("default"))

  }.application
} 
Example 13
package commons_test.test_helpers

import java.util.concurrent.Executors

import commons_test.test_helpers.RealWorldWithServerAndTestConfigBaseTest.RealWorldWithTestConfig
import commons_test.test_helpers.WsScalaTestClientWithHost.TestWsClient
import config.RealWorldComponents
import org.scalatest._
import play.api.ApplicationLoader.Context
import play.api.Configuration
import play.api.http.Status
import play.api.test.DefaultAwaitTimeout

import scala.concurrent.ExecutionContext

trait RealWorldWithServerBaseTest extends FlatSpec
  with MustMatchers
  with OptionValues
  with WsScalaTestClientWithHost
  with OneServerPerTestWithComponents_FixedForCompileTimeTestSetUp
  with Status
  with DefaultAwaitTimeout
  with WithAwaitUtilities
  with WithTestExecutionContext {

  override implicit val executionContext: ExecutionContext = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(1))

  implicit val host: Host = Host("http://localhost:")

  override type TestComponents <: RealWorldWithTestConfig

  implicit def wsClientWithConnectionData: TestWsClient = {
    TestWsClient(host, portNumber, components.wsClient)
  }

}

object RealWorldWithServerAndTestConfigBaseTest {

  class RealWorldWithTestConfig(context: Context) extends RealWorldComponents(context) {

    override def configuration: Configuration = {
      val testConfig = Configuration.from(TestUtils.config)
      val config = super.configuration
      testConfig.withFallback(config)
    }

  }

}

class RealWorldWithServerAndTestConfigBaseTest extends RealWorldWithServerBaseTest {
  override type TestComponents = RealWorldWithTestConfig

  override def createComponents: TestComponents = {
      new RealWorldWithTestConfig(context)
    }
} 
Example 14
Source File: AuthenticationTest.scala    From scala-play-realworld-example-app   with MIT License 5 votes vote down vote up
package users.controllers

import authentication.exceptions.MissingOrInvalidCredentialsCode
import com.softwaremill.macwire.wire
import commons_test.test_helpers.RealWorldWithServerAndTestConfigBaseTest.RealWorldWithTestConfig
import commons_test.test_helpers.{ProgrammaticDateTimeProvider, RealWorldWithServerAndTestConfigBaseTest, WithUserTestHelper}
import play.api.ApplicationLoader.Context
import play.api.http.HeaderNames
import play.api.libs.json._
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import users.models.UserDetailsWithToken
import users.test_helpers.UserRegistrations

import scala.concurrent.ExecutionContext

class AuthenticationTest extends RealWorldWithServerAndTestConfigBaseTest with WithUserTestHelper {

  val fakeApiPath: String = "test"

  val accessTokenJsonAttrName: String = "access_token"

  val programmaticDateTimeProvider = new ProgrammaticDateTimeProvider

  "Authentication" should "allow everyone to public API" in await {
    for {
      response <- wsUrl(s"/$fakeApiPath/public").get()
    } yield {
      response.status.mustBe(OK)
    }
  }

  it should "block request without jwt token" in await {
    for {
      response <- wsUrl(s"/$fakeApiPath/authenticationRequired").get()
    } yield {
      response.status.mustBe(UNAUTHORIZED)
      response.json.as[HttpExceptionResponse].code.mustBe(MissingOrInvalidCredentialsCode)
    }
  }

  it should "block request with invalid jwt token" in await {
    for {
      response <- wsUrl(s"/$fakeApiPath/authenticationRequired")
        .addHttpHeaders(HeaderNames.AUTHORIZATION -> "TokenS invalidJwtToken")
        .get()
    } yield {
      response.status.mustBe(UNAUTHORIZED)
      response.json.as[HttpExceptionResponse].code.mustBe(MissingOrInvalidCredentialsCode)
    }
  }

  it should "allow authenticated user to secured API" in await {
    for {
      userDetailsWithToken <- userTestHelper.register[UserDetailsWithToken](UserRegistrations.petycjaRegistration)

      response <- wsUrl(s"/$fakeApiPath/authenticationRequired")
        .addHttpHeaders(HeaderNames.AUTHORIZATION -> s"Token ${userDetailsWithToken.token}")
        .get()
    } yield {
      response.status.mustBe(OK)
    }
  }

  override def createComponents: RealWorldWithTestConfig =
    new JwtAuthenticationTestComponents(programmaticDateTimeProvider, context)
}

class AuthenticationTestController(authenticatedAction: AuthenticatedActionBuilder,
                                   components: ControllerComponents,
                                   implicit private val ex: ExecutionContext)
  extends AbstractController(components) {

  def public: Action[AnyContent] = Action { _ =>
    Results.Ok
  }

  def authenticated: Action[AnyContent] = authenticatedAction { request =>
    Ok(Json.toJson(request.user.securityUserId.value))
  }

}

class JwtAuthenticationTestComponents(dateTimeProvider: ProgrammaticDateTimeProvider, context: Context)
  extends RealWorldWithTestConfig(context) {

  lazy val authenticationTestController: AuthenticationTestController = wire[AuthenticationTestController]

  override lazy val router: Router = {
    val testControllerRoutes: PartialFunction[RequestHeader, Handler] = {
      case GET(p"/test/public") => authenticationTestController.public
      case GET(p"/test/authenticationRequired") => authenticationTestController.authenticated
    }

    Router.from(routes.orElse(testControllerRoutes))
  }
} 
Example 15
Source File: ArticleCreateTest.scala    From scala-play-realworld-example-app   with MIT License 5 votes vote down vote up
package articles

import java.time.Instant

import articles.models.ArticleWrapper
import articles.test_helpers.Articles
import commons.repositories.DateTimeProvider
import commons_test.test_helpers.RealWorldWithServerAndTestConfigBaseTest.RealWorldWithTestConfig
import commons_test.test_helpers.{FixedDateTimeProvider, RealWorldWithServerAndTestConfigBaseTest, WithArticleTestHelper, WithUserTestHelper}
import play.api.ApplicationLoader.Context
import play.api.libs.ws.WSResponse
import users.models.UserDetailsWithToken
import users.test_helpers.UserRegistrations

class ArticleCreateTest extends RealWorldWithServerAndTestConfigBaseTest with WithArticleTestHelper with WithUserTestHelper {

  val dateTime: Instant = Instant.now

  "Create article" should "create valid article without tags" in await {
    for {
      userDetailsWithToken <- userTestHelper.register[UserDetailsWithToken](UserRegistrations.petycjaRegistration)
      newArticle = Articles.hotToTrainYourDragon.copy(tagList = Nil)
      response <- articleTestHelper.create[WSResponse](newArticle, userDetailsWithToken.token)
    } yield {
      response.status.mustBe(OK)
      val article = response.json.as[ArticleWrapper].article
      article.title.mustBe(newArticle.title)
      article.updatedAt.mustBe(dateTime)
      article.tagList.isEmpty.mustBe(true)
    }
  }

  it should "create valid article with dragons tag" in await {
    for {
      userDetailsWithToken <- userTestHelper.register[UserDetailsWithToken](UserRegistrations.petycjaRegistration)
      newArticle = Articles.hotToTrainYourDragon
      response <- articleTestHelper.create[WSResponse](newArticle, userDetailsWithToken.token)
    } yield {
      response.status.mustBe(OK)
      val article = response.json.as[ArticleWrapper].article
      article.title.mustBe(newArticle.title)
      article.updatedAt.mustBe(dateTime)
      article.tagList.size.mustBe(1L)
    }
  }


  it should "create article and associate it with existing dragons tag" in await {
    def createFirstArticleToCreateDragonsTag(userDetailsWithToken: UserDetailsWithToken) = {
      articleTestHelper.create[WSResponse](Articles.hotToTrainYourDragon, userDetailsWithToken.token)
    }

    for {
      userDetailsWithToken <- userTestHelper.register[UserDetailsWithToken](UserRegistrations.petycjaRegistration)
      _ <- createFirstArticleToCreateDragonsTag(userDetailsWithToken)
      response <- articleTestHelper.create[WSResponse](Articles.hotToTrainYourDragon, userDetailsWithToken.token)
    } yield {
      response.status.mustBe(OK)
      val article = response.json.as[ArticleWrapper].article
      article.tagList.size.mustBe(1L)
    }
  }

  it should "create article and set author" in await {
    val registration = UserRegistrations.petycjaRegistration
    for {
      userDetailsWithToken <- userTestHelper.register[UserDetailsWithToken](registration)
      response <- articleTestHelper.create[WSResponse](Articles.hotToTrainYourDragon, userDetailsWithToken.token)
    } yield {
      response.status.mustBe(OK)
      val article = response.json.as[ArticleWrapper].article
      article.author.username.mustBe(registration.username)
    }
  }

  it should "generate slug based on title" in await {
    for {
      userDetailsWithToken <- userTestHelper.register[UserDetailsWithToken](UserRegistrations.petycjaRegistration)
      titlePart1 = "the"
      titlePart2 = "title"
      response <- articleTestHelper.create[WSResponse](Articles.hotToTrainYourDragon, userDetailsWithToken.token)
    } yield {
      response.status.mustBe(OK)
      val slug = response.json.as[ArticleWrapper].article.slug
      slug.contains(include(titlePart1).and(include(titlePart2)))
    }
  }

  override def createComponents: RealWorldWithTestConfig = {
    new RealWorldWithTestConfigWithFixedDateTimeProvider(new FixedDateTimeProvider(dateTime), context)
  }

}

class RealWorldWithTestConfigWithFixedDateTimeProvider(dtProvider: DateTimeProvider, context: Context)
  extends RealWorldWithTestConfig(context) {

  override lazy val dateTimeProvider: DateTimeProvider = dtProvider
} 
Example 16
package config

import java.util.UUID

import _root_.controllers.AssetsComponents
import articles.ArticleComponents
import authentication.AuthenticationComponents
import users.UserComponents
import play.api.ApplicationLoader.Context
import play.api._
import play.api.cache.AsyncCacheApi
import play.api.cache.ehcache.EhCacheComponents
import play.api.db.evolutions.{DynamicEvolutions, EvolutionsComponents}
import play.api.db.slick._
import play.api.db.slick.evolutions.SlickEvolutionsComponents
import play.api.i18n._
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.mvc._
import play.api.routing.Router
import play.filters.cors.{CORSConfig, CORSFilter}
import slick.basic.{BasicProfile, DatabaseConfig}

class RealWorldApplicationLoader extends ApplicationLoader {
  def load(context: Context): Application = new RealWorldComponents(context).application
}

class RealWorldComponents(context: Context) extends BuiltInComponentsFromContext(context)
  with SlickComponents
  with SlickEvolutionsComponents
  with AssetsComponents
  with I18nComponents
  with EvolutionsComponents
  with AhcWSComponents
  with AuthenticationComponents
  with  UserComponents
  with ArticleComponents
  with EhCacheComponents {

  override lazy val slickApi: SlickApi =
    new DefaultSlickApi(environment, configuration, applicationLifecycle)(executionContext)

  override lazy val databaseConfigProvider: DatabaseConfigProvider = new DatabaseConfigProvider {
    def get[P <: BasicProfile]: DatabaseConfig[P] = slickApi.dbConfig[P](DbName("default"))
  }

  override lazy val dynamicEvolutions: DynamicEvolutions = new DynamicEvolutions

  def onStart(): Unit = {
    // applicationEvolutions is a val and requires evaluation
    applicationEvolutions
  }

  onStart()

  // set up logger
  LoggerConfigurator(context.environment.classLoader).foreach {
    _.configure(context.environment, context.initialConfiguration, Map.empty)
  }

  protected lazy val routes: PartialFunction[RequestHeader, Handler] = userRoutes.orElse(articleRoutes)

  override lazy val router: Router = Router.from(routes)

  override lazy val defaultCacheApi: AsyncCacheApi = cacheApi(UUID.randomUUID().toString)

  private lazy val corsFilter: CORSFilter = {
    val corsConfig = CORSConfig.fromConfiguration(configuration)

    CORSFilter(corsConfig)
  }

  override def httpFilters: Seq[EssentialFilter] = List(corsFilter)
} 
Example 17
Source File: MyCompileTimeSpecs.scala    From slim-play   with MIT License 5 votes vote down vote up
import helpers.{
  OneAppPerSuiteWithComponents,
  OneAppPerTestWithComponents,
  OneServerPerSuiteWithComponents,
  OneServerPerTestWithComponents
}
import org.scalatest.TestSuite
import play.api.ApplicationLoader.Context
import play.api.libs.ws.ahc.AhcWSComponents

class AppWithTestComponents(context: Context) extends AppComponents(context) with AhcWSComponents

trait OneAppPerTestWithMyComponents extends OneAppPerTestWithComponents[AppWithTestComponents] {
  this: TestSuite =>

  override def createComponents(context: Context) = new AppWithTestComponents(context)
}

trait OneAppPerSuiteWithMyComponents extends OneAppPerSuiteWithComponents[AppWithTestComponents] {
  this: TestSuite =>

  override def createComponents(context: Context) = new AppWithTestComponents(context)
}

trait OneServerPerTestWithMyComponents
    extends OneServerPerTestWithComponents[AppWithTestComponents] { this: TestSuite =>

  override def createComponents(context: Context) = new AppWithTestComponents(context)
}

trait OneServerPerSuiteWithMyComponents
    extends OneServerPerSuiteWithComponents[AppWithTestComponents] { this: TestSuite =>

  override def createComponents(context: Context) = new AppWithTestComponents(context)
} 
Example 18
Source File: ScalaTestWithComponents.scala    From slim-play   with MIT License 5 votes vote down vote up
package helpers

import org.scalatest.TestSuite
import org.scalatestplus.play._
import play.api.{BuiltInComponents, _}
import play.api.ApplicationLoader.Context
import play.api._


trait OneAppPerTestWithComponents[T <: BuiltInComponents]
    extends BaseOneAppPerTest
    with FakeApplicationFactory
    with WithApplicationComponents[T] { this: TestSuite =>
}

trait OneAppPerSuiteWithComponents[T <: BuiltInComponents]
    extends BaseOneAppPerSuite
    with FakeApplicationFactory
    with WithApplicationComponents[T] { this: TestSuite =>
}

trait OneServerPerTestWithComponents[T <: BuiltInComponents]
    extends BaseOneServerPerTest
    with FakeApplicationFactory
    with WithApplicationComponents[T] { this: TestSuite =>

}

trait OneServerPerSuiteWithComponents[T <: BuiltInComponents]
    extends BaseOneServerPerSuite
    with FakeApplicationFactory
    with WithApplicationComponents[T] { this: TestSuite =>

}

trait WithApplicationComponents[T <: BuiltInComponents] {
  private var _components: T = _

  // accessed to get the components in tests
  final def components: T = _components

  // overridden by subclasses
  def createComponents(context: Context): T

  // creates a new application and sets the components
  def fakeApplication(): Application = {
    _components = createComponents(context)
    _components.application
  }

  def context: ApplicationLoader.Context = {
    val classLoader     = ApplicationLoader.getClass.getClassLoader
    val env             = new Environment(new java.io.File("."), classLoader, Mode.Test)
    val initialSettings = Map.empty[String, AnyRef]
    ApplicationLoader.Context.create(env, initialSettings)
  }
} 
Example 19
Source File: AppLoader.scala    From slim-play   with MIT License 5 votes vote down vote up
import play.api.ApplicationLoader.Context
import play.api._
import play.api.mvc.Results._
import play.api.routing.Router
import play.api.routing.sird._

import scala.concurrent.Future

class AppComponents(context: Context) extends BuiltInComponentsFromContext(context) {

  val httpFilters     = Nil
  override val Action = defaultActionBuilder

  val router: Router = Router.from {

    // Essentially copied verbatim from the SIRD example
    case GET(p"/hello/$to") =>
      Action {
        Ok(s"Hello $to")
      }

    
    case GET(p"/sqrt/${double(num)}") =>
      Action.async {
        Future {
          Ok(Math.sqrt(num).toString)
        }
      }

  }

}

class AppLoader extends ApplicationLoader {
  def load(context: Context) = new AppComponents(context).application
} 
Example 20
Source File: KafkaManagerLoaderForTests.scala    From CMAK   with Apache License 2.0 5 votes vote down vote up
package loader

import controllers.{ApiHealth, KafkaManagerContext}
import controllers.api.KafkaStateCheck
import features.ApplicationFeatures
import models.navigation.Menus
import play.api.ApplicationLoader.Context
import play.api.{Application, ApplicationLoader, LoggerConfigurator}

import scala.concurrent.ExecutionContext

class KafkaManagerLoaderForTests extends ApplicationLoader {
  var components: ApplicationComponents = null
  def applicationFeatures: ApplicationFeatures = components.applicationFeatures
  def menus: Menus = components.menus
  def executionContext: ExecutionContext = components.executionContext
  def kafkaManagerContext: KafkaManagerContext = components.kafkaManagerContext
  def kafkaStateCheck: KafkaStateCheck  = components.kafkaStateCheckC
  def apiHealth: ApiHealth= components.apiHealthC
  def load(context: Context): Application = {
    LoggerConfigurator(context.environment.classLoader).foreach {
      _.configure(context.environment, context.initialConfiguration, Map.empty)
    }
    components = new ApplicationComponents(context)
    components.application
  }
} 
Example 21
Source File: KafkaManagerLoader.scala    From CMAK   with Apache License 2.0 5 votes vote down vote up
package loader

import controllers.{AssetsComponents, BasicAuthenticationFilter, KafkaManagerContext}
import features.ApplicationFeatures
import models.navigation.Menus
import play.api.{Application, ApplicationLoader, BuiltInComponentsFromContext, LoggerConfigurator}
import play.api.ApplicationLoader.Context
import play.api.i18n.I18nComponents
import play.api.mvc.Filter
import play.api.routing.Router
import router.Routes

import scala.concurrent.ExecutionContext



class KafkaManagerLoader extends ApplicationLoader {
  def load(context: Context): Application = {
    LoggerConfigurator(context.environment.classLoader).foreach {
      _.configure(context.environment, context.initialConfiguration, Map.empty)
    }
    new ApplicationComponents(context).application
  }
}

class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with I18nComponents with AssetsComponents {
  implicit val applicationFeatures: ApplicationFeatures = ApplicationFeatures.getApplicationFeatures(context.initialConfiguration.underlying)
  implicit val menus: Menus = new Menus
  implicit val ec: ExecutionContext = controllerComponents.executionContext
  val kafkaManagerContext = new KafkaManagerContext(applicationLifecycle, context.initialConfiguration)
  private[this] val applicationC = new controllers.Application(controllerComponents, kafkaManagerContext)
  private[this] lazy val clusterC = new controllers.Cluster(controllerComponents, kafkaManagerContext)
  private[this] lazy val topicC = new controllers.Topic(controllerComponents, kafkaManagerContext)
  private[this] lazy val logKafkaC = new controllers.Logkafka(controllerComponents, kafkaManagerContext)
  private[this] lazy val consumerC = new controllers.Consumer(controllerComponents, kafkaManagerContext)
  private[this] lazy val preferredReplicaElectionC= new controllers.PreferredReplicaElection(controllerComponents, kafkaManagerContext)
  private[this] lazy val reassignPartitionsC = new controllers.ReassignPartitions(controllerComponents, kafkaManagerContext)
  lazy val kafkaStateCheckC = new controllers.api.KafkaStateCheck(controllerComponents, kafkaManagerContext)
  lazy val apiHealthC = new controllers.ApiHealth(controllerComponents)

  override lazy val httpFilters: Seq[Filter] = Seq(BasicAuthenticationFilter(context.initialConfiguration))


  override val router: Router = new Routes(
    httpErrorHandler, 
    applicationC, 
    clusterC, 
    topicC, 
    logKafkaC, 
    consumerC, 
    preferredReplicaElectionC,
    reassignPartitionsC, 
    kafkaStateCheckC, 
    assets,
    apiHealthC
  ).withPrefix(context.initialConfiguration.getOptional[String]("play.http.context").orNull)
}