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

Scala Status类代码示例

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

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



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

示例1: apiErrorHandler

//设置package包名称以及导入依赖的类
package app.v1.handler

import com.twitter.finagle.http.{ Request, Response, Status, Version }
import com.twitter.logging.Logger
import com.twitter.util.Future
import io.finch.Error.{ NotParsed, NotPresent, NotValid }
import io.finch._

trait ErrorHandler {

  private val log = Logger.get(getClass)

  def apiErrorHandler: PartialFunction[Throwable, Output[Nothing]] = {
    case e: NotPresent => BadRequest(e)
    case e: NotParsed  => BadRequest(e)
    case e: NotValid   => BadRequest(e)
    case e: Exception  => InternalServerError(e)
  }

  def topLevelErrorHandler[REQUEST <: Request](request: REQUEST, encoder: Encode[Throwable]): PartialFunction[Throwable, Future[Response]] = {
    case t: Throwable => unhandledException(request, t, encoder)
  }

  private def unhandledException[REQUEST <: Request](request: REQUEST, t: Throwable, encoder: Encode[Throwable]): Future[Response] = {
    try {
      log.info(s"Unhandled exception on URI ${request.uri} with message $t")
      Future.value(Response(Version.Http11, Status.InternalServerError))
    } catch {
      case e: Throwable => {
        log.error(s"Unable to log unhandled exception: $e")
        throw e
      }
    }
  }
} 
开发者ID:PScopelliti,项目名称:ProjectTracker,代码行数:36,代码来源:ErrorHandler.scala


示例2: RefusedByRateLimiterErrorSpec

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

import com.twitter.finagle.http.{Request, Status}
import org.specs2.{Specification, ScalaCheck}
import io.circe.syntax._
import io.circe.jawn._
import com.lookout.ratelimitingfilter.models._

class RefusedByRateLimiterErrorSpec extends Specification with ScalaCheck with Arbitraries {
  def is = s2"""
    RefusedByRateLimiterError object
      it should not lose data on roundtrips to JSON $dataIntegrity
      it should contain a `message` field           $messageField
      it should create a response with 429 status   $statusCode
  """

  def fields(error: RefusedByRateLimiterError): Seq[String] =
    error.asJson.asObject.toList.flatMap(_.fields)

  def dataIntegrity = prop {
    (error: RefusedByRateLimiterError) => {
      (decode[RefusedByRateLimiterError](error.asJson.noSpaces)) must_== Right(error)
    }
  }

  def messageField = prop {
    (error: RefusedByRateLimiterError) => {
      fields(error) must contain("message")
    }
  }

  def statusCode = prop {
    (error: RefusedByRateLimiterError) => {
      error.toResponse.status must_== Status.TooManyRequests
    }
  }
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:38,代码来源:RefusedByRateLimiterErrorSpec.scala


示例3: RedirectionSpec

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

import com.kurz.services.RedisConnectionPool
import com.twitter.finagle.http.Status
import io.finch.Input
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}

class RedirectionSpec extends FunSpec with Matchers with BeforeAndAfter {
  import com.kurz.Server.redirection

  before {
    RedisConnectionPool.instance.getResource().del("mb")
    RedisConnectionPool.instance.getResource().set("mb", "http://marceloboeira.com")
  }

  describe ("redirection") {
    describe("when the slug exists") {
      it("returns with the temporary redirection status") {
        redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.TemporaryRedirect)
      }

      it("returns with the proper header for Location") {
        redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.headers) shouldBe Some(Map("Location" -> "http://marceloboeira.com"))
      }
    }

    describe("when the slug does not exist") {
      it("returns with the not found status") {
        redirection(Input.get("/invalid")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.NotFound)
      }
    }
  }
} 
开发者ID:marceloboeira,项目名称:kurz,代码行数:34,代码来源:RedirectionSpec.scala


示例4: DefaultNoteApi

//设置package包名称以及导入依赖的类
package app.v1.api

import java.util.UUID

