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


Scala Filter类代码示例

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


在下文中一共展示了Filter类的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)
    }
  }
} 
开发者ID:umbc-cmcs447-grp,项目名称:rest-api,代码行数:34,代码来源:CustomCORSFilter.scala

示例2: 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

示例3: 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

示例4: JwtFilter

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

import akka.stream.Materializer
import com.google.inject.Inject
import model.JwtUser
import play.api.Logger
import play.api.libs.json.Json
import play.api.mvc.{Filter, RequestHeader, Result}
import play.api.mvc.Results._
import utils.JwtUtils

import scala.concurrent.{ExecutionContext, Future}

class JwtFilter @Inject()(implicit val mat: Materializer, implicit val ec: ExecutionContext) extends Filter {

  val logger: Logger = Logger(this.getClass())

  import utils.DefaultJsonParsers._

  override def apply(next: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    if (!JwtUtils.unsecuredEndpoints.contains(rh.path)) {
      logger.debug("Checking JWT token")
      val jwtToken = JwtUtils.getToken(rh.headers.get(JwtUtils.tokenHdr).getOrElse(""))
      if (jwtToken.isFailure) Future(Unauthorized)
      else next(rh.addAttr[JwtUser](JwtUtils.tokenAttr, Json.fromJson[JwtUser](Json.parse(jwtToken.get)).get))
    } else {
      logger.debug("Allowed in with no token")
      next(rh)
    }
  }

} 
开发者ID:olo-b,项目名称:FoodService,代码行数:33,代码来源:JwtFilter.scala

示例5: RegExCORSFilter

//设置package包名称以及导入依赖的类
package com.github.dgilling.regexcors

import akka.stream.Materializer
import play.api.Logger
import play.api.http.{DefaultHttpErrorHandler, HttpErrorHandler}
import play.api.mvc.{Result, RequestHeader, Filter}
import play.core.j.JavaHttpErrorHandlerAdapter
import play.filters.cors.{CORSFilter, AbstractCORSPolicy, CORSConfig}

import scala.concurrent.Future


class RegExCORSFilter(
                  override protected val corsConfig: CORSConfig = CORSConfig(),
                  override protected val errorHandler: HttpErrorHandler = DefaultHttpErrorHandler,
                  private val pathPrefixes: Seq[String] = Seq("/"),
                  private val ignoredPathPrefixes: Seq[String] = Seq.empty[String])(override implicit val mat: Materializer)
  extends CORSFilter {

  // Java constructor
  def this(corsConfig: CORSConfig, errorHandler: play.http.HttpErrorHandler, pathPrefixes: java.util.List[String])(mat: Materializer) = {
    this(corsConfig, new JavaHttpErrorHandlerAdapter(errorHandler), Seq(pathPrefixes.toArray.asInstanceOf[Array[String]]: _*))(mat)
  }

  override protected val logger = Logger(classOf[CORSFilter])

  override def apply(f: RequestHeader => Future[Result])(request: RequestHeader): Future[Result] = {
    if (pathPrefixes.exists(request.path.startsWith) &&
      !ignoredPathPrefixes.exists(request.path.startsWith)) {
      filterRequest(f, request)
    } else {
      f(request)
    }
  }
}

object RegExCORSFilter {

  val RequestTag = "CORS_REQUEST"

  def apply(corsConfig: CORSConfig = CORSConfig(), errorHandler: HttpErrorHandler = DefaultHttpErrorHandler,
            pathPrefixes: Seq[String] = Seq("/"))(implicit mat: Materializer) =
    new CORSFilter(corsConfig, errorHandler, pathPrefixes)

} 
开发者ID:dgilling,项目名称:play-regex-cors,代码行数:46,代码来源:RegExCORSFilter.scala

示例6: CORSFilter

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

import controllers.Default
import play.api.Logger
import play.api.mvc.{Filter, Result, RequestHeader}


