当前位置: 首页>>代码示例>>Scala>>正文


Scala Result类代码示例

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


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

示例1: ResultMessage

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

import play.api.libs.json.{JsValue, Json}

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc.Results.{Ok, BadRequest}
import play.api.mvc.Result

object ResultMessage {
  val MESSAGE_INVALID_JSON = "Invalid json"
  val MESSAGE_DB_ERROR = "DB error"
  val MESSAGE_API_NOT_FOUND = "Api is not found"
  val MESSAGE_SOME_IDS_HAVE_NOT_REGISTERED = "Some ids have not registered"
  val MESSAGE_VALUE_IS_NOT_FOUND = (value: String) => s"$value is not found"
  val MESSAGE_TABLE_REPOSITORY_ERROR = (message: String) => s"$message"

  case class ErrorMessage(json: JsValue)

  private val keyErrorMessage = "errorMessage"

  sealed trait ApiResult {
    def getAsFuture: Future[Result]
  }

  case class ApiSuccess(future: Future[String]) extends ApiResult {
    override def getAsFuture: Future[Result] = future.map{Ok(_)}
  }

  case class ApiError(errorMessage: ErrorMessage) extends ApiResult {
    override def getAsFuture: Future[Result] = Future[Result]{BadRequest(errorMessage.json.toString)}
  }

  def generateError(errorMessage: String): ErrorMessage = {
    ErrorMessage(
      Json.obj(keyErrorMessage -> errorMessage)
    )
  }
} 
开发者ID:misoton665,项目名称:ibuki,代码行数:40,代码来源:ResultMessage.scala

示例2: onServerError

//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.play

import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.http.HttpVerbs.{ GET, POST }
import play.api.http.Status.INTERNAL_SERVER_ERROR
import play.api.mvc.Results._
import play.api.mvc.{ Call, RequestHeader, Result }
import org.danielnixon.progressive.play.extensions.{ RequestHeaderWrapper, ResultWrapper }
import org.danielnixon.progressive.play.Results.redirectToRefererOrElse
import org.danielnixon.progressive.shared.api.AjaxResponse
import play.twirl.api.HtmlFormat

import scalaz.Scalaz._
import scala.concurrent.Future


  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val errorMessage = serverErrorToErrorMessage(request, exception)
    Logger.error(errorMessage, exception)
    errorResponse(request, errorMessage, INTERNAL_SERVER_ERROR)
  }

  private def errorResponse(request: RequestHeader, errorMessage: String, statusCode: Int): Future[Result] = {
    val status = Status(statusCode)

    Future.successful {
      request.isAjax match {
        case true => status(AjaxResponse.asJson(AjaxResponse(Some(errorMessage), None, None)))
        case false if request.method === POST => redirectToRefererOrElse(errorRoute)(request).flashingError(errorMessage)
        case _ => status(errorPage(request, statusCode, errorMessage))
      }
    }
  }
} 
开发者ID:danielnixon,项目名称:progressive,代码行数:36,代码来源:ProgressiveErrorHandler.scala

示例3: StashController

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

import javax.inject.{Inject, Singleton}

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc
import play.api.mvc.{Action, AnyContent, Controller, Result}
import services.{Constants, JsonConverter, Stash, StashStore}

import scala.concurrent.Future


@Singleton
class StashController @Inject()(stashStore: StashStore, jsonConverter: JsonConverter) extends Controller {

  def addStash = Action.async(request => {
    validateStashAndRespond(request, (stash) => stashStore.addStash(stash).map(addedStash => Ok(Json.toJson[Stash](addedStash))))
  })

  def index = Action.async(request => {
    stashStore.getStashes().map(stashes => Ok(Json.toJson(stashes)))
  })

  def getStash(id: String) = Action.async(request =>
    stashStore.getStash(id).map {
      case Some(retrievedStash) => Ok(Json.toJson[Stash](retrievedStash))
      case None => NotFound
    }
  )

  def updateStash = Action.async(request => {
    validateStashAndRespond(request, (stash) => stashStore.updateStash(stash).map(updatedStash => Ok(Json.toJson[Stash](updatedStash))))
  })

