当前位置: 首页>>代码示例>>Scala>>正文


Scala Http类代码示例

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


在下文中一共展示了Http类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: WebserverApp

//设置package包名称以及导入依赖的类
import java.security.KeyStore
import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory}

import com.twitter.finagle.Http
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch._
import io.finch.circe._


object WebserverApp extends App {

  def getSSLContext: SSLContext = {
    // Create and initialize the SSLContext with key material
    val passphrase = "sample".toCharArray()
    val trustPassphrase = "sample".toCharArray()
    // First initialize the key and trust material
    val ksKeys = KeyStore.getInstance("JKS")
    val keystoreResource = this.getClass.getClassLoader.getResourceAsStream("sample-keystore.jks")
    ksKeys.load(keystoreResource, passphrase)
    val ksTrust = KeyStore.getInstance("JKS")
    val trustStoreResource = this.getClass.getClassLoader.getResourceAsStream("sample-keystore.jks")
    ksTrust.load(trustStoreResource, trustPassphrase)
    // KeyManagers decide which key material to us
    val kmf = KeyManagerFactory.getInstance("SunX509")
    kmf.init(ksKeys, passphrase)
    // TrustManagers decide whether to allow connections
    val tmf = TrustManagerFactory.getInstance("SunX509")
    tmf.init(ksTrust)
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(kmf.getKeyManagers, tmf.getTrustManagers, null)
    sslContext
  }


  def sample: Endpoint[String] =
    get("sample") {
      Ok("Was it a TLS connection?... probably not")
    }

  val routes = sample

  val server = Http.server
    .withTransport.tls(getSSLContext)
    .serve(s":38082", routes.handle {
      case e: Exception =>
        InternalServerError(e)
    }.toService)

  println("Server running on :38082")
  Await.result(server)

} 
开发者ID:nicojs,项目名称:poc-finch-tls,代码行数:54,代码来源:WebserverApp.scala

示例3:

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

import app.config.application.ApplicationProperty
import app.v1.Api
import com.twitter.finagle.Http
import com.twitter.logging.Logger
import com.twitter.util.{ Await, Duration, StorageUnit }

trait ServerModule {

  self: com.twitter.app.App with Api with ApplicationProperty =>

  private val log = Logger.get(getClass)

  premain {
    log.info("[Finch] server is starting ...")

    val server = Http.server
      .withLabel(applicationProperty.systemId)
      .withRequestTimeout(Duration.fromSeconds(applicationProperty.requestTimeoutInSeconds))
      .withMaxRequestSize(StorageUnit.fromMegabytes(applicationProperty.maxRequestSizeInMB))
      .configured(Http.Netty4Impl)
      .serve(s":${applicationProperty.applicationPort}", apiService)

    onExit {
      server.close()
    }

    Await.result(server)
  }

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

示例4: 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)
  }
} 
开发者ID:finagle,项目名称:featherbed,代码行数:36,代码来源:package.scala

示例5: 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")
  }
} 
开发者ID:bobxwang,项目名称:scalatour,代码行数:46,代码来源:HttpTips.scala

示例6: 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

示例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: Test

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

import java.net.URL

import com.twitter.conversions.time._
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.factory.TimeoutFactory
import com.twitter.finagle.http.Request
import com.twitter.finagle.service.FailFastFactory.FailFast
import com.twitter.finagle.{Http, param}
import com.twitter.io.Buf
import com.twitter.util.Await

object Test {
  def main(args: Array[String]): Unit = {
    val url = new URL("https://github.com")

    println(s"Creating client using inet!${url.getHost}:443")

    val client = Http.client
      .configured(param.Label("finagle_pools"))
      .configured(TimeoutFactory.Param(10.seconds))
      .configured(Transporter.ConnectTimeout(10.seconds))
      .configured(FailFast(enabled = false))
      .withTransport.tls(hostname = url.getHost)
      .withTransport.verbose
      .withSessionPool.minSize(1)
      .withSessionPool.maxSize(2)
      .withSessionPool.maxWaiters(250)
      .newClient(s"inet!${url.getHost}:443")
      .toService

    val request = Request("https://github.com/twitter/finagle")
    val response = Await.result(client(request))
    println(new String(Buf.ByteArray.Owned.extract(response.content), "UTF-8"))
  }
} 
开发者ID:reikje,项目名称:finagle_pools,代码行数:38,代码来源:Test.scala

示例10: TestClientServerMain

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

import java.net.InetSocketAddress

import com.sgtest.controllers.AuthenticationController
import com.twitter.finagle.Http
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.stats.DefaultStatsReceiver
import com.twitter.finagle.zipkin.thrift.ZipkinTracer
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter, TraceIdMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter


object TestClientServerMain extends TestClientServer

class TestClientServer extends HttpServer {

  override def defaultFinatraHttpPort = ":8888"

  override val adminPort = flag("admin.port", new InetSocketAddress(8880), "Admin Http server port")

  override def configureHttp(router: HttpRouter) {
    router
      .filter[LoggingMDCFilter[Request, Response]]
      .filter[TraceIdMDCFilter[Request, Response]]
      .filter[CommonFilters]
      .add[AuthenticationController]
  }