case class CORSFilter() extends Filter{
  import scala.concurrent._
  import ExecutionContext.Implicits.global
  lazy val allowedDomain = play.api.Play.current.configuration.getString("cors.allowed.domain")
  def isPreFlight(r: RequestHeader) =(
    r.method.toLowerCase.equals("options")
      &&
      r.headers.get("Access-Control-Request-Method").nonEmpty
    )

  def apply(f: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = {
    Logger.trace("[cors] filtering request to add cors")
    if (isPreFlight(request)) {
      Logger.trace("[cors] request is preflight")
      Logger.trace(s"[cors] default allowed domain is $allowedDomain")
      Future.successful(Default.Ok.withHeaders(
        "Access-Control-Allow-Origin" -> allowedDomain.orElse(request.headers.get("Origin")).getOrElse(""),
        "Access-Control-Allow-Methods" -> request.headers.get("Access-Control-Request-Method").getOrElse("*"),
        "Access-Control-Allow-Headers" -> request.headers.get("Access-Control-Request-Headers").getOrElse(""),
        "Access-Control-Allow-Credentials" -> "true"
      ))
    } else {
      Logger.trace("[cors] request is normal")
      Logger.trace(s"[cors] default allowed domain is $allowedDomain")
      f(request).map{_.withHeaders(
        "Access-Control-Allow-Origin" -> allowedDomain.orElse(request.headers.get("Origin")).getOrElse(""),
        "Access-Control-Allow-Methods" -> request.headers.get("Access-Control-Request-Method").getOrElse("*"),
        "Access-Control-Allow-Headers" -> request.headers.get("Access-Control-Request-Headers").getOrElse(""),
        "Access-Control-Allow-Credentials" -> "true"
      )}
    }
  }
} 
开发者ID:roclet,项目名称:hashworkapi,代码行数:41,代码来源:CORSFilter.scala

示例7: BasicAuthenticationFilter

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

import akka.stream.Materializer
import play.api.mvc.{Filter, RequestHeader, Result, Results}
import sun.misc.BASE64Decoder

import scala.concurrent.{ExecutionContext, Future}


class BasicAuthenticationFilter(val username: String, val password: String)
                               (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {

  private object Constants {
    lazy val AuthorizationHeaderName = "authorization"
    lazy val BasicAuthenticationIdentifier = "Basic "
  }

  private lazy val unauthorizedResult = Future.successful {
    Results.Unauthorized.withHeaders(("WWW-Authenticate", """Basic realm="BasicAuthentication""""))
  }

  override def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    requestHeader.headers.get(Constants.AuthorizationHeaderName) match {
      case Some(authorizationBody) =>
        if (authorizationBody.startsWith(Constants.BasicAuthenticationIdentifier)) {
          val basicAuthenticationBody = authorizationBody.replace(Constants.BasicAuthenticationIdentifier, "")
          val decodedPayload = decodeBase64(basicAuthenticationBody)

          if (validateUsernamePassword(decodedPayload)) {
            nextFilter(requestHeader)
          } else {
            unauthorizedResult
          }
        } else {
          unauthorizedResult
        }
      case None => unauthorizedResult
    }
  }

  private def decodeBase64(string: String): String = {
    val decodedByteArray = new BASE64Decoder().decodeBuffer(string)
    new String(decodedByteArray, "UTF-8")
  }

  private def validateUsernamePassword(payload: String): Boolean = {
    val usernamePassword = payload.split(":")

    usernamePassword.length == 2 &&
      usernamePassword(0) == username &&
      usernamePassword(1) == password
  }

} 
开发者ID:janjaali,项目名称:playBasicAuthenticator,代码行数:55,代码来源:BasicAuthenticationFilter.scala

示例8: PjaxFilter

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

import javax.inject.Inject

import akka.stream.Materializer
import akka.util.ByteString
import com.thatscalaguy.utils.HTML
import play.api.http.HttpEntity
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}


class PjaxFilter @Inject()(materializer: Materializer)(implicit executionContext: ExecutionContext) extends Filter {
  private[this] val CONTAINER_KEY = "X-PJAX-Container"
  private[this] val PJAX_KEY = "X-PJAX"

  override implicit def mat: Materializer = materializer

  override def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    rh.headers.get(PJAX_KEY) match {
      case Some("true") if rh.headers.keys.contains(CONTAINER_KEY) =>
        f(rh) flatMap { result =>
          stripBody(result.body, rh.headers.get(CONTAINER_KEY).get.replace("#", "")) map { body =>
            result.copy(body = body)
          }
        }
      case _ => f(rh)
    }
  }

  private[this] def stripBody(body: HttpEntity, container: String): Future[HttpEntity] = {
    body.consumeData map { content =>
      val root = HTML.loadString(content.decodeString("UTF-8"))

      val stripedBody = (root \\ "_" filter (_ \@ "id" == container)).toString

      val newContent = if(stripedBody.isEmpty) content.decodeString("UTF-8") else stripedBody

      HttpEntity.Strict(ByteString(newContent), body.contentType)
    }
  }
} 
开发者ID:ThatScalaGuy,项目名称:play-pjax,代码行数:44,代码来源:PjaxFilter.scala

示例9: AppApplicationLoader

//设置package包名称以及导入依赖的类
import controllers.{Application, Assets}
import play.api.ApplicationLoader.Context
import play.api._
import play.api.routing.Router
import router.Routes
import com.softwaremill.macwire._
import play.api.libs.ws.ahc.AhcWSComponents
import services.SunService
import services.WeatherService
import scala.concurrent.Future
import akka.actor.Props
import actors.StatsActor
import actors.StatsActor.Ping
import play.api.mvc.Filter
import filters.StatsFilter

class AppApplicationLoader extends ApplicationLoader {

  def load(context: Context) = {
    LoggerConfigurator(context.environment.classLoader).foreach {
      configurator => configurator.configure(context.environment)
    }
    (new BuiltInComponentsFromContext(context) with AppComponents).application
  }
}

trait AppComponents extends BuiltInComponents with AhcWSComponents {
  lazy val assets: Assets = wire[Assets]
  lazy val prefix: String = "/"
  lazy val router: Router = wire[Routes]
  lazy val sunService = wire[SunService]
  lazy val weatherService = wire[WeatherService]
  lazy val applicationController = wire[Application]

  lazy val statsFilter: Filter = wire[StatsFilter]
  override lazy val httpFilters = Seq(statsFilter)


  val onStart = {
    Logger.info("The app is about to start")
    statsActor ! Ping
  }

  applicationLifecycle.addStopHook {
    () => Logger.info("The app is about to stop")
    Future.successful(Unit)
  }

  lazy val statsActor = actorSystem.actorOf(
    Props(wire[StatsActor]), StatsActor.name
  )
} 
开发者ID:bytehala,项目名称:scala-web-project,代码行数:53,代码来源:AppApplicationLoader.scala

示例10: HttpsRedirectFilter

//设置package包名称以及导入依赖的类
package com.themillhousegroup.play2letsencrypt

import javax.inject.Inject

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

import scala.concurrent.{ ExecutionContext, Future }

class HttpsRedirectFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
  def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    //play uses lower case headers.
    requestHeader.headers.get("x-forwarded-proto") match {
      case Some(header) => {
        if ("https" == header) {
          nextFilter(requestHeader).map { result =>
            result.withHeaders(("Strict-Transport-Security", "max-age=31536000"))
          }
        } else {
          Future.successful(Results.Redirect("https://" + requestHeader.host + requestHeader.uri, 301))
        }
      }
      case None => nextFilter(requestHeader)
    }
  }
} 
开发者ID:themillhousegroup,项目名称:play2-lets-encrypt,代码行数:27,代码来源:HttpsRedirectFilter.scala