  private def validateStashAndRespond(request: mvc.Request[AnyContent], responseAction: (Stash) => Future[Result]): Future[Result] = {
    request.body.asJson match {
      case None => Future.successful(BadRequest(Constants.noValidJsonMessage))
      case Some(json) =>
        val stash = jsonConverter.getStashFromRequestBody(json)
        stash match {
          case Some(value) => responseAction(value)
          case None => Future.successful(BadRequest(json))
        }
    }
  }
} 
开发者ID:dgrald,项目名称:locals-only-service-play,代码行数:48,代码来源:StashController.scala

示例4: BreakfastAppControllerSpec

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

import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers._

import scala.concurrent.Future

class BreakfastAppControllerSpec extends PlaySpec with OneAppPerSuite {
  "BreakfastAppController" should {
    "not return 404" when {
      "we try to hit the route /home" in {
        route(app, FakeRequest(GET, "/home")).map(status(_)) must not be Some(NOT_FOUND)
      }
    }
    "reneder a page" when {
      "we try to hit the route /home" in {
        var result: Option[Future[Result]] = route(app, FakeRequest(GET, "/home"))

        result.map(status(_)) mustBe Some(OK)

        val text: String = result.map(contentAsString(_)).get
        text must include ("Welcome to Play")
      }
    }
  }
} 
开发者ID:Hejocaso,项目名称:LunchApp,代码行数:29,代码来源:BreakfastAppControllerSpec.scala

示例5: BaseAuthController

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

import jp.t2v.lab.play2.auth.AuthElement
import models.document.{ DocumentAccessLevel, DocumentInfo, DocumentService }
import models.generated.tables.records.{ DocumentFilepartRecord, DocumentRecord, UserRecord }
import models.user.UserService
import play.api.Configuration
import play.api.mvc.Result
import scala.concurrent.ExecutionContext

abstract class BaseAuthController(
    config: Configuration,
    documents: DocumentService,
    users: UserService
  ) extends BaseController(config, users) with AuthElement {
  
  
  protected def documentPartResponse(
      docId: String,
      partNo: Int,
      user: UserRecord,
      response: (DocumentInfo, DocumentFilepartRecord, DocumentAccessLevel) => Result
    )(implicit ctx: ExecutionContext) = {

    documentResponse(docId, user, { case (doc, accesslevel) =>
      doc.fileparts.find(_.getSequenceNo == partNo) match {
        case None => NotFoundPage
        case Some(part) => response(doc, part, accesslevel)
      }
    })
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:34,代码来源:BaseAuthController.scala

示例6: BaseOptAuthController

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

import jp.t2v.lab.play2.auth.OptionalAuthElement
import models.document.{ DocumentAccessLevel, DocumentInfo, DocumentService }
import models.generated.tables.records.{ DocumentFilepartRecord, DocumentRecord, UserRecord }
import models.user.UserService
import play.api.Configuration
import play.api.mvc.{ AnyContent, Request, Result }
import scala.concurrent.{ ExecutionContext, Future }

abstract class BaseOptAuthController(
    config: Configuration,
    documents: DocumentService,
    users: UserService
  ) extends BaseController(config, users) with OptionalAuthElement {
  
  
  
  protected def documentPartResponse(
      documentId: String,
      partNo: Int,
      maybeUser: Option[UserRecord],
      response: (DocumentInfo, DocumentFilepartRecord, DocumentAccessLevel) => Future[Result]
    )(implicit ctx: ExecutionContext) = {
    
    documentResponse(documentId, maybeUser, { case (doc, accesslevel) =>
      doc.fileparts.find(_.getSequenceNo == partNo) match {
        case None => Future.successful(NotFoundPage)
        case Some(part) => response(doc, part, accesslevel)
      }
    })
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:35,代码来源:BaseOptAuthController.scala

示例7: ErrorHandler

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

import org.slf4j.MDC
import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{Result, RequestHeader}

import scala.concurrent.Future
import scala.util.Try

class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, m: String): Future[Result] = {
    val message = if(m.isEmpty) "there was a problem in the request, please check the path and the headers" else m
    Logger.warn(s"There was a client error with statusCode $statusCode in ${request.method} ${request.path} with message: $message")
    Future.successful(Status(statusCode)(Json.obj("error" -> true, "message" -> message)))
  }

  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val requestId = Try(MDC.get("requestId")).getOrElse{Logger.warn("couldnt get the requestId from MDC");""}
    val message = s"There was a server error in ${request.method} ${request.path} with requestId $requestId"
    Logger.error(message, exception)
    Future.successful(InternalServerError(Json.obj("error" -> true, "message" -> exception.getMessage)))
  }

} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:29,代码来源:ErrorHandler.scala

示例8: apply

//设置package包名称以及导入依赖的类
package net.white_azalea.filters.security.authorization

import javax.inject.Inject

import akka.stream.Materializer
import play.api.mvc.{ Filter, RequestHeader, Result }

import scala.concurrent.Future


  override def apply(nextFilter: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    val authName = auth.readAuthName(rh)
    lazy val isAccessible = auth.isAccessible(authName)(rh)

    if (isAccessible) {
      nextFilter(rh)
    } else {
      auth.handleNotAccessible(rh)
    }
  }
} 
开发者ID:Sunao-Yoshii,项目名称:SimplePlayModule,代码行数:22,代码来源:AuthorizationFilter.scala