  override def configureHttpServer(server: Http.Server): Http.Server = {
    val receiver = DefaultStatsReceiver.get
    val zipkinHost = sys.env.getOrElse("SG_ZIPKIN_HOST","localhost")
    val zipkinPort = sys.env.getOrElse("SG_ZIPKIN_PORT", "9410").toInt
    val tracer = ZipkinTracer.mk(
      host = zipkinHost,
      port = zipkinPort,
      statsReceiver = receiver
    )
    server
        .withTracer(tracer)
        .withLabel("test-client-server")
  }

} 
开发者ID:divanvisagie,项目名称:swiss-guard,代码行数:46,代码来源:TestClientServer.scala

示例11: 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

示例12: Yahoo

//设置package包名称以及导入依赖的类
package stockTicker

import java.io.{BufferedReader, InputStreamReader}
import java.time.LocalDate

import com.twitter.bijection.Conversion.asMethod
import com.twitter.finagle.http.Response
import com.twitter.finagle.service.{Backoff, RetryBudget}
import com.twitter.finagle.{Http, http}
import com.twitter.util.TimeConversions._
import com.twitter.util.{Await, Future}

import scala.collection.immutable.Seq

object Yahoo {


  private def rootUri = "real-chart.finance.yahoo.com"

  def pricesURL(businessDate : java.time.LocalDate, ticker: String) : String = {
    val lastYear = businessDate.minusYears(1)
    val url =f"http://$rootUri/table.csv?s=$ticker&a=${lastYear.getMonthValue}&b=${lastYear.getDayOfMonth}&c=${lastYear.getYear}&d=${businessDate.getMonthValue}&e=${businessDate.getDayOfMonth}&f=${businessDate.getYear}&g=d&ignore=.csv"
    url
  }

  private val budget: RetryBudget = RetryBudget(
    ttl = 10.seconds,
    minRetriesPerSec = 5,
    percentCanRetry = 0.1
  )

  private val client = Http.client
    .withRetryBudget(budget)
    .withRetryBackoff(Backoff.const(10 seconds))
    .newService(s"$rootUri:80")

  implicit val priceSource = new PriceSource[StockPrice] {
    override def fetchPrices(ticker: String) : Seq[StockPrice]  = {
      val request = http.Request(http.Method.Get, pricesURL(LocalDate.now, ticker))
      request.host = rootUri
      val response = client(request).as[Future[Response]]
      Await.result(response map { res =>
        val reader = new BufferedReader(new InputStreamReader(res.getInputStream))
        reader.readLine()
        Stream.continually(reader.readLine())
          .takeWhile(s=> s!= null && !s.isEmpty)
          .map { StockPrice(ticker, _) }
      })
    }
  }
} 
开发者ID:ashic,项目名称:scalaStocks,代码行数:52,代码来源:Yahoo.scala

示例13: UserService

//设置package包名称以及导入依赖的类
package net.gutefrage.finch.services

import io.catbird.util._
import cats.data.EitherT
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import io.circe.parser.parse
import io.circe.generic.auto._
import net.gutefrage.finch.models.User


class UserService {

  private case class RandomUserResults(results: List[User])

  private val hostname = "randomuser.me"
  private val client: Service[Request, Response] =
    Http.client.withTls(hostname).newService(s"$hostname:443")

  def get(): Future[List[User]] = {
    val req = Request("/api/", "results" -> "10")
    req.host = "api.randomuser.me"
    req.contentType = "application/json"
    (for {
      response <- EitherT.right(client(req))
      rawJson <- EitherT
        .fromEither[Future](parse(response.contentString))
        .leftMap(_ => List.empty[User])
      user <- EitherT
        .fromEither[Future](rawJson.as[RandomUserResults])
        .leftMap(_ => List.empty[User])
    } yield user.results).merge
  }

} 
开发者ID:muuki88,项目名称:finch-scalajs-twirl,代码行数:37,代码来源:UserService.scala

示例14: Server

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

import com.slouc.finchdemo.http.api.Api
import com.twitter.finagle.http.{Request, Response}
import com.twitter.server._
import com.twitter.finagle.{Http, Service}
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch.circe._

object Server extends TwitterServer {

  val api: Service[Request, Response] =
    (Api.endpoint1 :+: Api.endpoint2 :+: Api.endpoint3 :+: Api.endpoint4)
      .toService

  def main(): Unit = {
    val server = Http.server.serve(":8080", api)
    onExit {
      server.close()
    }
    Await.ready(adminHttpServer)
  }

} 
开发者ID:slouc,项目名称:finch-demo,代码行数:26,代码来源:Server.scala

示例15: Http2StreamingTest

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

import com.twitter.finagle.Http
import com.twitter.finagle.Http.HttpImpl
import com.twitter.finagle.http.AbstractStreamingTest
import com.twitter.finagle.http2.param.PriorKnowledge
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class Http2StreamingTest extends AbstractStreamingTest {
  def impl: HttpImpl = Http2
  override def configureClient: Http.Client => Http.Client  = { client =>
    client.configured(PriorKnowledge(true))
  }
  override def configureServer: Http.Server => Http.Server  = { server =>
    server.configured(PriorKnowledge(true))
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:20,代码来源:Http2StreamingTest.scala


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