• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala GlobalSettings类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.GlobalSettings的典型用法代码示例。如果您正苦于以下问题:Scala GlobalSettings类的具体用法?Scala GlobalSettings怎么用?Scala GlobalSettings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了GlobalSettings类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: injectorModules

//设置package包名称以及导入依赖的类
package global

import actors.ChadashSystem
import com.google.inject.{Guice, Module}
import play.api.mvc.{EssentialAction, Filters}
import play.api.{Application, GlobalSettings, Logger, Mode}
import play.filters.gzip.GzipFilter
import play.filters.headers.SecurityHeadersFilter

trait AppGlobalSettings extends GlobalSettings {

  private var INJECTOR: Option[com.google.inject.Injector] = None

  def injectorModules(): Seq[Module]

  override def onStart(app: Application) {
    INJECTOR = Some(Guice.createInjector(injectorModules(): _*))
  }

  override def onStop(app: Application) {
    Logger.info("Application shutdown...")
    if(app.mode != Mode.Test)
      ChadashSystem.system.shutdown()
  }

  override def doFilter(next: EssentialAction): EssentialAction = {
    Filters(super.doFilter(next), new GzipFilter(), SecurityHeadersFilter())
  }

  override def getControllerInstance[A](controllerClass: Class[A]): A = {
    INJECTOR match {
      case Some(x) => x.getInstance(controllerClass)
      case None => throw new UnsupportedOperationException("The DI framework has not been setup yet!")
    }
  }
} 
开发者ID:lifeway,项目名称:Chadash,代码行数:37,代码来源:AppGlobalSettings.scala


示例2: Global

//设置package包名称以及导入依赖的类
import org.squeryl.adapters.{H2Adapter, MySQLAdapter, PostgreSqlAdapter}
import org.squeryl.internals.DatabaseAdapter
import org.squeryl.{Session, SessionFactory}
import play.api.db.DB
import play.api.{Application, GlobalSettings}

object Global extends GlobalSettings {

  override def onStart(app: Application) {
    SessionFactory.concreteFactory = app.configuration.getString("db.default.driver") match {
      case Some("org.h2.Driver") => Some(() => getSession(new H2Adapter, app))
      case Some("org.postgresql.Driver") => Some(() => getSession(new PostgreSqlAdapter, app))
      case Some("com.mysql.jdbc.Driver") => Some(() => getSession(new MySQLAdapter, app))
      case _ => sys.error("Database driver must be either org.h2.Driver or org.postgresql.Driver")
    }
  }

  def getSession(adapter:DatabaseAdapter, app: Application) = Session.create(DB.getConnection()(app), adapter)

} 
开发者ID:chang850,项目名称:squeryl,代码行数:21,代码来源:Global.scala


示例3: PlayGlobalSettings

//设置package包名称以及导入依赖的类
package utils

import java.util.TimeZone

import jdub.async.Database
import org.joda.time.DateTimeZone
import play.api.{ Application, GlobalSettings }
import services.database.Schema

object PlayGlobalSettings extends GlobalSettings {
  override def onStart(app: Application) = {
    DateTimeZone.setDefault(DateTimeZone.UTC)
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"))

    val cnf = play.api.Play.current.configuration
    val host = cnf.getString("db.host").getOrElse("localhost")
    val port = 5432
    val database = cnf.getString("db.database")
    val username = cnf.getString("db.username").getOrElse("silhouette")
    val password = cnf.getString("db.password")

    Database.open(username, host, port, password, database)
    Schema.update()

    super.onStart(app)
  }

  override def onStop(app: Application) = {
    Database.close()
    super.onStop(app)
  }
} 
开发者ID:laurinka,项目名称:golfmit,代码行数:33,代码来源:PlayGlobalSettings.scala


示例4: CmdTask

//设置package包名称以及导入依赖的类
package com.galacticfog.lambda.scheduler

import java.util.UUID