示例9: CorrelationIdFilter

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

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, Materializer }
import javax.inject.Inject
import play.api.mvc.{ Filter, RequestHeader, Result }

import scala.concurrent.{ ExecutionContext, Future }

class CorrelationIdFilter @Inject() (implicit val executionContext: ExecutionContext, implicit val actorSystem: ActorSystem) extends Filter {

  val mat: Materializer = ActorMaterializer()
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    nextFilter(requestHeader.copy(
      tags = requestHeader.tags +
      (CorrelationContext.correlationIdTag ->
        requestRefNum(requestHeader).map(_.toString.toLowerCase).getOrElse(CorrelationContext.newCorrelationId))
    ))
  }

  private def requestRefNum(requestHeader: RequestHeader): Option[String] = {
    requestHeader.headers.get("L-IS24-RequestRefnum").map(_.trim).filter(!_.isEmpty)
  }
} 
开发者ID:mriehl,项目名称:play-bug,代码行数:25,代码来源:CorrelationIdFilter.scala

示例10: SettingSpec

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

import play.api.mvc.{RequestHeader, Result, Results}

class SettingSpec extends TestHelper {
  describe("Setting()") {
    it("can start http service on some port") {
      val setting = Setting()
      start(setting) { server =>
        assert(server.port > 0)
      }
    }
  }

  describe("Setting(methods = Set(GET))") {
    val setting = Setting(methods = Set(GET))
    it("accepts GET [200]") {
      start(setting) { server =>
        assert(get(server.url).getStatusCode === 200)
      }
    }

    it("rejects POST [404]") {
      start(setting) { server =>
        assert(post(server.url, "body").getStatusCode === 404)
      }
    }
  }

  describe("Setting(handler = ???") {
    val handler: PartialFunction[RequestHeader, Result] = {
      case h: RequestHeader if h.method == "POST" => Results.Unauthorized
      case h: RequestHeader if h.uri.contains("rerorero") => Results.InternalServerError
    }

    it("responses matched handler results") {
      start(Setting(methods = Set(GET, POST), handler = handler)) { server =>
        assert(post(server.url, "body").getStatusCode === 401)
        assert(get(server.url + "rerorero").getStatusCode === 500)
      }
    }

    it("responses according to methods property if not matched") {
      start(Setting(methods = Set(GET), handler = handler)) { server =>
        assert(post(server.url, "body").getStatusCode === 404)
        assert(get(server.url + "rorerore").getStatusCode === 200)
      }
    }
  }
} 
开发者ID:xuwei-k,项目名称:httpmock,代码行数:51,代码来源:SettingSpec.scala

示例11: ApiTest

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

