本文整理汇总了Scala中com.twitter.finagle.SimpleFilter类的典型用法代码示例。如果您正苦于以下问题:Scala SimpleFilter类的具体用法?Scala SimpleFilter怎么用?Scala SimpleFilter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SimpleFilter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RequestLoggingFilter
//设置package包名称以及导入依赖的类
package app.filter
import com.twitter.finagle.filter.LogFormatter
import com.twitter.finagle.http.Status.InternalServerError
import com.twitter.finagle.http.filter.CommonLogFormatter
import com.twitter.finagle.http.{ Request, Response }
import com.twitter.finagle.{ Service, SimpleFilter }
import com.twitter.logging.Logger
import com.twitter.util._
abstract class RequestLoggingFilter[REQ <: Request](val formatter: LogFormatter[REQ, Response])
extends SimpleFilter[REQ, Response] {
private val log = Logger.get(getClass)
final def apply(request: REQ, service: Service[REQ, Response]): Future[Response] = {
//log.info(s">>> RAW REQUEST: '${request.getContentString()}'")
val elapsed = Stopwatch.start()
val future = service(request)
future.respond {
case Return(response) => logSuccess(elapsed(), request, response)
case Throw(error) => logException(elapsed(), request, error)
}
future
}
final def logSuccess(replyTime: Duration, request: REQ, response: Response): Unit = {
val line = formatter.format(request, response, replyTime)
log.info(line)
}
final def logException(duration: Duration, request: REQ, error: Throwable): Unit = {
val response = Response(request.version, InternalServerError)
val line = formatter.format(request, response, duration)
log.info(line)
}
}
object RequestLoggingFilter extends RequestLoggingFilter[Request](new CommonLogFormatter)
示例2: HandleRefusedByRateLimiterFilter
//设置package包名称以及导入依赖的类
package com.lookout.ratelimitingfilter
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Failure, Service, SimpleFilter, RefusedByRateLimiter}
import com.twitter.util.Future
import com.twitter.logging.Logger
case class HandleRefusedByRateLimiterFilter() extends SimpleFilter[Request, Response] {
val LOG = Logger.get(getClass)
def apply(request: Request, service: Service[Request, Response]): Future[Response] = Future {
service(request) handle {
case _: RefusedByRateLimiter => {
val rateLimitedMessage = s"Request is rate limited: ${request.encodeString()}"
LOG.info(rateLimitedMessage)
RefusedByRateLimiterError(rateLimitedMessage).toResponse
}
}
}.flatMap(identity _)
}
示例3: QueryCacheFilter
//设置package包名称以及导入依赖的类
package net.gutefrage.filter
import com.redis._
import com.redis.serialization.Parse.Implicits._
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
import net.gutefrage.filter.ThriftByteArray._
class QueryCacheFilter(val methodsToCache: Option[Seq[String]] = None, redisClient: RedisClient) extends SimpleFilter[Array[Byte], Array[Byte]] {
def bytesToInt(bytes: Array[Byte]): Int = java.nio.ByteBuffer.wrap(bytes).getInt
def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = {
val (methodName, seqId) = request.binaryProtocolMethodNameSeqId
if (methodsToCache.isEmpty || methodsToCache.get.contains(methodName)) {
println(s"Incoming request with method: $methodName -> Try to serve it from cache.")
val redisKey = request.binaryProtocolChangeSeqId(Array[Byte](0, 0, 0, 0)).requestHashKey
redisClient.get[Array[Byte]](redisKey) match {
case Some(response) => {
println("Data in redis found, returning from cache")
Future.value(response)
}
case None => {
println("data not in cache yet")
service(request) map { result =>
redisClient.setex(redisKey, 15, result)
result
}
}
}
} else {
println(s"Incoming request with method: $methodName -> Don't serve it from cache.")
service(request)
}
}
}
示例4: WhichUserLogin
//设置package包名称以及导入依赖的类
package com.bob.reservefund.scala.Filter
import javax.inject.Inject
import com.twitter.finagle.filter.LogFormatter
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.inject.Logging
import com.twitter.util.{Stopwatch, Future}
case class WhichUserLogin(id: Long)
object WhichUserLoginContext {
private val UserField = Request.Schema.newField[WhichUserLogin]()
class RequestAopFilter[R <: Request] @Inject()(
logFormatter: LogFormatter[R, Response])
extends SimpleFilter[R, Response] with Logging {
override def apply(request: R, service: Service[R, Response]): Future[Response] = {
if (!isInfoEnabled) {
service(request)
}
else {
val elapsed = Stopwatch.start()
service(request) onSuccess { response =>
info(response.contentString)
} onFailure { e =>
// should never get here since this filter is meant to be after the exception barrier
info(logFormatter.formatException(request, e, elapsed()))
}
}
}
}
示例5: LoggingFilter
//设置package包名称以及导入依赖的类
package io.peregrine
import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.logging.Logger
import com.twitter.util._
import com.twitter.conversions.time._
class LoggingFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with LoggingFilterHelper {
def apply(request: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = {
applyLogging(request, req => service(req))
}
}
trait LoggingFilterHelper extends LoggerColors {
private val logger: Logger = PeregrineLogger.logger()
private[peregrine] def applyLogging(request: FinagleRequest,
func: FinagleRequest => Future[FinagleResponse]): Future[FinagleResponse] = {
val elapsed = Stopwatch.start()
func(request) map { response =>
val duration = elapsed().inMicroseconds/1000.0
val mColor = methodColor(response.statusCode)
logger.info("[%s%s] %s%s %s\"%s\" %s%d %sin %s%.3fms%s",
ANSI_RESET, request.remoteHost,
ANSI_PURPLE, request.method,
ANSI_BLUE, request.uri,
mColor, response.statusCode,
ANSI_RESET,
ANSI_GREEN, duration,
ANSI_RESET
)
response
}
}
private[this] def methodColor(statusCode: Int) = statusCode match {
case code if code >= 200 && code < 300 => ANSI_GREEN
case code if code >= 400 && code < 500 => ANSI_YELLOW
case code if code >= 500 && code < 600 => ANSI_RED
case _ => ANSI_RESET
}
}
示例6: AssetsFilter
//设置package包名称以及导入依赖的类
package io.peregrine
import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util._
class AssetsFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with LoggingFilterHelper {
val logger = PeregrineLogger.logger()
def apply(req: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = {
if (req.path.startsWith("/__peregrine__/")) {
return if (config.debugAssets()){
applyLogging(req, request => Future(render.internal(req.path.replace("/__peregrine__", "__peregrine__"), 200).build))
} else {
Future(render.internal(req.path.replace("/__peregrine__", "__peregrine__"), 200).build)
}
}
if (req.path.startsWith(config.assetsPathPrefix())) {
if (config.debugAssets()) {
applyLogging(req, request => applyAssets(request))
} else {
applyAssets(req)
}
} else {
service(req)
}
}
private[this] def applyAssets(req: FinagleRequest) = {
val path = req.path.replace(config.assetsPathPrefix(), "")
Try(render.static(path).build) match {
case Return(resp) => Future(resp)
case Throw(t) => Future(render.notFound.build)
}
}
protected def render = new ResponseBuilder()
}
示例7: YaasHeadersTenantConsistentWithRouteFilter
//设置package包名称以及导入依赖的类
package me.kamkor.yaas.http.filters
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
import me.kamkor.yaas.http.exceptions.ValidationException
import me.kamkor.yaas.http.filters.YaasHeadersContext._
class YaasHeadersTenantConsistentWithRouteFilter(routeParamName: String) extends SimpleFilter[Request, Response] {
def this() = this("tenant")
override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
checkIfHeaderTenantConsistentWithRoute(request)
service(request)
}
private def checkIfHeaderTenantConsistentWithRoute(request: Request): Unit =
Option(request.getParam(routeParamName)) foreach { tenantRouteParam =>
if (request.yaasHeaders.hybrisTenant != tenantRouteParam) {
throw new ValidationException(s"'hybris-tenant' header must match route param '$routeParamName'")
}
}
}
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:26,代码来源:YaasHeadersTenantConsistentWithRouteFilter.scala
示例8: YaasHeaders
//设置package包名称以及导入依赖的类
package me.kamkor.yaas.http.filters
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
object YaasHeaders {
val HybrisTenant = "hybris-tenant"
}
case class YaasHeaders(hybrisTenant: String)
class YaasHeadersFilter extends SimpleFilter[Request, Response] {
override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
YaasHeadersContext.setYaasHeaders(request)
service(request)
}
}
// create a context, see https://twitter.github.io/finatra/user-guide/build-new-http-server/filter.html
object YaasHeadersContext {
private val YaasHeadersField = Request.Schema.newField[YaasHeaders]
implicit class YaasAwareContextSyntax(val request: Request) extends AnyVal {
def yaasHeaders: YaasHeaders = request.ctx(YaasHeadersField)
}
private[filters] def setYaasHeaders(request: Request): Unit = {
val hybrisTenant = request.headerMap(YaasHeaders.HybrisTenant)
val yaasAware = YaasHeaders(hybrisTenant)
request.ctx.update(YaasHeadersField, yaasAware)
}
}
示例9: UserFilter
//设置package包名称以及导入依赖的类
package com.example
import com.example.db.DB
import com.google.inject.Inject
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.{Filter, Service, SimpleFilter}
import com.twitter.util.Future
class UserFilter @Inject() extends SimpleFilter[Request, Response] {
override def apply(request: Request, service: Service[Request, Response]): Future[Response] = {
val token = request.cookies.get("auth_token")
DB.isValidToken(token.map(x => x.value).getOrElse("")) flatMap {
case true => service(request)
case false => redirectToLoginPage
}
}
def redirectToLoginPage = Future {
val response = Response(Status.TemporaryRedirect)
response.location = "/loginform"
response
}
}
示例10: ThriftServer
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.util.{Await, Future}
object ThriftServer {
def main(args: Array[String]) {
val filter = new SimpleFilter[Hello.Hi.Args, Hello.Hi.Result] {
override def apply(request: Args, service: Service[Args, Result]): Future[Result] = {
println("hahaha")
service(request)
}
}
val hiService = new Service[Hello.Hi.Args, Hello.Hi.Result] {
override def apply(request: Hello.Hi.Args): Future[Hello.Hi.Result] = {
Future(Hello.Hi.Result(Some("hi!")))
}
}
val helloService = new Service[Hello.Hello.Args, Hello.Hello.Result] {
override def apply(request: Hello.Hello.Args): Future[Hello.Hello.Result] = {
Future(Hello.Hello.Result(Some("hello!")))
}
}
val serviceImpl = Hello.ServiceIface(hi = filter andThen hiService, hello = helloService)
val server = Thrift.serveIface("localhost:8081", Hello.MethodIfaceBuilder.newMethodIface(serviceImpl))
Await.ready(server)
}
}
示例11: ThriftClient
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.thrift.{ClientId, ThriftClientRequest}
import com.twitter.util.{Await, Future}
object ThriftClient {
def main(args: Array[String]) {
val client = Thrift.client
.withClientId(ClientId("CLIENT ID HARD TO MISS"))
.filtered(new SimpleFilter[ThriftClientRequest, Array[Byte]] {
override def apply(request: ThriftClientRequest, service: Service[ThriftClientRequest, Array[Byte]]): Future[Array[Byte]] = {
println("Filtered")
service(request)
}
})
.newIface[Hello.FutureIface]("localhost:8081", "SPECIAL LABEL HARD TO MISS")
println(Await.result(client.hi()))
}
}
示例12: ThriftMuxGlobalServer
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.{Service, SimpleFilter, Thrift, ThriftMux}
import com.twitter.util.{Await, Future}
object ThriftMuxGlobalServer {
def main(args: Array[String]) {
val iface = new Hello.FutureIface {
def hi() = {
println("received request")
println(s"Client id: ${ClientId.current}")
Future("hi there")
}
override def hello(): Future[String] = {
Future("hello there")
}
}
val filter = new SimpleFilter[Array[Byte], Array[Byte]] {
override def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = {
println("filtered")
service(request)
}
}
val service = new Hello.FinagledService(iface, Thrift.protocolFactory)
val server = ThriftMux.serve("localhost:8081", filter andThen service)
Await.ready(server)
}
}
示例13: ThriftGlobalFilterServer
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.thrift.ClientId
import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.util.{Await, Future}
object ThriftGlobalFilterServer {
def main(args: Array[String]) {
val iface = new Hello.FutureIface {
def hi() = {
println("received request")
println(s"Client id: ${ClientId.current}")
Future("hi there")
}
override def hello(): Future[String] = {
Future("hello there")
}
}
val filter = new SimpleFilter[Array[Byte], Array[Byte]] {
override def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = {
println("filtered")
service(request)
}
}
val service = new Hello.FinagledService(iface, Thrift.protocolFactory)
val server = Thrift.serve("localhost:8081", filter andThen service)
Await.ready(server)
}
}
示例14: ThriftMuxServer
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.{Service, SimpleFilter, Thrift, ThriftMux}
import com.twitter.util.{Await, Future}
object ThriftMuxServer {
def main(args: Array[String]) {
val filter = new SimpleFilter[Hello.Hi.Args, Hello.Hi.Result] {
override def apply(request: Args, service: Service[Args, Result]): Future[Result] = {
println("hahaha")
service(request)
}
}
val hiService = new Service[Hello.Hi.Args, Hello.Hi.Result] {
override def apply(request: Hello.Hi.Args): Future[Hello.Hi.Result] = {
Future(Hello.Hi.Result(Some("hi!")))
}
}
val helloService = new Service[Hello.Hello.Args, Hello.Hello.Result] {
override def apply(request: Hello.Hello.Args): Future[Hello.Hello.Result] = {
Future(Hello.Hello.Result(Some("hello!")))
}
}
val serviceImpl = Hello.ServiceIface(hi = filter andThen hiService, hello = helloService)
val server = ThriftMux.serveIface("localhost:8081", Hello.MethodIfaceBuilder.newMethodIface(serviceImpl))
Await.ready(server)
}
}
示例15: HawkAuthenticateRequestFilter
//设置package包名称以及导入依赖的类
package com.redbubble.hawk
import cats.syntax.either._
import com.redbubble.hawk.HawkAuthenticate.authenticateRequest
import com.redbubble.hawk.RequestContextBuilder.buildContext
import com.redbubble.hawk.validate.Credentials
import com.redbubble.util.http.ResponseOps._
import com.redbubble.util.http.{ApiError, AuthenticationFailedError}
import com.redbubble.util.metrics.StatsReceiver
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
abstract class HawkAuthenticateRequestFilter(
credentials: Credentials,
whitelistedPaths: Seq[String],
statsReceiver: StatsReceiver)
extends SimpleFilter[Request, Response] {
private val stats = statsReceiver.scope("hawk_auth")
private val failureCounter = stats.counter("failure")
private val successCounter = stats.counter("success")
final override def apply(request: Request, continue: Service[Request, Response]): Future[Response] =
if (whitelistedPaths.exists(p => request.path.startsWith(p))) {
continue(request)
} else {
authenticate(request).fold(
e => {
failureCounter.incr()
unauthorised(e.getMessage)
},
_ => {
successCounter.incr()
continue(request)
}
)
}
private def authenticate(request: Request): Either[ApiError, RequestValid] = {
val valid = buildContext(request).map { context =>
authenticateRequest(credentials, context)
}.getOrElse(errorE(s"Missing authentication header '$AuthorisationHttpHeader'"))
valid.leftMap(e => AuthenticationFailedError("Request is not authorised", Some(e)))
}
}