import org.apache.mesos.{Protos, MesosSchedulerDriver}
import org.apache.mesos.Protos.FrameworkInfo
import play.api.{Logger, Play, Application, GlobalSettings}
import scala.collection.mutable
import scala.concurrent.Future
import scala.sys.SystemProperties
import scala.concurrent.duration._
import Play.current
import play.api.libs.concurrent.Execution.Implicits._
import scala.util.Try

case class CmdTask(uuid: UUID, handlerMethod: String, jarUrl: String)

object Global extends GlobalSettings {

  lazy val driver: Try[MesosSchedulerDriver] = Try {
    Logger.info("creating LambdaScheduler")
    val scheduler = new LambdaScheduler

    val master = current.configuration.getString("master") getOrElse "localhost:5050"
    Logger.info(s"registering with mesos-master: ${master}")

    val schedulerHostname = current.configuration.getString("hostname") getOrElse java.net.InetAddress.getLocalHost.getHostName
    Logger.info(s"scheduler on: ${schedulerHostname}")

    val frameworkInfoBuilder = FrameworkInfo.newBuilder()
      .setName("gestalt-lambda-scheduler")
      .setFailoverTimeout(60.seconds.toMillis)
      .setUser("")
      .setCheckpoint(true)
      .setHostname(schedulerHostname)

    val frameworkInfo = frameworkInfoBuilder.build()
    Logger.info(s"scheduler on: ${schedulerHostname}")
    val implicitAcknowledgements = false

    new MesosSchedulerDriver( scheduler, frameworkInfo, master, implicitAcknowledgements )
  }

  val taskQueue = new mutable.Queue[CmdTask]

  override def onStart(app: Application): Unit = {
    Logger.info("onStart")
    driver foreach { d =>
      Logger.info("starting driver")
      Future { d.run } map println
    }
  }