import user.Fixtures

import scala.concurrent.Future
import play.api.libs.json.Json
import play.api.mvc.Result
import play.api.test.FakeApplication
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.scalatest.TestData

class ApiTest extends ApiSpecServer with TestUtils {

  implicit override def newAppForTest(td: TestData): FakeApplication = getFakeApp(new TestGlobal()(Fixtures))

  "The application " should {

    "return OK on ping" in {
      val result: Future[Result] = (new controllers.Application()).ping().apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      bodyText mustBe "Ok"
    }
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:26,代码来源:ApiTest.scala

示例12: helloMessage

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

import com.google.inject.Inject
import io.toolsplus.atlassian.connect.play.actions.JwtAuthenticationActions
import io.toolsplus.atlassian.connect.play.api.models.AtlassianHostUser
import io.toolsplus.atlassian.connect.play.auth.jwt.request.SelfAuthenticationTokenGenerator
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc.{Controller, Result}

import scala.concurrent.Future


  def helloMessage = jwtAuthenticationActions.withAtlassianHostUser.async {
    implicit request =>
      val json =
        Json.obj("message" -> s"Hello ${request.hostUser.host.baseUrl}")
      Future
        .successful(json)
        .map(json => withJwtAuthorizationHeaders(Ok(json)))
  }

  private def withJwtAuthorizationHeaders(result: Result)(
      implicit hostUser: AtlassianHostUser): Result = {
    selfAuthenticationTokenGenerator.createSelfAuthenticationToken(hostUser) match {
      case Right(token) => result.withHeaders(AUTHORIZATION -> s"JWT $token")
      case Left(error) => {
        logger.error(s"Failed to sign JWT: ${error.getMessage}")
        InternalServerError(error.getMessage)
      }
    }
  }
} 
开发者ID:toolsplus,项目名称:atlassian-connect-play-seed,代码行数:35,代码来源:ApiController.scala

示例13: CameraRelayControllerTest

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

import com.intersection.camerarelay.UploadManager
import org.mockito.Matchers._
import org.scalatest.concurrent.{Futures, ScalaFutures}
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
import play.api.libs.Files
import play.api.mvc.{Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.mockito.Mockito._

import scala.concurrent.Future

class CameraRelayControllerTest extends FunSpec with Matchers with MockitoSugar with BeforeAndAfter with Futures with ScalaFutures {
  var controller : CameraRelayController = _
  var uploadManager : UploadManager = _

  before {
    uploadManager = mock[UploadManager]
    controller = new CameraRelayController(uploadManager)
  }

  describe(classOf[CameraRelayControllerTest].getName) {
    it("Rejects requests without a valid siteId header : X-Site-Id") {
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
      val result = controller.uploadVideoChunk().apply(request)
      status(result) should equal(400)
    }

    it("Rejects requests without a valid Link-Time header : X-Link-Time") {
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234")).withBody(Files.TemporaryFile())
      val result: Future[Result] = controller.uploadVideoChunk().apply(request)
      status(result) should equal(400)
    }

    it("Accepts a fully formed request") {
      import scala.concurrent.ExecutionContext.Implicits.global
      when(uploadManager.handleVideoChunk(any[String],any[String],any[Files.TemporaryFile])).thenReturn(Future(()))
      val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
      val result: Future[Result] = controller.uploadVideoChunk().apply(request)
      status(result) should equal(202)
    }

  }
} 
开发者ID:arjunmukherjee,项目名称:camerarelay,代码行数:48,代码来源:CameraRelayControllerTest.scala

示例14: Session

//设置package包名称以及导入依赖的类
package ejisan.play.libs.scalauth

import play.api.mvc.{ Result, RequestHeader }
import play.api.{ Configuration, Logger }

case class Session(id: String, impersonator: Option[String]) {
  def toSeq(SESSION_COOKIE_NAME: String, IMPERSONATING_SESSION_COOKIE_NAME: String): Seq[(String, String)] =
    Seq(SESSION_COOKIE_NAME -> Some(id), IMPERSONATING_SESSION_COOKIE_NAME -> impersonator).collect {
      case (key, Some(value)) => (key, value)
    }
}

class PlaySessionManager(configuration: Configuration) {
  val SESSION_COOKIE_NAME: String =
    configuration.getString("scalauth.play.secure_action.cookie_name").getOrElse("SESSION")
  val IMPERSONATING_SESSION_COOKIE_NAME: String =
    configuration.getString("scalauth.play.secure_action.impersonator_cookie_name").getOrElse("IMPERSONATOR")

  def set(session: Session)(result: => Result)(implicit request: RequestHeader): Result = {
    Logger.debug(s"Set session for ID: `${session.id}` and IMPERSONATOR_ID: `${session.impersonator.getOrElse("N/A")}`.")
    forceEnd(result).addingToSession(session.toSeq(SESSION_COOKIE_NAME, IMPERSONATING_SESSION_COOKIE_NAME):_*)
  }

  def get(implicit request: RequestHeader): Option[Session] =
    request.session.get(SESSION_COOKIE_NAME).map(Session(_, request.session.get(IMPERSONATING_SESSION_COOKIE_NAME)))

  def start(id: String)(result: => Result)(implicit request: RequestHeader): Result =
    set(Session(id, None))(result)

  def restart(result: => Result)(implicit request: RequestHeader): Result =
    get.map(set(_)(result)).getOrElse(result)

  def impersonate(id: String)(result: => Result)(implicit request: RequestHeader): Result = {
    val impersonator = try {
      request.session(SESSION_COOKIE_NAME)
    } catch {
      case _: NoSuchElementException =>
      val e = new IllegalStateException("Impersonator must start main session before impersonating session.")
        Logger.error("Main session not found", e)
        throw e
    }
    set(Session(id, Some(impersonator)))(result)
  }

  def end(result: => Result)(implicit request: RequestHeader): Result = {
    if (request.session.data.keySet.exists(_ == IMPERSONATING_SESSION_COOKIE_NAME)) {
      result.removingFromSession(IMPERSONATING_SESSION_COOKIE_NAME)
    } else if (request.session.data.keySet.exists(_ == SESSION_COOKIE_NAME)) {
      result.removingFromSession(SESSION_COOKIE_NAME)
    } else {
      result
    }
  }

  def forceEnd(result: => Result)(implicit request: RequestHeader): Result =
    result.removingFromSession(SESSION_COOKIE_NAME, IMPERSONATING_SESSION_COOKIE_NAME)
} 
开发者ID:ejisan,项目名称:play-scalauth-secureaction,代码行数:58,代码来源:PlaySessionManager.scala

示例15: TestBuilder

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

import play.api.Application
import play.api.mvc.{AnyContentAsEmpty, Result}
import play.api.test.{FakeHeaders, FakeRequest, Helpers}
import play.mvc.Call

import scala.concurrent.Future

object TestBuilder {

  object anUser {

    import play.api.test.Helpers._
    def GET(call: Call)(implicit app: Application): Option[Future[Result]] =
      route(app, fakeUnauthenticatedRequest(Helpers.GET, call.url(), FakeHeaders(), AnyContentAsEmpty))

    def POST[A](call: Call)(body: A)(implicit w: play.api.http.Writeable[A], app: Application): Option[Future[Result]] =
      route(app, fakeUnauthenticatedRequest(Helpers.POST, call.url(), jsonHeaders, body))

    private def fakeUnauthenticatedRequest[A](method: String, uri: String, headers: FakeHeaders, body: A): FakeRequest[A] = FakeRequest(
      method,
      uri,
      withAjaxHeader(headers),
      body
    )

    private def jsonHeaders = FakeHeaders(
      Seq("Content-Type" -> "application/json")
    )

    private def withAjaxHeader(headers: FakeHeaders): FakeHeaders = headers.copy(data = headers.data :+ ("X-Requested-With" -> "XMLHttpRequest"))
  }

} 
开发者ID:fagossa,项目名称:play-reactive-couchbase,代码行数:36,代码来源:TestBuilder.scala


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