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

Scala Play类代码示例

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

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



在下文中一共展示了Play类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
    }
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:58,代码来源:CountriesDestroySpec.scala


示例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()
    }
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:62,代码来源:Global.scala


示例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)
  }
  } 
开发者ID:MartinEliasQ,项目名称:AppEmpre-Dojo3-Scala,代码行数:41,代码来源:Restaurants.scala


示例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
} 
开发者ID:hmrc,项目名称:trust-registration-frontend,代码行数:58,代码来源:frontendGlobal.scala


示例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")
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:55,代码来源:SessionCreateSpec.scala


示例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")
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:53,代码来源:CountriesShowSpec.scala


示例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")
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:51,代码来源:CountriesIndexSpec.scala


示例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")
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:42,代码来源:CountriesCreateSpec.scala


示例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")
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:42,代码来源:UsersIndexSpec.scala


示例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")
    }
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:51,代码来源:UsersShowSpec.scala


示例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")
    }
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:54,代码来源:UsersCreateSpec.scala


示例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)
  }


} 
开发者ID:kaznishi,项目名称:zz-sandbox-petit-ad,代码行数:48,代码来源:Campaign.scala


示例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)
  }

} 
开发者ID:delqn,项目名称:botslandia,代码行数:59,代码来源:Files.scala


示例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
    }
  }
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:23,代码来源:Utility.scala


示例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)
} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:20,代码来源:PlayApp.scala


示例16: ConnectDb

//设置package包名称以及导入依赖的类
package org.intracer.wmua.cmd

import play.api.Play
import scalikejdbc.{ConnectionPool, GlobalSettings, LoggingSQLAndTimeSettings}

case class ConnectDb(host: String = "jury.wikilovesearth.org.ua") extends (() => Unit) {

  def apply() = {
    Class.forName("com.mysql.jdbc.Driver")

    val url = s"jdbc:mysql://$host/wlxjury"

    val user = Play.current.configuration.getString("db.default.user").get
    val password = Play.current.configuration.getString("db.default.user").get

    ConnectionPool.singleton(url, user, password)

    GlobalSettings.loggingSQLAndTime = LoggingSQLAndTimeSettings(
      enabled = true,
      singleLineMode = false,
      printUnprocessedStackTrace = false,
      stackTraceDepth = 15,
      logLevel = 'info,
      warningEnabled = false,
      warningThresholdMillis = 3000L,
      warningLogLevel = 'warn
    )

  }

} 
开发者ID:intracer,项目名称:wlxjury,代码行数:32,代码来源:ConnectDb.scala


示例17: Truck

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

import scala.collection.JavaConverters._
import com.fasterxml.jackson.databind.{ ObjectMapper, JsonNode }
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.Play
import sys.process._

case class Truck (
  name: String,
  address: String,
  cuisine: List[String],
  url: String) {
  override def toString: String = s"""$name (${cuisine.mkString(",")}) @ $address [$url]"""
}

object Truck {
  def newObjectMapper: ObjectMapper = {
    val m = new ObjectMapper()
    m.registerModule(DefaultScalaModule)
  }

  private[Truck] lazy val mapper = newObjectMapper

  val defaultLat = Play.maybeApplication.flatMap(_.configuration.getDouble("foodtrucks.latitude")).getOrElse(0.0)
  val defaultLon = Play.maybeApplication.flatMap(_.configuration.getDouble("foodtrucks.longitude")).getOrElse(0.0)

  def apply(jsonNode: JsonNode): Truck = {
    val info = jsonNode.get("obj")

    Truck(
      info.get("name").asText,
      info.get("last_seen").get("address").asText,
      info.get("cuisine").elements.asScala.map(_.asText).toList,
      info.get("url").asText
    )
  }

  def listAll(lat: Double = defaultLat, lon: Double = defaultLon): List[Truck] = {
    val result = Seq("curl", "-XGET", s"http://nyctruckfood.com/api/trucks/search?q=$lat,$lon").!!
    mapper.readTree(result).elements.asScala.map(Truck(_)).toList
  }
} 
开发者ID:andy327,项目名称:slack-foodtrucks,代码行数:44,代码来源:Truck.scala


示例18: ControllerConfiguration

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fubenos3

import com.typesafe.config.Config
import play.api.{Application, Configuration, Play}
import uk.gov.hmrc.play.audit.filters.AuditFilter
import uk.gov.hmrc.play.auth.controllers.AuthParamsControllerConfig
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.http.logging.filters.LoggingFilter
import uk.gov.hmrc.play.microservice.bootstrap.DefaultMicroserviceGlobal
import uk.gov.hmrc.play.auth.microservice.filters.AuthorisationFilter
import net.ceedubs.ficus.Ficus._
import uk.gov.hmrc.play.filters.MicroserviceFilterSupport
import play.api.i18n.Messages.Implicits._
import play.api.Play.current


object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object AuthParamsControllerConfiguration extends AuthParamsControllerConfig {
  lazy val controllerConfigs = ControllerConfiguration.controllerConfigs
}