import app.v1.model.Note
import app.v1.service.ServiceComponent
import com.twitter.finagle.http.Status
import com.twitter.logging.Logger
import io.circe.generic.auto._
import io.finch.circe._
import io.finch.{ Endpoint, _ }

trait NoteApi {

  self: ServiceComponent =>

  private val basePath = "api" :: "v1" :: "notes"
  private val log = Logger.get(getClass)

  val noteApi: DefaultNoteApi = new DefaultNoteApi

  class DefaultNoteApi {

    def endpoints = (getNotes :+: getNoteById :+: createNote :+: deleteNote :+: patchNote)

    def getNotes: Endpoint[List[Note]] = get(basePath) {
      log.info("Calling getNotes endpoint... ")
      Ok(noteService.getNotes)
    }

    def getNoteById: Endpoint[Note] = get(basePath :: uuid) { uuid: UUID =>
      log.info("Calling getNoteById endpoint... ")
      Ok(noteService.getNoteById(uuid))
    }

    def createNote: Endpoint[Note] = post(basePath :: jsonBody[UUID => Note]) {
      (noteGen: UUID => Note) =>
        {
          log.info("Calling createNote endpoint... ")
          Created(noteService.createNote(noteGen))
        }
    }

    def deleteNote: Endpoint[Unit] = delete(basePath :: uuid) { uuid: UUID =>
      log.info("Calling deleteNote endpoint... ")
      noteService.deleteNote(uuid)
      NoContent[Unit].withStatus(Status.Ok)
    }

    def patchNote: Endpoint[Note] = patch(basePath :: uuid :: jsonBody[Note]) { (uuid: UUID, note: Note) =>
      log.info("Calling patchNote endpoint... ")
      noteService.patchNote(uuid, note)
      Ok(note)
    }

  }

} 
开发者ID:PScopelliti,项目名称:ProjectTracker,代码行数:59,代码来源:NoteApi.scala


示例5: RefusedByRateLimiterError

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

import com.twitter.finagle.http.{Response, Status}
import com.twitter.finagle.RefusedByRateLimiter
import com.twitter.io.Buf
import com.twitter.logging.Logger
import io.circe.{Decoder, Encoder}
import io.circe.syntax._

final case class RefusedByRateLimiterError(
  message: String
) extends Exception(message) {
  def toResponse: Response = RefusedByRateLimiterError.toResponse(this)
}

object RefusedByRateLimiterError {
  val LOG = Logger.get(getClass)

  implicit val errorEncoder: Encoder[RefusedByRateLimiterError] =
    Encoder.forProduct1("message") { err => err.message }

  implicit val errorDecoder: Decoder[RefusedByRateLimiterError] =
    Decoder.forProduct1[String, RefusedByRateLimiterError]("message") {
      case (message: String) => RefusedByRateLimiterError(message)
    }

  def toResponse(error: RefusedByRateLimiterError): Response = {
    val response = Response(Status.TooManyRequests)
    val content = error.asJson.noSpaces
    LOG.info(content)
    response.content = Buf.Utf8(content)
    response.contentType = "application/json"
    response
  }
} 
开发者ID:lookout,项目名称:rate-limiting-strategy,代码行数:36,代码来源:RefusedByRateLimiterError.scala


示例6: ClientArtifactsTests

//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client

import java.nio.file.{Files, Paths}

import com.twitter.finagle.http.Status

class ClientArtifactsTests extends TestBase {