示例11: SecurityFilter

//设置package包名称以及导入依赖的类
package org.zalando.zhewbacca

import javax.inject.Inject

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

import scala.concurrent.{ExecutionContext, Future}


class SecurityFilter @Inject() (
    rulesRepository: SecurityRulesRepository,
    implicit val mat: Materializer,
    implicit val ec: ExecutionContext
) extends Filter {

  override def apply(nextFilter: (RequestHeader) => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    rulesRepository.get(requestHeader).getOrElse {
      Logger.debug(s"No security rules found for ${requestHeader.method} ${requestHeader.uri}. Access denied.")
      new DenyAllRule
    }.execute(nextFilter, requestHeader)
  }

} 
开发者ID:zalando-incubator,项目名称:play-zhewbacca,代码行数:26,代码来源:SecurityFilter.scala

示例12: RequestCalculatorFilter

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

import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject

import akka.stream.Materializer
import play.api.Logger
import play.api.mvc.{Filter, RequestHeader, Result}
import play.api.libs.concurrent.Execution.Implicits._

import scala.concurrent.Future

class RequestCalculatorFilter @Inject()(implicit val mat: Materializer) extends Filter {

  private val counter = new AtomicLong(0)

  override def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    val value = counter.incrementAndGet()
    f(rh).map { result =>
      Logger.info("Request #" + value)
      result
    }
  }
} 
开发者ID:mielientiev,项目名称:play_intro_template.g8,代码行数:25,代码来源:RequestCalculatorFilter.scala