object MicroserviceAuditFilter extends AuditFilter with AppName with MicroserviceFilterSupport {
  override val auditConnector = MicroserviceAuditConnector
  override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
}

object MicroserviceLoggingFilter extends LoggingFilter with MicroserviceFilterSupport {
  override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object MicroserviceAuthFilter extends AuthorisationFilter with MicroserviceFilterSupport {
  override lazy val authParamsConfig = AuthParamsControllerConfiguration
  override lazy val authConnector = MicroserviceAuthConnector
  override def controllerNeedsAuth(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuth
}

object MicroserviceGlobal extends DefaultMicroserviceGlobal with RunMode with MicroserviceFilterSupport {
  override val auditConnector = MicroserviceAuditConnector

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")

  override val loggingFilter = MicroserviceLoggingFilter

  override val microserviceAuditFilter = MicroserviceAuditFilter

  override val authFilter = Some(MicroserviceAuthFilter)
} 
开发者ID:hmrc,项目名称:fu-be-nos3,代码行数:51,代码来源:microserviceGlobal.scala


示例19: ControllerConfiguration

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice

import com.typesafe.config.Config
import play.api.{Application, Configuration, Play}
import uk.gov.hmrc.play.audit.filters.AuditFilter
import uk.gov.hmrc.play.auth.controllers.AuthParamsControllerConfig
import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode}
import uk.gov.hmrc.play.http.logging.filters.LoggingFilter
import uk.gov.hmrc.play.microservice.bootstrap.DefaultMicroserviceGlobal
import uk.gov.hmrc.play.auth.microservice.filters.AuthorisationFilter
import net.ceedubs.ficus.Ficus._


object ControllerConfiguration extends ControllerConfig {
  lazy val controllerConfigs = Play.current.configuration.underlying.as[Config]("controllers")
}

object AuthParamsControllerConfiguration extends AuthParamsControllerConfig {
  lazy val controllerConfigs = ControllerConfiguration.controllerConfigs
}

object MicroserviceAuditFilter extends AuditFilter with AppName {
  override val auditConnector = MicroserviceAuditConnector
  override def controllerNeedsAuditing(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsAuditing
}

object MicroserviceLoggingFilter extends LoggingFilter {
  override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging
}

object MicroserviceAuthFilter extends AuthorisationFilter {
  override lazy val authParamsConfig = AuthParamsControllerConfiguration
  override lazy val authConnector = MicroserviceAuthConnector
  override def controllerNeedsAuth(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuth
}

object MicroserviceGlobal extends DefaultMicroserviceGlobal with RunMode {
  override val auditConnector = MicroserviceAuditConnector

  override def microserviceMetricsConfig(implicit app: Application): Option[Configuration] = app.configuration.getConfig(s"microservice.metrics")

  override val loggingFilter = MicroserviceLoggingFilter

  override val microserviceAuditFilter = MicroserviceAuditFilter

  override val authFilter = Some(MicroserviceAuthFilter)
} 
开发者ID:Baisysoft,项目名称:off-payroll-decision-service,代码行数:48,代码来源:microserviceGlobal.scala


示例20: HomeController

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

import java.io.File
import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import controllers.api.auth.{AuthConfigImpl, NormalUser}
import jp.t2v.lab.play2.auth.AuthElement
import play.api.Play
import play.api.mvc.{Action, Controller, Result}

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class HomeController @Inject() (actorSystem: ActorSystem) extends Controller with AuthElement with AuthConfigImpl{

  implicit val myExecutionContext: ExecutionContext = actorSystem.dispatcher

  def index = AsyncStack(AuthorityKey -> NormalUser) { implicit request =>
    Future {loadIndex()}
  }

  def indexAll(path: String) = AsyncStack(AuthorityKey -> NormalUser) { implicit request =>
    Future {loadIndex()}
  }

  def loginForm = Action.async {
    Future {loadIndex()}
  }

  def loadIndex():Result = {
    val f = new File("webConsole/front/index.html")
    Ok(scala.io.Source.fromFile(f.getCanonicalPath).mkString).as("text/html")
  }

  def dist(path: String) = Action {
    val f = new File("webConsole/front/dist/" + path)
    Ok(scala.io.Source.fromFile(f.getCanonicalPath).mkString).as("text/html")
  }

  def favicon() = Action {
    val f = new File("webConsole/front/public/favicon")
    Ok(scala.io.Source.fromFile(f.getCanonicalPath).mkString).as("text/html")
  }

  //DI?????Router?Controller???????????????
  def routes() = Action {
    val myRoutes = Play.current.routes.documentation map { r =>
      "%-10s %-50s %s".format(r._1, r._2, r._3)
    }
    Ok(myRoutes.mkString("\n"))
  }

} 
开发者ID:tm-sukehiro,项目名称:play2-sandbox,代码行数:56,代码来源:HomeController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Timestamp类代码示例发布时间:2022-05-23
下一篇:
Scala RunWith类代码示例发布时间: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