  override def onStop(app: Application): Unit = {
    Logger.info("onStop")
    driver foreach {
      Logger.info("stopping driver")
      _.stop()
    }
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:62,代码来源:Global.scala


示例5: setUp

//设置package包名称以及导入依赖的类
package global

import org.joda.time.DateTime
import play.api.{Application, GlobalSettings, Logger}
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.concurrent.{Future, Await}
import scala.concurrent.duration._

trait TestLogger {
  protected final val logger = Logger("test.global.TestLogger")
}

trait SetUpFixture extends TestLogger {
  def setUp()(implicit app: Application)
  def tearDown()(implicit app: Application)
  def await[A](f: Future[A]): A = TestGlobal.await(f)
  def applyFunction[A](l: List[A], f: A => Future[Option[A]]): List[A] = {
    val as: List[A] = List()
    l.foldLeft(as)((x, u) => (await(f(u)) ++ x).toList)
  }
}

class EmptyFixture extends SetUpFixture {
  override def setUp()(implicit app: Application) = {}
  override def tearDown()(implicit app: Application) = {}
}

class TestGlobal()(implicit fixture: SetUpFixture) extends GlobalSettings with TestLogger {

  // put here common setup / tear down for all your test
}

object TestGlobal {
  def await[A](f: Future[A]): A = Await.result(f, 10 seconds)
  def await[A](f: Seq[Future[A]]): Seq[A] = await(Future.sequence(f))
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:38,代码来源:TestGlobal.scala


示例6: ApiSpecServer

//设置package包名称以及导入依赖的类
package global

import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatestplus.play._
import play.api.GlobalSettings
import play.api.mvc.Results
import play.api.test._

abstract class ApiSpecServer extends PlaySpec with OneServerPerTest with Results with ScalaFutures with IntegrationPatience {

  val currentVersion = 1

  protected def getFakeApp(global: GlobalSettings): FakeApplication = {
    FakeApplication(
      additionalConfiguration = Map(
        "slick.dbs.default.driver" -> "slick.driver.H2Driver$",
        "slick.dbs.default.db.driver" -> "org.h2.Driver",
        "slick.dbs.default.db.url" -> "jdbc:h2:mem:play;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE",
        "slick.dbs.default.db.user" -> "sa",
        "slick.dbs.default.db.password" -> "",
        "slick.dbs.default.db.connectionPool" -> "disabled",
        "slick.dbs.default.db.keepAliveConnection" -> "true",

        "play.evolutions.enabled" -> "false",
        "play.evolutions.autoApply" -> "false",
        "play.evolutions.autocommit" -> "false"
      ),
      withGlobal = Some(global)
    )
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:32,代码来源:ApiSpecServer.scala


示例7: Global

//设置package包名称以及导入依赖的类
import dao.Items
import models.Item
import play.api.GlobalSettings
import play.api._

object Global extends GlobalSettings {

  override def onStart(app: Application): Unit = {
    if(Items.findAll.isEmpty) {
      Seq(
        Item(
          None,
          name = "Death Axe",
          damage = Some(11),
          armor = None
        ),
        Item(
          None,
          name = "Shinny Shield",
          damage = Some(2),
          armor = Some(10)
        ),
        Item(
          None,
          name = "Justice Chest",
          damage = None,
          armor = Some(7)
        ),
        Item(
          None,
          name = "Warrior\'s Helmet",
          damage = None,
          armor = Some(5)
        ),
        Item(
          None,
          name = "Plate Pants",
          damage = Some(11),
          armor = None
        )
      ).foreach(Items.save)
    }
  }
} 
开发者ID:njir,项目名称:scala-play,代码行数:45,代码来源:Global.scala


示例8: FacebookConnectionSpec

//设置package包名称以及导入依赖的类
package facebook4s

import facebook4s.api.AccessToken
import facebook4s.connection.{WSClient, FacebookConnectionInformation}
import facebook4s.request.FacebookBatchRequestBuilder
import facebook4s.response.FacebookBatchResponsePart
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play._

import play.api.GlobalSettings
import play.api.libs.json.Json
import play.api.test._
import play.api.mvc._
import play.api.mvc.BodyParsers._
import play.api.mvc.Results._

import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.Future

class FacebookConnectionSpec extends PlaySpec with OneServerPerSuite with BeforeAndAfterAll {

  import FacebookTestHelpers._

  val jsonAction = Action.async(parse.json) { request ? Future { Ok(request.body) } }
  val echoBodyAction = Action.async(parse.text) { request ? Future { Ok(request.body) } }
  val multipartAction = Action.async(parse.multipartFormData) { request ? Future { Ok(request.body.dataParts.toSeq.sortBy(_._1).map(d ? d._1 + d._2.mkString).mkString) } }

  implicit override lazy val app: FakeApplication =
    FakeApplication(
      withGlobal = Some(new GlobalSettings() {
        override def onRouteRequest(request: RequestHeader): Option[Handler] = {
          request.uri match {
            case uri if uri.startsWith("/json") ? Some(jsonAction)
            case uri if uri.endsWith("/v2.5/")  ? Some(multipartAction)
            case uri if uri.startsWith("/v")    ? Some(echoBodyAction)
            case uri                            ? super.onRouteRequest(request)
          }
        }
      }))

  "Parse batch responses" in {

    val jsonResponse = makeJsonResponse(NUM_SUCCESSES, NUM_ERRORS)
    val parts = Json.parse(jsonResponse).validate[Seq[FacebookBatchResponsePart]].getOrElse(Seq.empty)

    val returnCodes = (1 to NUM_SUCCESSES).map { _ ? HTTP_SUCCESS_CODE } ++ (1 to NUM_ERRORS).map { _ ? HTTP_ERROR_CODE }
    assert(parts.size == NUM_SUCCESSES + NUM_ERRORS)
    assert(parts.map(_.status) == returnCodes)

    parts.take(NUM_SUCCESSES).map(_.json) foreach { json ?
      (json \ "name").validate[String].get == NAME
    }
    parts.takeRight(NUM_ERRORS).map(_.json) foreach { json ?
      (json \ "error" \ "code").validate[Int].get == JSON_ERROR_CODE
    }

  }
} 
开发者ID:SocialOrra,项目名称:social4s,代码行数:59,代码来源:FacebookConnectionSpec.scala


示例9: Global

//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.wasp.web


import _root_.controllers.Assets
import akka.actor.Props
import it.agilelab.bigdata.wasp.core.WaspSystem
import it.agilelab.bigdata.wasp.core.WaspSystem.{actorSystem, masterActor}
import it.agilelab.bigdata.wasp.core.bl.ConfigBL
import it.agilelab.bigdata.wasp.core.logging.LoggerInjector
import it.agilelab.bigdata.wasp.core.utils.{WaspDB, ActorSystemInjector}
import it.agilelab.bigdata.wasp.master.MasterGuardian
import it.agilelab.bigdata.wasp.producers.InternalLogProducerGuardian
import org.apache.log4j.Level
import play.api.mvc.{RequestHeader, Handler}
import play.api.{Application, GlobalSettings, Logger}
import play.api.routing._
import play.api.routing.sird._
import play.api.mvc._


object Global extends GlobalBase{

  override def onRequestOverride(req: RequestHeader): Option[Handler] = {
    Logger.info("Global onRequestOverride")
    None
  }

}

trait GlobalBase extends GlobalSettings with ActorSystemInjector with LoggerInjector {

  org.apache.log4j.Logger.getLogger("org").setLevel(Level.WARN)
  org.apache.log4j.Logger.getLogger("akka").setLevel(Level.WARN)
  
  override def loggerActorProps : Props = Props(new InternalLogProducerGuardian(ConfigBL))

  override def onStart(app : Application) {

    Logger.info("starting app: " + app.configuration.getString("application.version").getOrElse("no version"))
    
    val startMaster = app.configuration.getString("master.start").getOrElse("true")
    val actorSystem = WaspSystem.actorSystem
    WaspDB.DBInitialization(actorSystem)
    WaspSystem.systemInitialization(actorSystem)
    if(startMaster == "true") {
      masterActor = WaspSystem.actorSystem.actorOf(Props(new MasterGuardian(ConfigBL)))
    }
  }

  def onRequestOverride(req: RequestHeader): Option[Handler]

  override def onRouteRequest(req: RequestHeader): Option[Handler] = {
    Logger.info(s"onRouteRequest: ${req.toString()}")
    onRequestOverride(req) orElse super.onRouteRequest(req)
  }

} 
开发者ID:agile-lab-dev,项目名称:wasp,代码行数:58,代码来源:Global.scala


示例10: Global

//设置package包名称以及导入依赖的类
package global

import akka.actor.ActorSystem
import play.api.libs.json.Json
import play.api.mvc.{Result, RequestHeader}
import play.api.mvc.Results._
import play.api.{Application, GlobalSettings}

import scala.concurrent.Future

object Global extends GlobalSettings {

  var system: ActorSystem = _

  override def onStart(app: Application): Unit = {
    system = ActorSystem("es-actor-system")
  }

  override def onStop(app: Application): Unit = {
    system.shutdown()
  }

  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    Future.successful(BadRequest(Json.obj("error" -> error)))
  }

  override def onError(request: RequestHeader, ex: Throwable): Future[Result] = {
    Future.successful(InternalServerError(Json.obj("error" -> ex.getMessage)))
  }
} 
开发者ID:asrulsibaoel,项目名称:scala-cqrs-es,代码行数:31,代码来源:Global.scala


示例11: Global

//设置package包名称以及导入依赖的类
import conf.util.CORSFilter
import play.api.libs.json.Json
import play.api.mvc.{Result, RequestHeader, WithFilters}
import play.api.{GlobalSettings, Application}
import play.api.mvc.Results.NotFound

import scala.concurrent.Future


object Global extends WithFilters(CORSFilter()) with GlobalSettings {
  override def onStart(app: Application): Unit = {
    super.onStart(app)
  }

  override def onHandlerNotFound(request: RequestHeader):Future[Result] = {
    Future.successful(NotFound(Json.obj("error" -> "Wrong Path")))
  }

  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String):Future[Result] = {
    Future.successful(NotFound(Json.obj("error" -> "Bad Request")))
  }

  // 500 - internal server error
  override def onError(request: RequestHeader, throwable: Throwable) :Future[Result] = {

    Future.successful(NotFound(Json.obj("error" -> "500 Internal Error")))
  }


} 
开发者ID:roclet,项目名称:hashworkapi,代码行数:32,代码来源:Global.scala


示例12: Global

//设置package包名称以及导入依赖的类
import models.WorkbenchConfig
import play.api.{Application, GlobalSettings}
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import java.util.logging.{ConsoleHandler, SimpleFormatter, FileHandler}
import de.fuberlin.wiwiss.silk.workspace.FileUser
import de.fuberlin.wiwiss.silk.workspace.User
import de.fuberlin.wiwiss.silk.plugins.Plugins
import de.fuberlin.wiwiss.silk.plugins.jena.JenaPlugins
import play.api.Play
import play.api.Play.current
import scala.concurrent.Future

object Global extends GlobalSettings {

  override def beforeStart(app: Application) {
    
    // ensure user.home is set to $ELDS_HOME, if present
    val elds_home = System.getenv("ELDS_HOME")
    if (elds_home != null) {
      System.setProperty("user.home", elds_home)
    }
  
    // Configure logging
    val logFile = if(app.getFile("/logs/").exists) app.getFile("/logs/engine.log") else app.getFile("../logs/engine.log")
    val fileHandler = new FileHandler(logFile.getAbsolutePath)
    fileHandler.setFormatter(new SimpleFormatter())
    java.util.logging.Logger.getLogger("").addHandler(fileHandler)

    val consoleHandler = new ConsoleHandler()
    java.util.logging.Logger.getLogger("").addHandler(consoleHandler)

    //Initialize user manager
    val user = new FileUser
    User.userManager = () => user

    //Load plugins
    Plugins.register()
    JenaPlugins.register()
  }
  
  override def onError(request: RequestHeader, ex: Throwable) = {
    Future.successful(InternalServerError(ex.getMessage))
  }
}


  lazy val baseUrl = Play.configuration.getString("application.context").getOrElse("").stripSuffix("/")

  def workbench = WorkbenchConfig.get
} 
开发者ID:petrovskip,项目名称:silk.2.6-GenLinkSA,代码行数:52,代码来源:Global.scala


示例13: Global

//设置package包名称以及导入依赖的类
package lila.app

import lila.common.HTTPRequest
import play.api.mvc._
import play.api.mvc.Results._
import play.api.{ Application, GlobalSettings }

object Global extends GlobalSettings {

  override def onStart(app: Application) {
    kamon.Kamon.start()
    lila.app.Env.current
  }

  override def onStop(app: Application) {
    kamon.Kamon.shutdown()
  }

  override def onRouteRequest(req: RequestHeader): Option[Handler] = {
    lila.mon.http.request.all()
    if (req.remoteAddress contains ":") lila.mon.http.request.ipv6()
    super.onRouteRequest(req)
  }

  private def niceError(req: RequestHeader): Boolean =
    req.method == "GET" &&
      HTTPRequest.isSynchronousHttp(req) &&
      !HTTPRequest.hasFileExtension(req)

  override def onHandlerNotFound(req: RequestHeader) =
    if (niceError(req)) controllers.Main.notFound(req)
    else fuccess(NotFound("404 - Resource not found"))

  override def onBadRequest(req: RequestHeader, error: String) =
    if (error startsWith "Illegal character in path") fuccess(Redirect("/"))
    else if (error startsWith "Cannot parse parameter") onHandlerNotFound(req)
    else if (niceError(req)) {
      lila.mon.http.response.code400()
      controllers.Lobby.handleStatus(req, Results.BadRequest)
    } else fuccess(BadRequest(error))

  override def onError(req: RequestHeader, ex: Throwable) =
    if (niceError(req)) {
      if (lila.common.PlayApp.isProd) {
        lila.mon.http.response.code500()
        fuccess(InternalServerError(views.html.base.errorPage(ex) {
          lila.api.Context(req, lila.app.Env.api.assetVersion.get)
        }))
      } else super.onError(req, ex)
    } else fuccess(InternalServerError(ex.getMessage))
} 
开发者ID:DrNixx,项目名称:line,代码行数:52,代码来源:Global.scala


示例14: Global

//设置package包名称以及导入依赖的类
import models.A
import play.api.{GlobalSettings, Application}
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.indexes.{IndexType, Index}
//import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.ExecutionContext.Implicits.global

object Global extends GlobalSettings {

  def ensureIndex(collection: JSONCollection, index: Index, retry: Int = 10): Unit = collection.indexesManager.ensure(index) recover {
    case t: Throwable =>
      if (retry > 0)
        ensureIndex(collection, index, retry - 1)
      else throw t
  }

  override def onStart(app: Application) {
    ensureIndex(A.collection, Index(Seq("a1" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a2" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a3" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a4" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a5" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a6" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a7" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a8" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a9" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a0" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a10" -> IndexType.Ascending)))
    ensureIndex(A.collection, Index(Seq("a11" -> IndexType.Ascending)))
    println("\n\nStarting on start")
  }
} 
开发者ID:arussel,项目名称:reactivemongo-lock,代码行数:33,代码来源:Global.scala


示例15: Global

//设置package包名称以及导入依赖的类
package global

import play.api.GlobalSettings
import play.api.Application
import play.api.Logger
import models.DAO

object Global extends GlobalSettings {
  
  override def onStart(app: Application): Unit = {
    super.onStart(app)
    Logger.info("Face Recognition Service Started")
    //DAO.init
  }
  
  override def onStop(app: Application): Unit = {
    super.onStop(app)
    Logger.info("Face Recognition Service Stopped")
  }
} 
开发者ID:pamu,项目名称:facereg,代码行数:21,代码来源:Global.scala


示例16: Global

//设置package包名称以及导入依赖的类
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.{GlobalSettings, Application, Logger}
import play.api.mvc._
import play.api.Play.current


object Global extends GlobalSettings {
  override def onStart(app: Application) = {
    AccountManager ! "Start"
    StripeChargeActor ! "Start"
    BillEmailScheduler ! "Start"
  }

  override def onStop(app: Application) = {
    AccountManager ! "Stop"
    StripeChargeActor ! "Stop"
    BillEmailScheduler ! "Stop"
  }

  override def onError(request: RequestHeader, ex: Throwable) = {
    AccessLogger.warn(s"Global onError: ${ex.getMessage}")

    Future.successful(InternalServerError(
      Json.obj("errors" -> Json.arr(Json.toJson(ex.getCause))))
    )
  }
} 
开发者ID:pro-zw,项目名称:m8chat,代码行数:29,代码来源:Global.scala


示例17: EffectiveDateResourceTimemachineOffSpec

//设置package包名称以及导入依赖的类
package cjp.catalogue.resource

import java.util.concurrent.TimeUnit

import akka.util.Timeout
import org.joda.time.DateTime
import org.mockito.Mockito._
import cjp.catalogue.repository.EffectiveDateRepository
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, BeforeAndAfter, WordSpec}
import play.api.GlobalSettings
import play.api.http.{Status, HeaderNames}
import play.api.libs.json.Json
import play.api.mvc.{AnyContentAsJson, AnyContentAsText}
import play.api.test._

class EffectiveDateResourceTimemachineOffSpec extends WordSpec with BeforeAndAfter with PlayRunners with ResultExtractors with HeaderNames with Status with Matchers with MockitoSugar {
  implicit val timeout = Timeout(10L, TimeUnit.SECONDS)