示例13: MetricsFilter

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

import javax.inject.Inject

import akka.stream.Materializer
import com.codahale.metrics.MetricRegistry
import play.api.mvc.{Filter, RequestHeader, Result}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success

class MetricsFilter @Inject()(metricRegistry: MetricRegistry)(
    implicit ec: ExecutionContext,
    override implicit val mat: Materializer
) extends Filter {
  private val successTimer = metricRegistry.timer("play.requests.success")
  private val clientErrorMeter =
    metricRegistry.meter("play.requests.clientError")
  private val serverErrorMeter =
    metricRegistry.meter("play.requests.serverError")

  override def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    val timeCtx      = successTimer.time()
    val futureResult = f(rh)

    futureResult.onComplete {
      case Success(result) if result.header.status < 400 =>
        timeCtx.stop()
      case Success(result) if result.header.status < 500 =>
        clientErrorMeter.mark()
      case _ =>
        serverErrorMeter.mark()
    }
    futureResult
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:37,代码来源:MetricsFilter.scala

示例14: XResponseTimeHeader

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

import javax.inject.Inject

import akka.stream.Materializer
import controllers.BuildInfo
import play.api.http.DefaultHttpFilters
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{ Filter, RequestHeader, Result }
import play.filters.gzip.GzipFilter

import scala.concurrent.Future

class XResponseTimeHeader @Inject() (implicit val mat: Materializer) extends Filter {
  def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
    val startTime = System.currentTimeMillis

    nextFilter(requestHeader).map { result =>
      val endTime = System.currentTimeMillis
      val responseTime = endTime - startTime
      val env = sys.props.get("environment").getOrElse("default")

      if (env == "local") {
        result.withHeaders(
          "X-Response-Time" -> responseTime.toString,
          "Server" -> (BuildInfo.name + "/" + BuildInfo.version),
          "Access-Control-Allow-Origin" -> "*",
          "Access-Control-Allow-Methods" -> "OPTIONS, GET, POST, PUT, DELETE, HEAD",
          "Access-Control-Allow-Headers" -> "Accept, Content-Type, Origin, X-Json, X-Prototype-Version, X-Requested-With",
          "Access-Control-Allow-Credentials" -> "true"
        )
      } else {
        result.withHeaders(
          "X-Response-Time" -> responseTime.toString,
          "Server" -> (BuildInfo.name + "/" + BuildInfo.version)
        )
      }
    }
  }
}

class Filters @Inject() (gzipFilter: GzipFilter, responseTimeHeader: XResponseTimeHeader)
  extends DefaultHttpFilters(gzipFilter, responseTimeHeader) 
开发者ID:ONSdigital,项目名称:sbr-pipeline-test,代码行数:44,代码来源:Filters.scala

示例15: CommonRequestHeaderFilter

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

import akka.stream.Materializer
import com.google.inject.Inject
import com.yper.common.CommonHeaderRequest
import play.api.Logger
import play.api.mvc.{Result, RequestHeader, Filter}
import play.api.routing.Router.Tags

import scala.concurrent.{Future, ExecutionContext}


class CommonRequestHeaderFilter @Inject() (implicit override val mat: Materializer,
                                            exec: ExecutionContext) extends Filter{

  override def apply(nextFilter: (RequestHeader) => Future[Result])
                    (requestHeader: RequestHeader): Future[Result] = {

    val commonRequestHeader = CommonHeaderRequest(
      requestHeader.headers.get("").getOrElse("default"),
      requestHeader.headers.get("").getOrElse("default"),
      CommonHeaderRequest.getCurrentTimeStamp,
      requestHeader.remoteAddress,
      requestHeader.headers.get("user-agent").getOrElse("default")
    )

    val startTime = System.currentTimeMillis

    nextFilter(requestHeader).map { result =>
      val action = requestHeader.tags(Tags.RouteController) +
        "." + requestHeader.tags(Tags.RouteActionMethod)
      val endTime = System.currentTimeMillis
      val requestTime = endTime - startTime

      Logger.info(s"Request Came From: ${commonRequestHeader.ipAddress} !")
      Logger.info(s"${action} took ${requestTime}ms and returned ${result.header.status}")

      result.withHeaders(
        "Request-Time" -> requestTime.toString
      )
    }
  }
} 
开发者ID:vi-kas,项目名称:yper,代码行数:44,代码来源:CommonRequestHeaderFilter.scala


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