本文整理汇总了Scala中com.twitter.finagle.http.Response类的典型用法代码示例。如果您正苦于以下问题:Scala Response类的具体用法?Scala Response怎么用?Scala Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: beforeAll
//设置package包名称以及导入依赖的类
package placeholder.base
import java.net.InetSocketAddress
import com.twitter.finagle
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import org.scalatest._
import placeholder.Main
import scala.concurrent.Await
import scala.concurrent.duration._
trait IntegrationTestBase extends FeatureSpec with GivenWhenThen with Matchers with BeforeAndAfterAll {
val server = Main
var serverAddress: InetSocketAddress = _
var client: Service[Request, Response] = _
var requestHost: String = _
server.main(Array())
override def beforeAll(): Unit = {
serverAddress = Await.result(server.getServerAddress, 10.seconds)
requestHost = s"localhost:${serverAddress.getPort.toString}"
client = finagle.Http.newService(requestHost)
}
def performRequest(request: Request): Future[Response] = {
request.host = requestHost
client(request)
}
}
示例2: 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)
示例3: 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
}
}
}
}
示例4: Foo2
//设置package包名称以及导入依赖的类
package com.bluedit
import com.twitter.finagle.http.{Response, Request}
import com.twitter.finagle.{Service, Http}
import com.twitter.util.Await
import io.finch._
import io.finch.circe._
import io.circe.generic.auto._
import shapeless.{CNil, :+:}
import io.circe._, io.circe.generic.auto._, io.circe.syntax._
case class Foo2( f: String )
case class Bar2( b: String )
case class Person2( firstname: String, lastname: String )
object HelloService4 extends App {
val foo2: Endpoint[Foo2] = get("foo" / string ) {
name: String => Ok( Foo2(name))
}
val bar2: Endpoint[Bar2] = get("bar" / string ) {
name: String => Ok( Bar2(name))
}
val person2: Endpoint[Person2] = get("person" / string ) {
name: String => Ok( Person2( name, "Welkenbach"))
}
val api: Service[Request, Response] = (foo2 :+: bar2 :+: person2).toService
Await.ready(Http.server.serve(":9001", api ))
}
示例5: 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 _)
}
示例6: 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
}
}
示例7: MockClient
//设置package包名称以及导入依赖的类
package featherbed
import java.net.URL
import com.twitter.finagle.{Filter, Http}
import com.twitter.finagle.http.{Request, Response}
import org.scalamock.matchers.Matcher
import org.scalamock.scalatest.MockFactory
package object fixture {
private[fixture] class MockClient (
baseUrl: URL,
filter: Filter[Request, Response, Request, Response]
) extends Client(baseUrl) {
override def clientTransform(c: Http.Client) = c.filtered(filter)
}
trait ClientTest { self: MockFactory =>
class TransportRequestMatcher(f: Request => Unit) extends Matcher[Any] {
override def canEqual(x: Any) = x match {
case x: Request => true
case _ => false
}
override def safeEquals(that: Any): Boolean = that match {
case x: Request => f(x); true
case _ => false
}
}
def request(f: Request => Unit): TransportRequestMatcher = new TransportRequestMatcher(f)
def mockClient(url: String, filter: Filter[Request, Response, Request, Response]): Client =
new MockClient(new URL(url), filter)
}
}
示例8: HttpTips
//设置package包名称以及导入依赖的类
package com.bob.scalatour.twitters
import com.twitter.finagle.transport.Transport
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Method, Response, Request}
import com.twitter.finagle.loadbalancer.{Balancers, LoadBalancerFactory}
import com.twitter.util.{Await => twitterAwait, Monitor}
object HttpTips {
def main(args: Array[String]) {
val balancer: LoadBalancerFactory = Balancers.heap()
val monitor: Monitor = new Monitor {
override def handle(exc: Throwable): Boolean = {
// do sth with the exception
true
}
}
val client: Service[Request, Response] = Http.client
.withMonitor(monitor)
.withLoadBalancer(balancer)
// It’s important to disable Fail Fast when only have one host in the replica set
// because Finagle doesn’t have any other path to choose.
.withSessionQualifier.noFailFast
.configured(Transport.Options(noDelay = false, reuseAddr = false))
.newService("172.16.40.68:8090,172.16.40.69:8090", "riskservice")
val request = Request(Method.Get, "/calculator/users/together?userId=1234&date=2015-12-12&bbb=bbb")
// here we should set the host header value even it is empty,otherwise it will nothing can obtain
request.headerMap.add("host", "")
(1 to 20).map {
z => {
println(s"now is the ${z} request to send")
val response = client(request)
twitterAwait.ready(response.map(x => println(x.contentString)))
}
}
val url = Request.queryString("/calculator/users/together", Map("userId" -> "314", "date" -> "2015", "bbb" -> "bbb"))
println(url) // url value will be: /calculator/users/together?userId=314&date=2015&bbb=bbb
println("http invoke done")
}
}
示例9: MExceptionMapper
//设置package包名称以及导入依赖的类
package com.bob.reservefund.scala
import com.google.inject.Inject
import com.twitter.finagle.http.{Response, Request}
import com.twitter.finatra.http.exceptions.HttpException
import com.twitter.finatra.http.exceptions.ExceptionMapper
import com.twitter.finatra.http.response.ResponseBuilder
class MExceptionMapper @Inject()(response: ResponseBuilder) extends ExceptionMapper[Exception] {
override def toResponse(request: Request, throwable: Exception): Response = {
throwable match {
case e: HttpException =>
val builder = response.status(e.statusCode)
builder.json(
s"""
|{
| "msg": ${e.getMessage()}
|}
""".stripMargin)
case _: Exception =>
response.status(500).json( """{
| "name": "Bob",
| "age": 19
| }""")
}
}
}
示例10: 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()))
}
}
}
}
示例11: ServiceMain
//设置package包名称以及导入依赖的类
package io.github.mijicd.prezi
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter
import com.twitter.finatra.logging.modules.Slf4jBridgeModule
import io.github.mijicd.prezi.api.Presentations
import io.github.mijicd.prezi.modules.{DataSource, PreziJson}
object ServiceMain extends Service
class Service extends HttpServer {
override protected def modules = Seq(Slf4jBridgeModule, DataSource)
override protected def jacksonModule = PreziJson
override protected def defaultFinatraHttpPort = ":8180"
override protected def disableAdminHttpServer = true
override protected def configureHttp(router: HttpRouter): Unit = router.
filter[LoggingMDCFilter[Request, Response]].
filter[CommonFilters].
add[Presentations]
}
示例12: WebServer
//设置package包名称以及导入依赖的类
package com.gilesc
package mynab
package finch
import com.gilesc.mynab.finch.endpoint.AccountEndpoints
import com.gilesc.mynab.finch.endpoint.AccountGroupEndpoints
object WebServer {
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Http, Service}
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch._
import io.finch.circe._
// Endpoints
val api: Service[Request, Response] = (
AccountGroupEndpoints.postGroup :+:
AccountGroupEndpoints.getGroup :+:
AccountEndpoints.getAccount :+:
AccountEndpoints.postAccount
).handle({
case e => NotFound(new Exception(e.toString))
}).toServiceAs[Application.Json]
// Service Stuff
def shutdown(): Unit = {}
def main(args: Array[String]): Unit = {
val server = Http.server.serve(":8080", api)
Await.ready(server)
shutdown()
}
}
示例13: ExampleServerMain
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.http.{Response, Request}
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter, TraceIdMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter
object ExampleServerMain extends ExampleServer
class ExampleServer extends HttpServer {
override def defaultFinatraHttpPort = ":9999"
override def configureHttp(router: HttpRouter) {
router
.filter[LoggingMDCFilter[Request, Response]]
.filter[TraceIdMDCFilter[Request, Response]]
.filter[CommonFilters]
.add[PingController]
}
}
示例14: ServerMain
//设置package包名称以及导入依赖的类
package $package$
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter, TraceIdMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter
import $package$.controllers.MainController
object ServerMain extends Server
class Server extends HttpServer {
override val name = "$package$ $name;format="Camel"$"
override def configureHttp(router: HttpRouter) {
router
.filter[CommonFilters]
.filter[LoggingMDCFilter[Request, Response]]
.filter[TraceIdMDCFilter[Request, Response]]
.add[MainController]
}
}
示例15: FinatraServerMain
//设置package包名称以及导入依赖的类
package com.github.ikhoon
import com.github.ikhoon.app.v1.fake.FakeController
import com.github.ikhoon.app.v1.ping.PingController
import com.github.ikhoon.app.v1.user.UserController
import com.github.ikhoon.modules._
import com.jakehschwartz.finatra.swagger.DocsController
import com.twitter.finagle.http.{ Request, Response }
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{ CommonFilters, LoggingMDCFilter, TraceIdMDCFilter }
import com.twitter.finatra.http.routing.HttpRouter
object FinatraServerMain extends FinatraServer
class FinatraServer extends HttpServer {
override def modules = Seq(
TypesafeConfigModule, QuillDatabaseModule, SlickDatabaseModule, SwaggerModule
) ++ HttpClientModules.modules
override def jacksonModule = CustomJacksonModule
override def defaultFinatraHttpPort = ":9999"
override def configureHttp(router: HttpRouter) {
router
.filter[LoggingMDCFilter[Request, Response]]
.filter[TraceIdMDCFilter[Request, Response]]
.filter[CommonFilters]
.add[DocsController]
.add[PingController]
.add[UserController]
.add[FakeController]
}
}