  private val effectiveDateRepository = mock[EffectiveDateRepository]
  private val controller = new EffectiveDateResource(effectiveDateRepository, enableTimemachine = false)

  object TestGlobal extends GlobalSettings {
    override def getControllerInstance[A](controllerClass: Class[A]): A =
      controller.asInstanceOf[A]
  }

  before {
    reset(effectiveDateRepository)
  }

  "calling PUT /manage/effectiveDate" should {
    "return 403 if timemachine feature switch is disabled" in {
      running(TestServer(18888, FakeApplication(withGlobal = Some(TestGlobal)))) {
        val json = Json.parse("""{"effectiveDate":"2015-04-10T14:12:57.159Z"}""")
        val request: FakeRequest[AnyContentAsJson] = FakeRequest().withJsonBody(json).withHeaders("ContentType" -> "application/json")

        val result = controller.setEffectiveDate.apply(request)

        status(result) should be(403)
        verifyZeroInteractions(effectiveDateRepository)
      }
    }
  }

  "calling DELETE /manage/effectiveDate" should {
    "return 403 if timemachine feature switch is disabled" in {
      running(TestServer(18888, FakeApplication(withGlobal = Some(TestGlobal)))) {
        val result = controller.resetEffectiveDate.apply(FakeRequest())

        status(result) should be(403)
        verifyZeroInteractions(effectiveDateRepository)
      }
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:57,代码来源:EffectiveDateResourceTimemachineOffSpec.scala


示例18: Global

//设置package包名称以及导入依赖的类
import javax.inject.Inject

import play.api.Play.current
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.iteratee.Enumerator
import play.api.libs.json.Json
import play.api.{ Logger, Application, GlobalSettings }

import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json.collection.JSONCollection

class Global @Inject() (
  val reactiveMongoApi: ReactiveMongoApi) extends GlobalSettings {

  def collection = reactiveMongoApi.db.collection[JSONCollection]("spots")

  val spots = List(
    Json.obj(
      "text" -> "Bar 8",
      "username" -> "fmos",
      "favorite" -> false
    )
  )

  override def onStart(app: Application) {
    Logger.info("Application has started")

    collection.bulkInsert(spots.toStream, ordered = true).
      foreach(i => Logger.info("Database was initialized"))
  }

  override def onStop(app: Application) {
    Logger.info("Application shutdown...")

    collection.drop().onComplete {
      case _ => Logger.info("Database collection dropped")
    }
  }
} 
开发者ID:ElComite,项目名称:placesmapper_back,代码行数:40,代码来源:Global.scala


示例19: MazeGlobal

//设置package包名称以及导入依赖的类
package global

import actors.MazeActor
import akka.actor.Props
import play.api.libs.concurrent.Akka
import play.api.{Application, GlobalSettings, Logger}
import play.api.Play.current


object MazeGlobal extends GlobalSettings {

  lazy val actor = Akka.system.actorOf(Props[MazeActor], "MazeActor")

  override def onStart(app: Application): Unit = {
    super.onStart(app)
    Logger.info("App started")
  }

  override def onStop(app: Application): Unit = {
    super.onStop(app)
    Logger.info("App Stopped")
    Akka.system.shutdown()
  }

} 
开发者ID:pamu,项目名称:zippr-challenge,代码行数:26,代码来源:MazeGlobal.scala


示例20: Global

//设置package包名称以及导入依赖的类
import com.mcw.KafkaStreamConsumer
import play.api.libs.json.Json
import play.api.{Logger, GlobalSettings}
import play.api.mvc.Results._
import play.api.mvc.{Result, RequestHeader}
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.concurrent.Future
import models._


object Global extends GlobalSettings {

  override def onError(rh: RequestHeader, ex: Throwable) = {
    val mm = "ERROR " + ex.getMessage
    Logger.error(mm, ex)
    Future(InternalServerError(Json.prettyPrint(Json.toJson(Msg(mm)))))
  }

  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    val errObj = Msg(error)
    Future(BadRequest(Json.prettyPrint(Json.toJson(errObj))))
  }

  override def onHandlerNotFound(rh: RequestHeader) = {
    Future.successful(NotFound(Json.prettyPrint(Json.toJson(Msg("404 Not Found")))))
  }

  override def onStart(app: play.api.Application): Unit = {
  }

  override def onStop(app: play.api.Application) {
  }

} 
开发者ID:p44,项目名称:Kafka-Speed-Bag,代码行数:36,代码来源:Global.scala



注:本文中的play.api.GlobalSettings类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala mapping类代码示例发布时间:2022-05-23
下一篇:
Scala Index类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap