本文整理汇总了Scala中play.api.Play类的典型用法代码示例。如果您正苦于以下问题:Scala Play类的具体用法?Scala Play怎么用?Scala Play使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Play类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CountriesDestroySpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import utils.TimeUtil.now
class CountriesDestroySpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Countries"))
DatabaseInserter.insert("Users", 12, List("[email protected]", "John", "Doe", "password", "token", now.toString, "User", "1", "999999", "2016-01-01"))
DatabaseInserter.insert("Users", 13, List("[email protected]", "Johnny", "Doe", "password", "admin_token", now.toString, "Admin", "1", "999999", "2016-01-01"))
DatabaseInserter.insert("Countries", 11, List("Denmark", "DEN", "1", "2016-10-10"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Countries"))
}
"deleting countries" should {
"returns 404 if no such record" in {
val request = FakeRequest(DELETE, "/countries/200").withHeaders("Authorization" -> "admin_token")
val destroy = route(app, request).get
status(destroy) mustBe NOT_FOUND
}
"returns 204 if successfully deleted and user is Admin" in {
val request = FakeRequest(DELETE, "/countries/11").withHeaders("Authorization" -> "admin_token")
val destroy = route(app, request).get
status(destroy) mustBe NO_CONTENT
}
"returns 403 if user is not Admin" in {
val request = FakeRequest(DELETE, "/countries/11").withHeaders("Authorization" -> "token")
val destroy = route(app, request).get
status(destroy) mustBe FORBIDDEN
}
}
}
示例2: 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()
}
}
}
示例3: Restaurants
//设置package包名称以及导入依赖的类
package dao;
import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile
import play.api.Play
import slick.driver.PostgresDriver.api._
import scala.concurrent.Future
import model.CompleteRestaurant
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile
import play.api.Play
import slick.driver.PostgresDriver.api._
import scala.concurrent.Future
import model.CompleteRestaurant
import scala.concurrent.ExecutionContext.Implicits.global
import model.RestaurantTableDef
object Restaurants {
val dbConfig=DatabaseConfigProvider.get[JdbcProfile](Play.current)
val restaurants=TableQuery[RestaurantTableDef]
def list:Future[Seq[CompleteRestaurant]]={
dbConfig.db.run(restaurants.result)
}
def getById(id:Long): Future[Option[CompleteRestaurant]]={
dbConfig.db.run(restaurants.filter(_.id===id).result.headOption)
}
def save(restaurant:CompleteRestaurant):Future[String]={
dbConfig.db.run(restaurants+=restaurant).map(res => "Restaurant saved").recover{
case ex: Exception => ex.getCause.getMessage
}
}
def update(restaurant:CompleteRestaurant):Future[Int]={
dbConfig.db.run(restaurants.filter(_.id===restaurant.id).update(restaurant))
}
def delete(id:Long):Future[Int]={
dbConfig.db.run(restaurants.filter(_.id===id).delete)
}
}
示例4: FrontendGlobal
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.trustregistration
import java.io.File
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import play.api.Mode._
import play.api.mvc.Request
import play.api.{Application, Configuration, Play}
import play.twirl.api.Html
import uk.gov.hmrc.crypto.ApplicationCrypto
import uk.gov.hmrc.play.audit.filters.FrontendAuditFilter
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.frontend.bootstrap.DefaultFrontendGlobal
import uk.gov.hmrc.play.http.logging.filters.FrontendLoggingFilter
object FrontendGlobal
extends DefaultFrontendGlobal {
override val auditConnector = FrontendAuditConnector
override val loggingFilter = LoggingFilter
override val frontendAuditFilter = AuditFilter
override def onStart(app: Application) {
super.onStart(app)
ApplicationCrypto.verifyConfiguration()
}
override def onLoadConfig(config: Configuration, path: File, classloader: ClassLoader, mode: Mode): Configuration = {
super.onLoadConfig(config, path, classloader, mode)
}
override def standardErrorTemplate(pageTitle: String, heading: String, message: String)(implicit rh: Request[_]): Html =
uk.gov.hmrc.trustregistration.views.html.error_template(pageTitle, heading, message)
override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")
}
object ControllerConfiguration extends ControllerConfig {
lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}
object LoggingFilter extends FrontendLoggingFilter {
override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}
object AuditFilter extends FrontendAuditFilter with RunMode with AppName {
override lazy val maskedFormFields = Seq("password")
override lazy val applicationPort = None
override lazy val auditConnector = FrontendAuditConnector
override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
}
示例5: SessionCreateSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import com.github.t3hnar.bcrypt._
class SessionCreateSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Users"))
val password = "password".bcrypt
DatabaseInserter.insert("Users", 12, List("[email protected]", "John", "Doe", password, "token", "2016-01-01", "User", "1", "999999", "2016-01-01"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Users"))
}
"creates session if data is ok" in {
val request = FakeRequest(POST, "/session").withJsonBody(Json.parse("""{ "email":"[email protected]", "password":"password" }"""))
val create = route(app, request).get
status(create) mustBe CREATED
contentType(create) mustBe Some("application/json")
contentAsString(create) must include("user")
contentAsString(create) must include("authToken")
}
"responses with error if data is not ok" in {
val request = FakeRequest(POST, "/session").withJsonBody(Json.parse("""{ "email":"[email protected]", "password":"bad_password" }"""))
val create = route(app, request).get
status(create) mustBe BAD_REQUEST
contentType(create) mustBe Some("application/json")
contentAsString(create) must include("error")
}
}
示例6: CountriesShowSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import utils.TimeUtil.now
class CountriesShowSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Countries"))
DatabaseInserter.insert("Users", 12, List("[email protected]mail.com", "John", "Doe", "password", "token", now.toString, "User", "1", "999999", "2016-01-01"))
DatabaseInserter.insert("Countries", 88, List("Austria", "AU", "0", "2015-01-01"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Countries"))
}
"renders error" in {
val request = FakeRequest(GET, "/countries/20").withHeaders("Authorization" -> "token")
val show = route(app, request).get
status(show) mustBe NOT_FOUND
contentType(show) mustBe Some("application/json")
contentAsString(show) must include("error")
contentAsString(show) must include("not found")
}
"renders country" in {
val request = FakeRequest(GET, "/countries/88").withHeaders("Authorization" -> "token")
val show = route(app, request).get
status(show) mustBe OK
contentType(show) mustBe Some("application/json")
contentAsString(show) must include("country")
}
}
示例7: CountriesIndexSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import utils.TimeUtil.now
class CountriesIndexSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Countries"))
DatabaseInserter.insert("Users", 12, List("[email protected]", "John", "Doe", "password", "token", now.toString, "User", "1", "999999", "2016-01-01"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Countries"))
}
"renders the forbidden for unauthorized response" in {
val request = FakeRequest(GET, "/countries")
val index = route(app, request).get
status(index) mustBe FORBIDDEN
contentType(index) mustBe Some("application/json")
contentAsString(index) must include("errors")
}
"renders countries list for authorized user response" in {
val request = FakeRequest(GET, "/countries").withHeaders("Authorization" -> "token")
val index = route(app, request).get
status(index) mustBe OK
contentType(index) mustBe Some("application/json")
contentAsString(index) must include("countries")
}
}
示例8: CountriesCreateSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import utils.TimeUtil.now
class CountriesCreateSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseInserter.insert("Users", 12, List("[email protected]", "John", "Doe", "password", "token", now.toString, "Moderator", "1", "999999", "2016-01-01"))
DatabaseCleaner.clean(List("Countries"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Countries"))
}
"saves the record on create" in {
val request = FakeRequest(POST, "/countries").withJsonBody(Json.parse("""{ "country": {"title":"Germany", "abbreviation":"GER"} }""")).withHeaders("Authorization" -> "token")
val create = route(app, request).get
status(create) mustBe CREATED
contentType(create) mustBe Some("application/json")
contentAsString(create) must include("country")
}
}
示例9: UsersIndexSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import utils.TimeUtil.now
class UsersIndexSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Users"))
DatabaseInserter.insert("Users", 12, List("[email protected]", "John", "Doe", "password", "token", now.toString, "User", "1", "999999", "2016-01-01"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Users"))
}
"renders the index response" in {
val index = route(app, FakeRequest(GET, "/users").withHeaders("Authorization" -> "token")).get
status(index) mustBe OK
contentType(index) mustBe Some("application/json")
contentAsString(index) must include("users")
contentAsString(index) mustNot include("authToken")
}
}
示例10: UsersShowSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.{DatabaseCleaner, DatabaseInserter}
import play.api.Play
import utils.TimeUtil.now
class UsersShowSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Users"))
DatabaseInserter.insert("Users", 10, List("[email protected]", "John", "Doe", "password", "token", now.toString, "User", "1", "999999", "2016-01-01"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Users"))
}
"show response" should {
"responses 404 if there is no such user" in {
val show = route(app, FakeRequest(GET, "/users/1").withHeaders("Authorization" -> "token")).get
status(show) mustBe NOT_FOUND
contentType(show) mustBe Some("application/json")
contentAsString(show) mustNot include("user")
}
"responses 200 if record exists" in {
val show = route(app, FakeRequest(GET, "/users/10").withHeaders("Authorization" -> "token")).get
status(show) mustBe OK
contentAsString(show) must include("user")
contentAsString(show) mustNot include("authToken")
}
}
}
示例11: UsersCreateSpec
//设置package包名称以及导入依赖的类
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.play.PlaySpec
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.FakeRequest
import play.api.test.Helpers._
import play.api.libs.json._
import test.helpers.DatabaseCleaner
import play.api.Play
class UsersCreateSpec extends PlaySpec with BeforeAndAfterAll {
val app = new GuiceApplicationBuilder().build
override def beforeAll() {
Play.maybeApplication match {
case Some(app) => ()
case _ => Play.start(app)
}
DatabaseCleaner.clean(List("Users"))
}
override def afterAll() {
DatabaseCleaner.clean(List("Users"))
}
"creating" should {
"returns 400 if bad request" in {
val request = FakeRequest(POST, "/users").withJsonBody(Json.parse("""{ "user": {"password":"pass"} }"""))
val create = route(app, request).get
status(create) mustBe BAD_REQUEST
contentType(create) mustBe Some("application/json")
contentAsString(create) must include("errors")
contentAsString(create) must include("\"email\":[\"must not be empty\"]")
}
"returns 201 if request is acceptable" in {
DatabaseCleaner.clean(List("Users"))
val request = FakeRequest(POST, "/users").withHeaders("Authorization" -> "token").withJsonBody(Json.parse("""{ "user": {"email":"[email protected]", "password":"pass"} }"""))
val create = route(app, request).get
status(create) mustBe CREATED
contentType(create) mustBe Some("application/json")
contentAsString(create) must include("user")
contentAsString(create) must include("authToken")
}
}
}
示例12: Campaign
//设置package包名称以及导入依赖的类
package models
import play.api.Play
import slick.driver.H2Driver.api._
import scala.concurrent.Future
import play.api.db.slick.DatabaseConfigProvider
import play.api.db.slick.HasDatabaseConfig
import slick.driver.JdbcProfile
case class Campaign(id: Option[Int], title: String, content: String)
trait CampaignsTable {
class Campaigns(tag: Tag) extends Table[Campaign](tag, "CAMPAIGNS") {
def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
def title = column[String]("TITLE")
def content = column[String]("CONTENT")
def * = (id.?, title, content) <> (Campaign.tupled, Campaign.unapply)
}
val campaigns = TableQuery[Campaigns]
}
object CampaignsDAO extends HasDatabaseConfig[JdbcProfile] with CampaignsTable {
val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
def findById(id: Int): Future[Option[Campaign]] =
db.run(campaigns.filter(_.id === id).result.headOption)
def findAll: Future[Seq[Campaign]] =
db.run(campaigns.result)
def insert(newRecord: Campaign): Future[Int] = {
db.run((campaigns returning campaigns.map(_.id)) += newRecord)
}
def update(record: Campaign): Future[Int] = {
db.run(campaigns.filter(_.id === record.id)
.map(a => (a.title, a.content))
.update((record.title, record.content)))
}
def getCampaignIds: Future[Seq[Int]] = {
db.run(campaigns.map(row => (row.id)).result)
}
}
示例13: Files
//设置package包名称以及导入依赖的类
package controllers
import java.io.FileInputStream
import java.util.UUID
import play.api.Play
import play.api.mvc.{Action, Controller, ResponseHeader, Result}
import com.google.common.io.BaseEncoding
import exceptions.GoogleAuthTokenExpired
import models.File
import play.api.libs.iteratee.Enumerator
object Files extends Controller {
lazy val oauth2 = new utils.OAuth2(Play.current)
def fileUpload = Action(parse.multipartFormData) { request =>
request.body.file("file").map { picture =>
val fileName = picture.filename
val contentType = picture.contentType.getOrElse("text/html")
val fstream = new FileInputStream(picture.ref.file)
val ftext = BaseEncoding.base64.encode(Stream.continually(fstream.read).takeWhile(_ != -1).map(_.toByte).toArray)
try {
val user = oauth2.getUser(request.session)
// Persist
File.create(new File(0, user.id, fileName, contentType, ftext))
// TODO(delyan): this should return file ID perhaps?
Ok(fileName)
} catch {
case expired: GoogleAuthTokenExpired =>
val state = UUID.randomUUID().toString
Ok(views.html.index(None, Some(oauth2.getLoginURL(state)), List()))
.withSession("oauth-state" -> state)
}
}.getOrElse {
Redirect(routes.Users.index)
.flashing("error" -> "Missing file")
}
}
def file = Action {
// TODO(delyan): File.get...
Ok("{}").as("application/json")
}
def downloadFile(fileName: String) = Action { request =>
val user = oauth2.getUser(request.session)
val file = File.getByName(user.id, fileName)
// TODO(delyan): File.get...
val fileContent: Enumerator[Array[Byte]] = Enumerator(BaseEncoding.base64.decode(file.file))
Result(
header = ResponseHeader(200),
body = fileContent
).as(file.content_type)
}
}
示例14: Utility
//设置package包名称以及导入依赖的类
package controllers
import play.api.Play
import play.api.mvc.{BodyParser, MultipartFormData, RequestHeader}
import play.core.parsers.Multipart
object Utility {
import play.api.mvc.BodyParsers.parse._
def multipartFormData[A](filePartHandler: RequestHeader => Multipart.FilePartHandler[A], maxLength: Long = DefaultMaxDiskLength): BodyParser[MultipartFormData[A]] = {
BodyParser("multipartFormData") { request =>
val app = play.api.Play.current // throw exception
implicit val mat = app.materializer
val bodyAccumulator = Multipart.multipartParser(DefaultMaxTextLength, filePartHandler(request)).apply(request)
// TODO enforceMaxLength(request, maxLength, bodyAccumulator) or maybe not
bodyAccumulator
}
}
}
示例15: PlayApp
//设置package包名称以及导入依赖的类
import play.api.{Application, ApplicationLoader, Environment, Mode, Play}
import play.core.server.{ServerConfig, ServerProvider}
object PlayApp extends App {
val config = ServerConfig(mode = Mode.Dev)
val application: Application = {
val environment = Environment(config.rootDir, this.getClass.getClassLoader, Mode.Dev)
val context = ApplicationLoader.createContext(environment)
val loader = ApplicationLoader(context)
loader.load(context)
}
Play.start(application)
val serverProvider: ServerProvider = ServerProvider.fromConfiguration(this.getClass.getClassLoader, config.configuration)
serverProvider.createServer(config, application)
}