本文整理汇总了Scala中com.twitter.finagle.http.Method类的典型用法代码示例。如果您正苦于以下问题:Scala Method类的具体用法?Scala Method怎么用?Scala Method使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Method类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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")
}
}
示例2: 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)
}
}
}
}
}
示例3: StatusEndpointTest
//设置package包名称以及导入依赖的类
package placeholder
import com.twitter.finagle.http.{Response, Method, Request}
import com.twitter.util.Await
import placeholder.base.IntegrationTestBase
class StatusEndpointTest extends IntegrationTestBase {
feature("Server status endpoint") {
scenario("returns server uptime") {
Given("the server is running")
val path = "/status"
val responseFuture = performRequest(Request(Method.Get, path))
When(s"I do a HTTP GET to '$path'")
val response: Response = Await.result(responseFuture)
response.statusCode shouldBe 200
Then("the response should have statuscode 200")
}
}
}
示例4: TickServices
//设置package包名称以及导入依赖的类
package mon4all.api
import mon4all.db._
import com.twitter.finagle.http.{Method, HttpMuxer, Request, Response}
import com.twitter.finagle.{Http, Service, ListeningServer}
import com.twitter.finagle.http
import com.twitter.finagle.http.filter.Cors
import com.twitter.finagle.http.service.RoutingService
import com.twitter.finagle.http.path._
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future}
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
object TickServices {
import Helpers._
def getJobItem(jobName: String, itemName: String) = service {
req => http.Response(req.version, http.Status.Ok)
}
case class TickJob(id: Long, name: String) {
def toJValue = (("id" -> id) ~ ("name" -> name))
}
val tickJobs = compact(
List(TickJob(1, "FA Purchase Score BT"),
TickJob(2, "Sim Birth BT"),
TickJob(3, "FA Daily Recompute"),
TickJob(10, "Cash Credit Daily"),
TickJob(20, "Usage Profiling"),
TickJob(30, "Some Spark Shell"),
TickJob(40, "PySpark Notebook"))
.map(_.toJValue))
def getTickJobs = service {
req => {
val resp = http.Response(req.version, http.Status.Ok)
resp.setContentString(tickJobs)
resp
}
}
}
示例5: 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)
}
}
示例6: ServiceConsumer
//设置package包名称以及导入依赖的类
package com.twitter.finagle.example.zookeeper
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
import com.twitter.finagle.Http
import com.twitter.finagle.example.zookeeper.ServiceProvider.EchoServer
import com.twitter.finagle.http.{Method, Request, Version}
import com.twitter.io.Reader
import com.twitter.util.Await
object ServiceConsumer {
def main(args: Array[String]): Unit = {
//use zookeeper to discover service
val client = Http.client
.withSessionPool.maxSize(10)
.newService(ServiceProvider.buildConsumerPath(EchoServer.servicePath), "echo-client")
//create a "Greetings!" request.
val data = Reader.fromStream(new ByteArrayInputStream("Greetings!".getBytes(StandardCharsets.UTF_8)))
val request = Request(Version.Http11, Method.Post, "/", data)
Await.ready(client(request)) onSuccess { response =>
println(s"response status: ${response.status}, response string: ${response.contentString} ")
} onFailure { e =>
println(s"error: $e")
} ensure {
client.close()
}
}
}
示例7: 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))
示例8: RoutingService
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.service
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Request, Response, Method}
import com.twitter.finagle.http.path.Path
import com.twitter.util.Future
class RoutingService[REQUEST <: Request](
val routes: PartialFunction[Request, Service[REQUEST, Response]])
extends Service[REQUEST, Response] {
// Try routes, fall back to 404 Not Found
protected[this] val notFoundService = new NotFoundService[REQUEST]
protected[this] val notFoundPf: PartialFunction[REQUEST, Service[REQUEST, Response]] = {
case _ => notFoundService
}
protected[this] val requestToService: PartialFunction[REQUEST, Service[REQUEST, Response]] =
routes.orElse(notFoundPf)
def apply(request: REQUEST): Future[Response] = {
val service = requestToService(request)
service(request)
}
}
object RoutingService {
def byPath[REQUEST](routes: PartialFunction[String, Service[REQUEST, Response]]) =
new RoutingService(
new PartialFunction[Request, Service[REQUEST, Response]] {
def apply(request: Request): Service[REQUEST, Response] = routes(request.path)
def isDefinedAt(request: Request): Boolean = routes.isDefinedAt(request.path)
})
def byPathObject[REQUEST](routes: PartialFunction[Path, Service[REQUEST, Response]]) =
new RoutingService(
new PartialFunction[Request, Service[REQUEST, Response]] {
def apply(request: Request): Service[REQUEST, Response] = routes(Path(request.path))
def isDefinedAt(request: Request): Boolean =
routes.isDefinedAt(Path(request.path))
})
def byMethodAndPath[REQUEST](routes: PartialFunction[(Method, String), Service[REQUEST, Response]]) =
new RoutingService(
new PartialFunction[Request, Service[REQUEST, Response]] {
def apply(request: Request): Service[REQUEST, Response] =
routes((request.method, request.path))
def isDefinedAt(request: Request): Boolean =
routes.isDefinedAt((request.method, request.path))
})
def byMethodAndPathObject[REQUEST](routes: PartialFunction[(Method, Path), Service[REQUEST, Response]]) =
new RoutingService(
new PartialFunction[Request, Service[REQUEST, Response]] {
def apply(request: Request): Service[REQUEST, Response] =
routes((request.method, Path(request.path)))
def isDefinedAt(request: Request): Boolean =
routes.isDefinedAt((request.method, Path(request.path)))
})
}
示例9: MethodRequiredFilterTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.filter
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Method, Request, Response, Status}
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class MethodRequiredFilterTest extends FunSuite {
val dummyService = new Service[Request, Response] {
def apply(request: Request): Future[Response] = {
val response = request.response
request.params.get("exception").foreach(e => {
response.write("exception thrown")
throw new Exception()
})
request.params.get("code") match {
case Some(code) => response.statusCode = code.toInt
case None => response.status = Status.Ok
}
Future.value(response)
}
}
val filter = new MethodRequiredFilter[Request](Set(Method.Post))
test("return 407 when disallowed method is used") {
val request = Request()
request.method = Method.Get
val response = Await.result(filter(request, dummyService))
assert(response.status == Status.MethodNotAllowed)
assert(response.headers.get("Allow") == "POST")
}
test("return 200 when allowed method is used") {
val request = Request()
request.method = Method.Post
val response = Await.result(filter(request, dummyService))
assert(response.status == Status.Ok)
}
}
示例10: HeadFilterTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.filter
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Method, Request, Response, Status}
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class HeadFilterTest extends FunSuite {
val Body = "hello world"
val dummyService = new Service[Request, Response] {
def apply(request: Request) = {
assert(request.method == Method.Get)
val response = Response(request)
response.status = Status.Ok
response.write(Body)
Future.value(response)
}
}
test("convert GET to HEAD") {
val request = Request("/test.json")
request.method = Method.Head
val response = Await.result(HeadFilter(request, dummyService))
assert(request.method == Method.Head) // unchanged
assert(response.contentLength == Some(Body.length))
assert(response.contentString == "")
}
test("GET is normal") {
val request = Request("/test.json")
val response = Await.result(HeadFilter(request, dummyService))
request.method == Method.Get // unchanged
assert(response.contentLength == None)
assert(response.contentString == Body)
}
}
示例11: JsonpFilterTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http.filter
import com.twitter.finagle.Service
import com.twitter.finagle.http.{MediaType, Method, Request, Response, Status}
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class JsonpFilterTest extends FunSuite {
val dummyService = new Service[Request, Response] {
def apply(request: Request): Future[Response] = {
val response = request.response
response.status = Status.Ok
if (request.params.contains("not_json"))
response.mediaType = "not_json"
else
response.mediaType = MediaType.Json
response.write("{}")
Future.value(response)
}
}
test("wrap json") {
val request = Request("/test.json", "callback" -> "mycallback")
val response = Await.result(JsonpFilter(request, dummyService))
assert(response.contentType == Some("application/javascript"))
assert(response.contentString == "/**/mycallback({});")
}
test("ignore non-json") {
val request = Request("/test.json", "callback" -> "mycallback", "not_json" -> "t")
val response = Await.result(JsonpFilter(request, dummyService))
assert(response.mediaType == Some("not_json"))
assert(response.contentString == "{}")
assert(response.contentType == Some("not_json"))
}
test("ignore HEAD") {
val request = Request("/test.json", "callback" -> "mycallback")
request.method = Method.Head
val response = Await.result(JsonpFilter(request, dummyService))
assert(response.contentType == Some("application/json"))
assert(response.contentString == "{}")
}
test("ignore empty callback") {
// Search Varnish sets callback to blank. These should not be wrapped.
val request = Request("/test.json", "callback" -> "")
val response = Await.result(JsonpFilter(request, dummyService))
assert(response.contentType == Some("application/json"))
assert(response.contentString == "{}")
}
}
示例12: HttpResponderSpec
//设置package包名称以及导入依赖的类
package io.livingston.ditto.http
import java.net.ServerSocket
import com.twitter.finagle.Http
import com.twitter.finagle.http.{Method, Request}
import com.twitter.util.Await
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
class HttpResponderSpec extends WordSpec with Matchers with BeforeAndAfter {
val s = new ServerSocket(0)
val port = s.getLocalPort
s.close()
val yaml =
s"""
|---
|http:
|- port: $port
| endpoints:
| - uri: "/get"
| method: "GET"
| status: 200
| body: "OK"
| latency:
| min: 10
| max: 50
""".stripMargin
val server = new HttpResponder()
before {
server.apply(yaml)
}
after {
server.close()
}
"Http config" should {
"respond correctly to http requests" in {
val client = Http.newService(s":$port")
val response = Await.result(client(Request(Method.Get, "/get")))
response.statusCode should be(200)
response.contentString should be("OK")
}
}
}
示例13: HttpRequestLabellerSpec
//设置package包名称以及导入依赖的类
package com.samstarling.prometheusfinagle.filter
import com.samstarling.prometheusfinagle.UnitTest
import com.twitter.finagle.http.{Method, Request, Response, Status}
import org.specs2.specification.Scope
class HttpRequestLabellerSpec extends UnitTest {
trait Context extends Scope {
val request = Request(Method.Get, "/foo/bar")
val response = Response(Status.Ok)
val labeller = new HttpRequestLabeller()
val labels = labeller.labelsFor(request, response)
}
"keys" >> {
"returns the keys in the correct order" in new Context {
labeller.keys ==== Seq("status", "statusClass", "method")
}
}
"labelsFor" >> {
"returns the status code of the response" in new Context {
labels(0) ==== "200"
}
"returns the status class of the request" in new Context {
labels(1) ==== "2xx"
}
"returns the method of the request" in new Context {
labels(2) ==== "GET"
}
}
}
示例14: MetricsServiceSpec
//设置package包名称以及导入依赖的类
package com.samstarling.prometheusfinagle.metrics
import com.samstarling.prometheusfinagle.UnitTest
import com.twitter.finagle.http.{Method, Request}
import com.twitter.util.Await
import io.prometheus.client.CollectorRegistry
import org.specs2.specification.Scope
import scala.collection.JavaConverters._
class MetricsServiceSpec extends UnitTest {
trait Context extends Scope {
val registry = new CollectorRegistry(true)
val telemetry = new Telemetry(registry, "unit_test")
val service = new MetricsService(registry.metricFamilySamples.asScala.toList)
}
"it renders metrics correctly" in new Context {
telemetry.counter("foo").inc()
val request = Request(Method.Get, "/")
val response = Await.result(service.apply(request))
response.getContentString.trim ====
"# HELP unit_test_foo No help provided\n" +
"# TYPE unit_test_foo counter\n" +
"unit_test_foo 1.0"
}
}
示例15: HttpClient
//设置package包名称以及导入依赖的类
import com.twitter.finagle.Http
import com.twitter.finagle.http.{Method, Request, Version}
import com.twitter.util.{Await, Future}
class HttpClient {
lazy val client = Http.client
.withLabel("finagle-client")
.newService("localhost:9999")
private def requestHandler(request: Request) = client(request).map(_.contentString)
def get(url: String): Future[String] = {
val request = Request(Version.Http11, Method.Get, url)
requestHandler(request)
}
def post(url: String, payload: String) = {
val request = Request(Version.Http11, Method.Post, url)
request.setContentString(payload)
requestHandler(request)
}
}
object HttpClient {
def apply() = new HttpClient()
}
object FinagleClient {
val httpClient = HttpClient()
def main(args: Array[String]) {
//do get request
Await.ready(httpClient get "/ping") onSuccess { responseString =>
println(s"got: $responseString from get /ping")
}
//do post request
Await.ready(httpClient post ("/ping","myPayload")) onSuccess { responseString =>
println(s"got: $responseString from post /ping")
}
}
}