本文整理汇总了Scala中play.api.mvc.RequestHeader类的典型用法代码示例。如果您正苦于以下问题:Scala RequestHeader类的具体用法?Scala RequestHeader怎么用?Scala RequestHeader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestHeader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CustomCORSFilter
//设置package包名称以及导入依赖的类
package filters
import javax.inject.{Inject, Singleton}
import akka.stream.Materializer
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result}
import play.filters.cors.CORSFilter
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class CustomCORSFilter @Inject()(corsFilter: CORSFilter)
(implicit override val mat: Materializer,
exec: ExecutionContext) extends Filter {
override def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
requestHeader.headers.get(HeaderNames.ORIGIN) match {
case (Some("null")) =>
val newHeaders = requestHeader.headers
.remove(HeaderNames.ORIGIN)
.add(HeaderNames.ORIGIN -> "http://file.url.local.null")
val mappedOrigin = requestHeader.copy(headers = newHeaders)
corsFilter(nextFilter)(mappedOrigin)
.map { result =>
result.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "null")
}
case _ => corsFilter(nextFilter)(requestHeader)
}
}
}
示例2: UserFeedback
//设置package包名称以及导入依赖的类
package controllers
import play.api.data.Form
import play.api.mvc.{Flash, RequestHeader}
import UserFeedback.{Feedback, Success, Yes, No}
case class UserFeedback(message: String, isError: Boolean) {
def toSeq: Seq[(String, String)] = Seq(
Feedback -> message,
Success -> (if (isError) No else Yes)
)
}
object UserFeedback {
val Feedback = "feedback"
val Success = "success"
val Yes = "yes"
val No = "no"
def success(message: String) = UserFeedback(message, isError = false)
def error(message: String) = UserFeedback(message, isError = true)
def flashed(request: RequestHeader): Option[UserFeedback] =
flashed(request.flash)
def flashed(flash: Flash, textKey: String = Feedback): Option[UserFeedback] =
for {
message <- flash get textKey
isError = (flash get Success) contains No
} yield UserFeedback(message, isError)
def formed(form: Form[_]) =
form.globalError.orElse(form.errors.headOption)
.map(formError => error(formError.message))
}
示例3: HelpController
//设置package包名称以及导入依赖的类
package controllers.help
import controllers.{ HasVisitLogging, WebJarAssets }
import javax.inject.{ Inject, Singleton }
import models.visit.VisitService
import play.api.mvc.{ Action, Controller, RequestHeader }
import play.twirl.api.HtmlFormat
@Singleton
class HelpController @Inject() (
implicit val visits: VisitService,
implicit val webjars: WebJarAssets
) extends Controller with HasVisitLogging {
private def result(template: HtmlFormat.Appendable)(implicit request: RequestHeader) = {
logPageView()
Ok(template)
}
def index = Action { Redirect(routes.HelpController.showTutorial()) }
def showTutorial = Action { implicit request => result(views.html.help.tutorial()) }
def showLocalizedTutorial(lang: String) = Action { implicit request =>
lang.toUpperCase match {
case "DE" => result(views.html.help.tutorial_de())
case "ES" => result(views.html.help.tutorial_es())
case "IT" => result(views.html.help.tutorial_it())
case _ => NotFound(views.html.error404())
}
}
def showFAQ = Action { implicit request => result(views.html.help.faq()) }
def showAbout = Action { implicit request => result(views.html.help.about()) }
}
示例4: toResult
//设置package包名称以及导入依赖的类
package api
import ApiResponse._
import ApiError._
import models.ApiLog
import play.api.mvc.Results._
import play.api.mvc.{ Result, RequestHeader }
import play.api.libs.json._
import play.api.libs.json.Json._
import play.api.i18n.Lang
def toResult[R <: RequestHeader](implicit request: R, lang: Lang): Result = {
val envelope = request.getQueryString("envelope") == Some("true")
toResult(envelope)
}
def toResult(envelope: Boolean = false)(implicit lang: Lang): Result = {
val js = if (envelope) envelopedJson else json
(status match {
case STATUS_CREATED => if (js == JsNull) Created else Created(js)
case STATUS_ACCEPTED => if (js == JsNull) Accepted else Accepted(js)
case STATUS_NOCONTENT => NoContent
case s if s < 300 => if (js == JsNull) Ok else Ok(js)
case STATUS_BADREQUEST => BadRequest(js)
case STATUS_UNAUTHORIZED => Unauthorized(js)
case STATUS_FORBIDDEN => Forbidden(js)
case STATUS_NOTFOUND => NotFound(js)
case s if s > 400 && s < 500 => BadRequest(js)
case _ => InternalServerError(js)
}).withHeaders((headers ++ Api.basicHeaders): _*)
}
}
示例5: 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)))
}
}
示例6: ErrorHandler
//设置package包名称以及导入依赖的类
package utils
import javax.inject.{Inject, Provider}
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import play.api.http.DefaultHttpErrorHandler
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}
import play.api.routing.Router
import play.api.{Configuration, OptionalSourceMapper}
import scala.concurrent.Future
import controllers.{WebJarAssets, routes}
class ErrorHandler @Inject() (
val messagesApi: MessagesApi,
env: play.api.Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: javax.inject.Provider[Router],
p: Provider[WebJarAssets])
extends DefaultHttpErrorHandler(env, config, sourceMapper, router)
with SecuredErrorHandler with I18nSupport {
// https://www.playframework.com/documentation/2.5.x/Migration25#Handling-legacy-components
implicit lazy val webJarAssets = p.get()
override def onNotAuthenticated(implicit request: RequestHeader): Future[Result] =
Future.successful(Redirect(routes.Auth.signIn()))
override def onNotAuthorized(implicit request: RequestHeader): Future[Result] =
Future.successful(Redirect(routes.Auth.signIn()).flashing("error" -> Messages("error.accessDenied")))
override def onNotFound(request: RequestHeader, message: String): Future[Result] =
Future.successful(Ok(views.html.errors.notFound(request)))
override def onServerError(request:RequestHeader, exception:Throwable):Future[Result] =
Future.successful(Ok(views.html.errors.serverError(request, exception)))
}
示例7: CorrelationContext
//设置package包名称以及导入依赖的类
package filters
import java.util.UUID
import play.api.mvc.RequestHeader
case class CorrelationContext(correlationId: String = CorrelationContext.newCorrelationId)
object CorrelationContext {
val correlationIdTag: String = "correlationId"
def fromRequest(request: RequestHeader): CorrelationContext = CorrelationContext(
correlationId = correlationId(request).getOrElse(newCorrelationId)
)
def newCorrelationId: String = {
UUID.randomUUID().toString.toLowerCase
}
private def correlationId(request: RequestHeader): Option[String] = {
if (request.tags.contains(correlationIdTag))
Some(request.tags(correlationIdTag))
else
None
}
}
示例8: 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)
}
}
示例9: MessageDigestController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import play.api.libs.streams.Accumulator
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{Action, Controller, RequestHeader}
import play.core.parsers.Multipart.{FileInfo, FilePartHandler}
import services.MessageDigestService
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class MessageDigestController @Inject()(digestService: MessageDigestService)(implicit exec: ExecutionContext) extends Controller{
def index = Action.async {
Future.successful( Ok(views.html.MessageDigest.index(digestService.algorithms)) )
}
def upload = Action(Utility.multipartFormData(digest)){ implicit request =>
val digest = request.body.files.map(f => (f.filename, f.ref))
Ok(views.html.MessageDigest.digest(digest))
}
def digest(rh: RequestHeader): FilePartHandler[String] = {
case FileInfo(key, fileName, contentType) =>
val Some(Seq(algo, _*)) = rh.queryString.get("algorithm")
Accumulator(digestService.sink(algo)).map{ d =>
FilePart(key, fileName, contentType, d)
}
}
}
示例10: 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
}
}
}
示例11: SecuredSpec
//设置package包名称以及导入依赖的类
package controllers
import db.scalikejdbc.{InMemDb, UserJdbc}
import org.intracer.wmua.User
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.mvc.{RequestHeader, Security, Session}
class SecuredSpec extends Specification with Mockito with InMemDb {
sequential
val userDao = UserJdbc
def mockRequest(username: String): RequestHeader = {
val request = mock[RequestHeader]
val session = mock[Session]
session.get(Security.username) returns Some(username)
request.session returns session
request
}
"user" should {
"load from db" in {
inMemDbApp {
val username = "[email protected]"
val user = User("fullname", username, None, Set("jury"), Some("password hash"), Some(10))
val created = userDao.create(user)
val request: RequestHeader = mockRequest(username)
new Secured {}.userFromRequest(request) === Some(created)
}
}
"be None if not in db" in {
inMemDbApp {
val username = "user login"
val user = User("fullname", username, None, Set("jury"), Some("password hash"), Some(10))
val created = userDao.create(user)
val request: RequestHeader = mockRequest(username + " other")
new Secured {}.userFromRequest(request) === None
}
}
}
}
示例12: AccessLog
//设置package包名称以及导入依赖的类
package httpmock
import play.api.mvc.RequestHeader
final case class AccessLog(
request: RequestHeader,
bodyOpt: Option[ArrayByte] = None
) {
override def equals(other: Any): Boolean = other match {
case that: AccessLog =>
this.===(that)
case _ =>
false
}
def ===(that: AccessLog): Boolean = (this.bodyOpt, that.bodyOpt) match {
case (Some(body1), Some(body2)) =>
(this.request == that.request) && body1 == body2
case (None, None) =>
this.request == that.request
case _ =>
false
}
override def hashCode = {
(request.hashCode() * 31) + bodyOpt.map(_.hashCode).getOrElse(7)
}
}
示例13: 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)
}
}
}
}
示例14: CapabilityDisjunctionOps
//设置package包名称以及导入依赖的类
package com.jasperdenkers.play
import play.api.mvc.RequestHeader
package object auth {
implicit class CapabilityDisjunctionOps(firstCapability: Capability) {
def ||(secondCapability: Capability) = Disjunction(firstCapability, secondCapability)
}
implicit class CapabilityConjunctionOps(firstCapability: Capability) {
def &&(secondCapability: Capability) = Conjunction(firstCapability, secondCapability)
}
implicit def token2Capability(token: Token): Capability = new CapabilityByToken {
def predicate = _ == token
}
implicit def isAuthenticated(implicit request: RequestHeader) =
request match {
case _: AuthenticatedRequest[_, _] | _: AuthorizedRequest[_, _] => true
case _ => false
}
implicit def isAuthorized(capabilities: Capability*)(implicit request: RequestHeader) =
request match {
case authorizedRequest: AuthorizedRequest[_, _] => authorizedRequest.isAuthorized(capabilities.toSet)
case _ => false
}
}
示例15: 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)
}