  "Client Artifacts" should {

    "upload an artifact without a path" in {
      val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
      whenReady( client.uploadArtifact(bytes, "marathon.jpg") ) { result =>
        result._1 shouldBe(Status.Created)
        result._2 shouldBe( Some( s"http://${server.host.get}:${server.port.get}/v2/artifacts/marathon.jpg" ) )
      }
    }

    "upload an artifact with a path" in {
      val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
      whenReady( client.uploadArtifact(bytes, "marathon.jpg", Some("this/is/a/path/marathon.jpg")) ) { result =>
        result._1 shouldBe(Status.Created)
        result._2 shouldBe( Some( s"http://${server.host.get}:${server.port.get}/v2/artifacts/this/is/a/path/marathon.jpg" ) )
      }
    }

    "get an uploaded artifact" in {
      whenReady( client.getArtifact("marathon.jpg") ) { data =>
        val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
        bytes shouldBe( data )
      }
      whenReady( client.getArtifact("this/is/a/path/marathon.jpg") ) { data =>
        val bytes = Files.readAllBytes(Paths.get(this.getClass.getClassLoader.getResource("marathon.jpg").toURI))
        bytes shouldBe( data )
      }
    }

    "delete an artifact" in {
      whenReady( client.deleteArtifact("this/is/a/path/marathon.jpg") ) { status =>
        status shouldBe( Status.Ok )
        whenReady( client.deleteArtifact("this/is/a/path/marathon.jpg").failed ) { ex =>
          ex shouldBe a[MarathonClientException]
          ex.asInstanceOf[MarathonClientException].status shouldBe (Status.NotFound)
        }
      }
    }

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:51,代码来源:ClientArtifactsTests.scala


示例7: MiscEndpointTests

//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client

import uk.co.appministry.scathon.models.v2.GetInfoResponse
import com.twitter.finagle.http.Status
import play.api.libs.json.JsValue

class MiscEndpointTests extends TestBase {

  "Misc Endpoints" should {

    "receive JsValue for metrics endpoint" in {
      whenReady( client.metrics() ) { value =>
        value shouldBe a[JsValue]
      }
    }

    "receive Ok for ping endpoint" in {
      whenReady( client.ping() ) { status =>
        status shouldBe( Status.Ok )
      }
    }

    "receive server info from getInfo endpoint" in {
      whenReady( client.getInfo() ) { response =>
        response shouldBe a[GetInfoResponse]
      }
    }

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:32,代码来源:MiscEndpointTests.scala


示例8: PluginsTests

//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client

import uk.co.appministry.scathon.testServer.plugins.TestPlugin
import com.twitter.finagle.http.{Method, Status}

class PluginsTests extends TestBase {

  "Plugins Tests" should {

    "retrieve a list of plugins" in {
      val testPlugin = new TestPlugin
      whenReady( client.getPlugins() ) { plugins =>
        plugins.length shouldBe(1)
        inside( plugins(0) ) {
          case plugin =>
            plugin.id shouldBe(testPlugin.info.id)
            plugin.implementation shouldBe(testPlugin.info.implementation)
        }
      }
    }

    "send a request and get a response from a plugin" in {
      whenReady( client.pluginExecuteRequest(Method.Get, "test-plugin", Some("/the/path/does/not/matter/here")) ) { response =>
        response.status shouldBe(Status.Ok)
        response.contentString shouldBe("GET")
      }
    }

    "receive an error for an unsupported method" in {
      whenReady(client.pluginExecuteRequest(Method.Head, "test-plugin", Some("/the/path/does/not/matter/here")).failed) { ex =>
        ex shouldBe a[NotAllowed]
        inside(ex.asInstanceOf[NotAllowed]) {
          case e =>
            e.status shouldBe(Status.MethodNotAllowed)
        }
      }
    }

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:42,代码来源:PluginsTests.scala


示例9: LeaderTests

//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client

import com.twitter.finagle.http.Status

class LeaderTests extends TestBase {

  "Leader Tests" should {

    "get leader info from the server" in {
      whenReady( client.getLeader() ) { data =>
        data should matchPattern { case Some(_) => }
      }
    }

    "receive Ok when removing a leader" in {
      whenReady( client.deleteLeader() ) { status =>
        status shouldBe(Status.Ok)
      }
    }

    "receive NotFound when removing a leader (leader not there)" in {
      whenReady( client.deleteLeader().failed ) { ex =>
        ex shouldBe a[NotFound]
      }
    }

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:30,代码来源:LeaderTests.scala


示例10: EventSubscriptionTests

//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client

import java.net.URI

import uk.co.appministry.scathon.models.v2.EventSubscriptionSubscribeEvent
import com.twitter.finagle.http.Status

class EventSubscriptionTests extends TestBase {

  "Event subscriptions operations" should {

    val callbackUri = "http://callback-uri.com/some-path"

    "create a subscription when requested" in {
      whenReady( client.createEventSubscription(new URI(callbackUri)) ) { event =>
        event shouldBe a[EventSubscriptionSubscribeEvent]
      }
    }

    "get a subscription list when requested" in {
      whenReady( client.getEventSubscriptions() ) { items =>
        items shouldBe( List(callbackUri) )
      }
    }

    "delete a subscription when requested" in {
      whenReady( client.deleteEventSubscription(new URI(callbackUri)) ) { status =>
        status shouldBe(Status.Ok)
        whenReady( client.getEventSubscriptions() ) { items =>
          items shouldBe( List.empty[String] )
        }
      }
    }

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:38,代码来源:EventSubscriptionTests.scala


示例11: CaseClassExceptionMapper

//设置package包名称以及导入依赖的类
package me.kamkor.yaas.http.exceptions.json

import javax.inject.Inject

import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finatra.http.exceptions.ExceptionMapper
import com.twitter.finatra.http.response.ResponseBuilder
import com.twitter.finatra.json.internal.caseclass.exceptions.CaseClassMappingException
import me.kamkor.yaas.http.responses.ErrorResponse

class CaseClassExceptionMapper @Inject()(
  response: ResponseBuilder
) extends ExceptionMapper[CaseClassMappingException] {

  override def toResponse(request: Request, e: CaseClassMappingException): Response = {
    // FIXME, do it properly
    val errorMessage = e.errors map (_.getMessage) mkString ("\n")

    val errorResponse =
      ErrorResponse(
        status = Status.BadRequest.code,
        message = errorMessage
      )

    response.badRequest.json(errorResponse)
  }


} 
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:30,代码来源:CaseClassExceptionMapper.scala


示例12: WishListsFeatureTest

//设置package包名称以及导入依赖的类
package me.kamkor.wishlists

import com.twitter.finagle.http.Status
import com.twitter.finatra.http.test.{EmbeddedHttpServer, HttpTest}
import com.twitter.inject.Mockito
import com.twitter.inject.server.FeatureTest

object WishListsFeatureTest {

  val TestTenant = "TestTenant"
  val Headers = Map("hybris-tenant" -> TestTenant)

}

class WishListsFeatureTest extends FeatureTest with Mockito with HttpTest {

  import WishListsFeatureTest._

  override val server = new EmbeddedHttpServer(new WishListsServer)

  "A WishLists endpoint" should {

    "GET wishlist" in {
      //mock document repository client
      //server.httpGet(path = s"/$TestTenant/wishlists/1", headers = Headers, andExpect = Status.Ok)
    }

    "GET NotFound" in {

    }

    "PUT wishlist" in {
      server.httpPut(
        path = s"/$TestTenant/wishlists/1",
        headers = Headers,
        putBody =
          """
            |{
            |  "owner":"kamil",
            |  "title":"food list",
            |  "description":"Food for the weekend"
            |}
          """.stripMargin,
        andExpect = Status.NoContent
      )
    }

    "DELETE wishlist" in {
      server.httpDelete(path = s"/$TestTenant/wishlists/1", headers = Headers, andExpect = Status.NoContent)
    }
  }


} 
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:55,代码来源:WishListsFeatureTest.scala


示例13: 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
  }
} 
开发者ID:Sergey778,项目名称:finatra_test,代码行数:27,代码来源:UserFilter.scala


示例14: RootApiSpec

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

import com.twitter.finagle.http.Status
import io.finch._
import org.scalatest.prop.Checkers
import org.scalatest.{FlatSpec, Matchers}

class RootApiSpec extends FlatSpec with Matchers with Checkers {

  behavior of "root endpoint"

  it should "return 'ok'" in {
    val input = Input.get("/")
    val res = RootCtrl.root(input)
    res.output.map(_.status) === Some(Status.Ok)
    res.value.isDefined === true
    res.value.get shouldBe "ok"
  }

} 
开发者ID:aluxian,项目名称:SusuCatBot,代码行数:21,代码来源:RootApiSpec.scala


示例15: HelloControllerFeatureTest

//设置package包名称以及导入依赖的类
import com.twitter.finagle.http.Status
import com.twitter.finatra.http.test.EmbeddedHttpServer
import com.twitter.inject.server.FeatureTest

class HelloControllerFeatureTest extends FeatureTest {
  override val server: EmbeddedHttpServer = new EmbeddedHttpServer(
    twitterServer = new FitmanServer)

  "Say Hello" in {
    server.httpGet(
      path = "/hello",
      andExpect = Status.Ok,
      withBody = "Fitman says hello"
    )
  }
} 
开发者ID:simoncyl,项目名称:Fitman,代码行数:17,代码来源:FeatureTest.scala


示例16: Api

//设置package包名称以及导入依赖的类
package com.slouc.finchdemo.http.api

import com.twitter.finagle.http.Status
import com.twitter.util.Future
import io.finch._
import io.circe.generic.auto._
import io.finch.circe._

object Api {

  val endpoint1: Endpoint[String] = get("books" :: string :: param("minPrice") :: paramOption("maxPrice")) {
    (s: String, minPrice: String, maxPrice: Option[String]) =>
      // do something and return Output
      Ok(s"Cool request bro! Here are the params: $s, $minPrice" + maxPrice.getOrElse(s" and $maxPrice", ""))
  }

  val endpoint2: Endpoint[String] = post("books" :: jsonBody[Book]) {
    (book: Book) =>
      // do something and return Output
      Ok(s"You posted a book with title: ${book.title} and author: ${book.author}")
  }

  val endpoint3: Endpoint[MyResponse] = post("books" :: "json" :: jsonBody[Book]) {
    (book: Book) =>
      // do something and return Output
      Ok(MyResponse(200, "This is a response!"))
  }.rescue {
    case (t: Throwable) => Future(Output.payload(MyResponse(400, "Not cool dude!"), Status.BadRequest))
  }

  val endpoint4: Endpoint[FancyResponse[FancyResponseBody]] = post("books" :: "fancy" :: jsonBody[Book]) {
    (book: Book) =>
      // do something and return Output
      Ok(FancyResponse(200, "This is one fancy response!", FancyResponseBody("response")))
  }

}

case class Book(title: String, author: String)

case class MyResponse(code: Int, msg: String)

case class FancyResponse[T: io.circe.Encoder](code: Int, msg: String, body: T)

case class FancyResponseBody(msg: String) 
开发者ID:slouc,项目名称:finch-demo,代码行数:46,代码来源:Api.scala


示例17: HttpStreamingClient

//设置package包名称以及导入依赖的类
package com.twitter.finagle.example.http

import com.twitter.concurrent.AsyncStream
import com.twitter.util.{Await, Base64StringEncoder => Base64}
import com.twitter.finagle.http.{Request, Method, Status}
import com.twitter.finagle.Http
import com.twitter.io.{Buf, Reader}


object HttpStreamingClient {
  def main(args: Array[String]): Unit = {
    val username = args(0)
    val password = args(1)
    val host = args(2)
    val path = args(3)

    val client = Http.client.withStreaming(enabled = true).newService(host)

    val request = Request(Method.Get, path)
    val userpass = username + ":" + password
    request.headerMap.add("Authorization", "Basic " + Base64.encode(userpass.getBytes("UTF-8")))
    request.headerMap.add("User-Agent", "Finagle 0.0")
    request.headerMap.add("Host", host)
    println(request)

    Await.result(client(request).flatMap {
      case response if response.status != Status.Ok =>
        println(response)
        client.close()

      case response =>
        var messageCount = 0 // Wait for 1000 messages then shut down.
        fromReader(response.reader).foreach {
          case Buf.Utf8(buf) if messageCount < 1000 =>
            messageCount += 1
            println(buf)
            println("--")

          case _ =>
            client.close()
        }
    })
  }

  def fromReader(reader: Reader): AsyncStream[Buf] =
    AsyncStream.fromFuture(reader.read(Int.MaxValue)).flatMap {
      case None => AsyncStream.empty
      case Some(a) => a +:: fromReader(reader)
    }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:51,代码来源:HttpStreamingClient.scala


示例18: ValidateRequestFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.filter

import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.util.Future



class ValidateRequestFilter[REQUEST <: Request]
  extends SimpleFilter[REQUEST, Response] {

  def apply(request: REQUEST, service: Service[REQUEST, Response]): Future[Response] = {
    if (request.uri != "/bad-http-request" && request.params.isValid) {
      service(request)
    } else {
      val response = request.response
      response.status = Status.BadRequest
      response.clearContent()
      Future.value(response)
    }
  }
}


object ValidateRequestFilter extends ValidateRequestFilter[Request] 
开发者ID:wenkeyang,项目名称:finagle,代码行数:26,代码来源:ValidateRequestFilter.scala


示例19: ExceptionFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.filter

import com.twitter.finagle.{CancelledRequestException, Service, SimpleFilter}
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.logging.Logger
import com.twitter.util.{Future, NonFatal}


class ExceptionFilter[REQUEST <: Request] extends SimpleFilter[REQUEST, Response] {
  import ExceptionFilter.ClientClosedRequestStatus

  private val log = Logger("finagle.http")

  def apply(request: REQUEST, service: Service[REQUEST, Response]): Future[Response] =
    {
      try {
        service(request)
      } catch {
        // apply() threw an exception - convert to Future
        case NonFatal(e) => Future.exception(e)
      }
    } rescue {
      case e: CancelledRequestException =>
        // This only happens when ChannelService cancels a reply.
        log.warning("cancelled request: uri:%s", request.uri)
        respond(request, ClientClosedRequestStatus)
      case e: Throwable =>
        try {
          log.warning(e, "exception: uri:%s exception:%s", request.uri, e)
          respond(request, Status.InternalServerError)
        } catch {
          // logging or internals are broken.  Write static string to console -
          // don't attempt to include request or exception.
          case e: Throwable =>
            Console.err.println("ExceptionFilter failed")
            throw e
        }
    }

  private def respond(request: REQUEST, responseStatus: Status): Future[Response] = {
    val response = request.response
    response.status = responseStatus
    response.clearContent()
    response.contentLength = 0
    Future.value(response)
  }
}


object ExceptionFilter extends ExceptionFilter[Request] {
  private[ExceptionFilter] val ClientClosedRequestStatus =
    Status.ClientClosedRequest
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:54,代码来源:ExceptionFilter.scala


示例20: MethodRequiredFilter

//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.filter

import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.finagle.http.{Method, Request, Response, Status}
import com.twitter.util.Future


class MethodRequiredFilter[REQUEST <: Request](
   val supportedMethods: Set[Method] = Set(Method.Get, Method.Head, Method.Post))
 extends SimpleFilter[REQUEST, Response] {

  private[this] val allowedMethods = supportedMethods.mkString(", ").toUpperCase

  def apply(request: REQUEST, service: Service[REQUEST, Response]): Future[Response] =
    if (!supportedMethods.contains(request.method)) {
      val response = request.response
      response.status = Status.MethodNotAllowed
      response.allow = allowedMethods
      Future.value(response)
    } else {
      service(request)
    }
}


object MethodRequiredFilter
  extends MethodRequiredFilter[Request](Set(Method.Get, Method.Head, Method.Post)) 
开发者ID:wenkeyang,项目名称:finagle,代码行数:28,代码来源:MethodRequiredFilter.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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