本文整理汇总了Scala中com.twitter.finagle.Service类的典型用法代码示例。如果您正苦于以下问题:Scala Service类的具体用法?Scala Service怎么用?Scala Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Service类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: 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 ))
}
开发者ID:getmetorajesh,项目名称:rj_reddit_slick_finch,代码行数:34,代码来源:test.scala
示例2: 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()))
}
}
}
}
开发者ID:bobxwang,项目名称:ReserveFundService,代码行数:37,代码来源:WhichUserLoginFilter.scala
示例3: 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()
}
}
开发者ID:CraigGiles,项目名称:mynab,代码行数:35,代码来源:WebServer.scala
示例4: FibonacciSequenceService
//设置package包名称以及导入依赖的类
package services
import algorithms.sequences.{FibonacciFinder, MatricesFibonacciFinder}
import com.twitter.finagle.Service
import com.twitter.finagle.httpx.{Request, Response}
import com.twitter.util.Future
import io.finch.request.param
import io.finch.response._
object FibonacciSequenceService extends Service[Request, Response] {
val fibonacciFinder: FibonacciFinder = new MatricesFibonacciFinder()
override def apply(request: Request): Future[Response] = {
for {
termNumber <- param("termNumber")(request).map(_.toInt)
} yield {
val result = fibonacciFinder.findNthTermInSequence(termNumber)
Ok(s"$result")
}
}
}
开发者ID:willb611,项目名称:algorithms-service,代码行数:22,代码来源:FibonacciSequenceService.scala
示例5: BinomialService
//设置package包名称以及导入依赖的类
package services
import algorithms.BinomialCoefficient
import com.twitter.finagle.Service
import com.twitter.finagle.httpx.{Request, Response}
import com.twitter.util.Future
import io.finch.request.param
import io.finch.response._
object BinomialService extends Service[Request, Response] {
override def apply(request: Request): Future[Response] = {
for {
n <- param("n")(request).map(_.toInt)
k <- param("k")(request).map(_.toInt)
} yield {
val result = BinomialCoefficient.nChooseK(n, k)
Ok(s"$result")
}
}
}
开发者ID:willb611,项目名称:algorithms-service,代码行数:22,代码来源:BinomialService.scala
示例6: 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
}
}
开发者ID:pairi,项目名称:pairi,代码行数:45,代码来源:LoggingFilter.scala
示例7: HelloFinagleServer
//设置package包名称以及导入依赖的类
package jp.gr.java_conf.massakai.application
import com.twitter.finagle.{Http, Service, http}
import com.twitter.util.{Await, Future}
object HelloFinagleServer extends App {
val service = new Service[http.Request, http.Response] {
def apply(req: http.Request): Future[http.Response] =
Future.value(
http.Response(req.version, http.Status.Ok)
)
}
val server = Http.serve(":8080", service)
Await.ready(server)
}
开发者ID:massakai,项目名称:finagle-kafka-sample,代码行数:16,代码来源:HelloFinagleServer.scala
示例8: HelloFinagleClient
//设置package包名称以及导入依赖的类
package jp.gr.java_conf.massakai.application
import com.twitter.finagle.{Http, Service, http}
import com.twitter.util.{Await, Future}
object HelloFinagleClient extends App {
val client: Service[http.Request, http.Response] = Http.newService("www.scala-lang.org:80")
val request = http.Request(http.Method.Get, "/")
request.host = "www.scala-lang.org"
val response: Future[http.Response] = client(request)
response.onSuccess { resp: http.Response =>
println("GET success: " + resp)
}
Await.ready(response)
}
开发者ID:massakai,项目名称:finagle-kafka-sample,代码行数:16,代码来源:HelloFinagleClient.scala
示例9: 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
示例10: 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)
}
}
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:36,代码来源:YaasHeadersFilter.scala
示例11: 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
示例12: 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)
}
}
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:32,代码来源:ThriftServer.scala
示例13: 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()))
}
}
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:22,代码来源:ThriftClient.scala
示例14: 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)
}
}
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:33,代码来源:ThriftMuxGlobalServer.scala
示例15: 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)
}
}
开发者ID:vtatai,项目名称:finagleThriftPlayground,代码行数:32,代码来源:ThriftMuxServer.scala
示例16: RedisService
//设置package包名称以及导入依赖的类
package com.twitter.finagle.redis.server
import com.twitter.finagle.Service
import com.twitter.finagle.redis.server.runner.{CommandRunner, Store}
import com.twitter.io.Buf
import com.twitter.util.Future
import com.twitter.concurrent.AsyncMutex
import com.twitter.finagle.redis.server.protocol.{Command, CommandParser}
import com.twitter.io.Buf.ByteArray
class RedisService extends Service[List[Buf], Buf] {
private var store: Store = Store()
private val mutex = new AsyncMutex()
override def apply(request: List[Buf]): Future[Buf] = {
val parsedCmd: Command = CommandParser(request)
val sync = mutex.acquireAndRunSync {
val (reply, newStore) = CommandRunner.run(parsedCmd, store)
store = newStore
reply
}
sync.map(reply => ByteArray.Owned(reply.decode))
}
}
开发者ID:gustavoamigo,项目名称:finagle-redis-server,代码行数:24,代码来源:RedisService.scala
示例17: Bucket
//设置package包名称以及导入依赖的类
package io.github.daviddenton.finagle.aws
import java.net.URI
import java.time.Clock
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Http, Service}
case class Bucket(name: String) extends AnyVal {
def toUri = URI.create(s"https://$name.s3.amazonaws.com")
}
object Bucket {
def client(bucket: Bucket, region: AwsRegion, credentials: AwsCredentials,
clock: Clock = Clock.systemUTC()): Service[Request, Response] = {
val signatureV4Signer = AwsSignatureV4Signer(AwsCredentialScope(region, AwsService("s3")), credentials)
val authority = bucket.toUri.getAuthority
val http = Http.client.withTls(authority)
.newService(s"$authority:443")
AwsCredentialFilter(authority, clock, signatureV4Signer)
.andThen(http)
}
}
开发者ID:daviddenton,项目名称:finagle-aws,代码行数:25,代码来源:Bucket.scala
示例18: S3Api
//设置package包名称以及导入依赖的类
package io.github.daviddenton.finagle.aws
import com.twitter.finagle.Service
import com.twitter.finagle.http.Method.{Delete, Get, Put}
import com.twitter.finagle.http.Status.{NoContent, NotFound, Ok}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import scala.xml.XML
object S3Api {
def apply(client: Service[Request, Response]): S3Api = new S3Api {
override def list(): Future[Seq[Bucket]] = client(Request(Get, "/")).map(_.contentString).map(XML.loadString).map(S3.buckets)
override def +=(bucket: Bucket): Future[Bucket] = {
val request = Request(Put, "/" + bucket.name)
client(request).flatMap {
rsp =>
rsp.status match {
case Ok => Future(bucket)
case _ => Future.exception(new IllegalArgumentException("AWS returned " + rsp.status))
}
}
}
override def -=(bucket: Bucket): Future[Option[Bucket]] =
client(Request(Delete, "/" + bucket.name)).flatMap {
rsp =>
rsp.status match {
case NoContent => Future(Option(bucket))
case NotFound => Future(None)
case _ => Future.exception(new IllegalArgumentException("AWS returned " + rsp.status))
}
}
}
}
trait S3Api {
def list(): Future[Seq[Bucket]]
def +=(bucket: Bucket): Future[Bucket]
def -=(bucket: Bucket): Future[Option[Bucket]]
}
开发者ID:daviddenton,项目名称:finagle-aws,代码行数:45,代码来源:S3Api.scala
示例19: AwsCredentialFilterTest
//设置package包名称以及导入依赖的类
package io.github.daviddenton.finagle.aws
import java.time.{Clock, Instant, ZoneId}
import com.twitter.finagle.Service
import com.twitter.finagle.http.Method.Get
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Await.result
import com.twitter.util.Future
import org.jboss.netty.handler.codec.http.HttpHeaders.Names
import org.scalatest.{FunSpec, Matchers}
class AwsCredentialFilterTest extends FunSpec with Matchers {
private val clock = Clock.fixed(Instant.ofEpochMilli(0), ZoneId.of("UTC"))
private val filter = AwsCredentialFilter("somehost", clock,
AwsSignatureV4Signer(AwsCredentialScope(AwsRegion.usEast, AwsService.s3), AwsCredentials("access", "secret")))
private val mirrorHeaders = Service.mk {
req: Request =>
val response = Response()
req.headerMap.foreach(response.headerMap += _)
Future.value(response)
}
describe("AwsCredentialFilter") {
it("adds host header") {
result(filter(Request(Get, "/test"), mirrorHeaders)).headerMap(Names.HOST) shouldBe "somehost"
}
it("adds auth header") {
result(filter(Request(Get, "/test"), mirrorHeaders)).headerMap(Names.AUTHORIZATION) shouldBe
"AWS4-HMAC-SHA256 Credential=access/19700101/us-east/s3/aws4_request, SignedHeaders=content-length;host;x-amz-date, Signature=d7690ffa429d19877081491d5a325f564782998a3369a311a3dfcaa8cdeb9ecc"
}
it("adds time header") {
result(filter(Request(Get, "/test"), mirrorHeaders)).headerMap(AwsHeaders.DATE) shouldBe "19700101T010000Z"
}
it("adds content sha256") {
result(filter(Request(Get, "/test"), mirrorHeaders)).headerMap(AwsHeaders.CONTENT_SHA256) shouldBe "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
}
}
开发者ID:daviddenton,项目名称:finagle-aws,代码行数:46,代码来源:AwsCredentialFilterTest.scala
示例20: AuthenticationFilter
//设置package包名称以及导入依赖的类
import com.twitter.finagle.{Service, Filter}
import com.twitter.finagle.http.{Response, Request}
import com.twitter.util.Future
import data.UserData
import org.jboss.netty.handler.codec.http.HttpHeaders.Names
import org.jboss.netty.handler.codec.http.HttpResponseStatus
class AuthenticationFilter(loginService: LoginService) extends Filter[Request, Response, AuthorizedRequest, Response] {
override def apply(request: Request, continue: Service[AuthorizedRequest, Response]): Future[Response] = {
if(request.headers().contains(Names.AUTHORIZATION)) {
request.headers().get(Names.AUTHORIZATION).split(":") match {
case Array(username, password) =>
if(loginService.login(username, password)) {
val authorizedRequest = AuthorizedRequest(request, UserData(username, List("guest")))
continue(authorizedRequest)
} else unauthorized(request)
case _ => unauthorized(request)
}
} else unauthorized(request)
}
def unauthorized(request: Request): Future[Response] =
Future.value(Response(request.getProtocolVersion(), HttpResponseStatus.UNAUTHORIZED))
}
开发者ID:marlomajor,项目名称:finagle-microservice,代码行数:25,代码来源:AuthenticationFilter.scala
注:本文中的com.twitter.finagle.Service类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论