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

Scala Return类代码示例

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

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



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

示例1: UserContext

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

import com.twitter.finagle.context.Contexts
import com.twitter.finagle.util.ByteArrays
import com.twitter.io.Buf
import com.twitter.util.{Return, Throw, Try}

case class UserContext(userId: Long)


  def current: Option[UserContext] = Contexts.broadcast.get(UserContext)

  override def marshal(userContext: UserContext): Buf = {
    val bytes = new Array[Byte](bodyLengthBytes)
    ByteArrays.put64be(bytes, 0, userContext.userId)
    Buf.ByteArray.Owned(bytes)
  }

  override def tryUnmarshal(body: Buf): Try[UserContext] = {
    if (body.length != bodyLengthBytes) {
      return Throw(new IllegalArgumentException(s"Invalid body. Length ${body.length} but required 16"))
    }

    val bytes = Buf.ByteArray.Owned.extract(body)
    val userId = ByteArrays.get64be(bytes, 0)

    Return(UserContext(userId))
  }
} 
开发者ID:gutefrage,项目名称:the-finagle-docs,代码行数:30,代码来源:UserContext.scala


示例2: rng

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

import com.twitter.finagle.{ClientConnection, Service, ServiceFactory, ServiceFactoryProxy, ServiceProxy}
import com.twitter.finagle.service.FailingFactory
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.util.Rng
import com.twitter.util.{Throw, Time, Future, Return}
import java.util.concurrent.atomic.AtomicInteger


private[loadbalancer] trait LeastLoaded[Req, Rep] { self: Balancer[Req, Rep] =>
  protected def rng: Rng

  protected case class Node(
      factory: ServiceFactory[Req, Rep],
      counter: AtomicInteger,
      token: Int)
    extends ServiceFactoryProxy[Req, Rep](factory)
    with NodeT[Req, Rep] {

    type This = Node

    def load: Double = counter.get
    def pending: Int = counter.get

    override def apply(conn: ClientConnection): Future[Service[Req, Rep]] = {
      counter.incrementAndGet()
      super.apply(conn).transform {
        case Return(svc) =>
          Future.value(new ServiceProxy(svc) {
            override def close(deadline: Time) =
              super.close(deadline).ensure {
                counter.decrementAndGet()
              }
          })

        case [email protected](_) =>
          counter.decrementAndGet()
          Future.const(t)
      }
    }
  }

  protected def newNode(factory: ServiceFactory[Req, Rep], statsReceiver: StatsReceiver) =
    Node(factory, new AtomicInteger(0), rng.nextInt())

  private[this] val failingLoad = new AtomicInteger(0)
  protected def failingNode(cause: Throwable) = Node(new FailingFactory(cause), failingLoad, 0)
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:LeastLoaded.scala


示例3: ClientId

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

import com.twitter.finagle.context.Contexts
import com.twitter.util.{Return, Throw}
import com.twitter.io.Buf

case class ClientId(name: String) {
  
object ClientId {
  // As a matter of legacy, we need to support the notion of
  // an empty client id. Old version of contexts could serialize
  // the absence of a client id with an empty buffer.
  private[finagle] val clientIdCtx = new Contexts.broadcast.Key[Option[ClientId]]("com.twitter.finagle.thrift.ClientIdContext") {
    def marshal(clientId: Option[ClientId]): Buf = clientId match {
      case None => Buf.Empty
      case Some(ClientId(name)) => Buf.Utf8(name)
    }

    def tryUnmarshal(buf: Buf) = buf match {
      case buf if buf.isEmpty => Return.None
      case Buf.Utf8(name) => Return(Some(ClientId(name)))
      case invalid => Throw(new IllegalArgumentException("client id not a utf8 string"))
    }
  }

  private[this] val NoClientFn: () => Option[ClientId] = () => None

  def current: Option[ClientId] =
    Contexts.broadcast.getOrElse(clientIdCtx, NoClientFn)

  private[finagle] def let[R](clientId: ClientId)(f: => R): R =
    Contexts.broadcast.let(clientIdCtx, Some(clientId))(f)

  private[finagle] def let[R](clientId: Option[ClientId])(f: => R): R = {
    clientId match {
      case Some(id) => Contexts.broadcast.let(clientIdCtx, Some(id))(f)
      case None => Contexts.broadcast.letClear(clientIdCtx)(f)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:41,代码来源:ClientId.scala


示例4: format

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

import com.twitter.util.{Duration, Return, Throw, Stopwatch, Future}
import com.twitter.finagle.{SimpleFilter, Service}
import com.twitter.logging.Logger

trait LogFormatter[-Req, Rep] {
  def format(request: Req, reply: Rep, replyTime: Duration): String

  def formatException(request: Req, throwable: Throwable, replyTime: Duration): String
}


trait LoggingFilter[Req, Rep] extends SimpleFilter[Req, Rep] {
  val log: Logger
  val formatter: LogFormatter[Req, Rep]

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] = {
    val elapsed = Stopwatch.start()
    val future = service(request)
    future respond {
      case Return(reply) =>
        log(elapsed(), request, reply)
      case Throw(throwable) =>
        logException(elapsed(), request, throwable)
    }
    future
  }

  protected def log(replyTime: Duration, request: Req, reply: Rep) {
    val line = formatter.format(request, reply, replyTime)
    log.info(line)
  }

  protected def logException(replyTime: Duration, request: Req, throwable: Throwable) {
    val line = formatter.formatException(request, throwable, replyTime)
    log.info(throwable, line)
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:41,代码来源:LoggingFilter.scala


示例5: Retries

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

import com.twitter.finagle.util.{BufReader, BufWriter}
import com.twitter.io.Buf
import com.twitter.util.{Return, Throw, Try}


private[finagle] case class Retries(val retries: Int)

private[finagle] object Retries
  extends Contexts.broadcast.Key[Retries]("com.twitter.finagle.Retries")
{

  def current: Option[Retries] =
    Contexts.broadcast.get(Retries)

  override def marshal(retries: Retries): Buf = {
    val bw: BufWriter = BufWriter.fixed(4)
    bw.writeIntBE(retries.retries)
    bw.owned()
  }

  override def tryUnmarshal(buf: Buf): Try[Retries] = {
    if (buf.length != 4) {
      Throw(new IllegalArgumentException(
        s"Could not extract Retries from Buf. Length ${buf.length} but required 4"))
    } else {
      val retries: Int = BufReader(buf).readIntBE()
      Return(Retries(retries))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:33,代码来源:Retries.scala


示例6: StatsFactoryWrapper

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

import com.twitter.finagle._
import com.twitter.util.Throwables
import com.twitter.finagle.stats.{StatsReceiver, RollupStatsReceiver}
import com.twitter.util.{Future, Stopwatch, Return, Throw}

private[finagle] object StatsFactoryWrapper {
  val role = Stack.Role("ServiceCreationStats")

  
class StatsFactoryWrapper[Req, Rep](
    self: ServiceFactory[Req, Rep],
    statsReceiver: StatsReceiver)
  extends ServiceFactoryProxy[Req, Rep](self)
{
  private[this] val failureStats = statsReceiver.scope("failures")
  private[this] val latencyStat = statsReceiver.stat("service_acquisition_latency_ms")

  override def apply(conn: ClientConnection): Future[Service[Req, Rep]] = {
    val elapsed = Stopwatch.start()
    super.apply(conn) respond {
      case Throw(t) =>
        failureStats.counter(Throwables.mkString(t): _*).incr()
        latencyStat.add(elapsed().inMilliseconds)
      case Return(_) =>
        latencyStat.add(elapsed().inMilliseconds)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:31,代码来源:StatsFactoryWrapper.scala


示例7: onClose

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

import com.twitter.util.{Closable, Future, Promise, Return, Time}


    def onClose(h: => Unit) = {
      if (closing.isDefined)
        h
      else
        closeHandlers ::= { () => h }
    }

     // Invokes close handlers in reverse order from which they were added.
    closing ensure { closeHandlers foreach { handler =>
      handler()
    }}
  }

  def makeLifoCloser(): CloseNotifier with Closable = new CloseNotifier with Closable {
    private[this] val closing = new Promise[Unit]
    private[this] val notifier = makeLifo(closing)

    def close(deadline: Time) = {
      closing.updateIfEmpty(Return(()))
      Future.Done
    }
    def onClose(h: => Unit) = notifier.onClose(h)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:30,代码来源:CloseNotifier.scala


示例8: MaskCancelFilterTest

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

import com.twitter.finagle.Service
import com.twitter.util.{Future, Promise, Return}
import org.junit.runner.RunWith
import org.mockito.Matchers.anyObject
import org.mockito.Mockito.{when, verify}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import scala.language.reflectiveCalls

@RunWith(classOf[JUnitRunner])
class MaskCancelFilterTest extends FunSuite with MockitoSugar {
  trait MaskHelper {
    val service = mock[Service[Int, Int]]
    when(service.close(anyObject)).thenReturn(Future.Done)
    val filter = new MaskCancelFilter[Int, Int]

    val filtered = filter andThen service
    val p = new Promise[Int] {
      @volatile var interrupted: Option[Throwable] = None
      setInterruptHandler { case exc => interrupted = Some(exc) }
    }
    when(service(1)).thenReturn(p)

    val f = filtered(1)
    verify(service).apply(1)
  }

  test("MaskCancelFilter should mask interrupts") {
    new MaskHelper {
      assert(p.interrupted == None)
      f.raise(new Exception)
      assert(p.interrupted == None)
    }
  }

  test("MaskCancelFilter should propagate results") {
    new MaskHelper {
      assert(f.poll == None)
      p.setValue(123)
      assert(p.poll == Some(Return(123)))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:47,代码来源:MaskCancelFilterTest.scala


示例9: DeadlineTest

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

import com.twitter.util.{Time, Duration, Return}
import org.junit.runner.RunWith
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatest.junit.{AssertionsForJUnit, JUnitRunner}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

@RunWith(classOf[JUnitRunner])
class DeadlineTest 
  extends FunSuite 
  with AssertionsForJUnit
  with GeneratorDrivenPropertyChecks {

  val time = for (t <- Gen.choose(0L, Long.MaxValue)) yield Time.fromNanoseconds(t)
  val dur = for (d <- Gen.choose(0L, Long.MaxValue)) yield Duration.fromNanoseconds(d)
  val deadline = for (t <- time; d <- dur) yield Deadline(t, t + d)
  val deadlineWithoutTop  = deadline.filter(_.deadline != Time.Top)

  test("Deadline marshalling") {
    // won't pass Time.Top as deadline for marshalling
    forAll(deadlineWithoutTop) { d =>
      assert(Deadline.tryUnmarshal(Deadline.marshal(d)) == Return(d))
    }
  }

  test("Deadline.combined") {
    forAll(deadline, deadline) { (d1, d2) =>
      assert(Deadline.combined(d1, d2).timestamp == (d1.timestamp max d2.timestamp))
      assert(Deadline.combined(d1, d2).deadline == (d1.deadline min d2.deadline))
      assert(Deadline.combined(d1, d2) == Deadline.combined(d2, d1))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:36,代码来源:DeadlineTest.scala


示例10: WrappedInt

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

import com.twitter.concurrent.Spool
import com.twitter.util.{Return, Promise}
import collection.mutable

case class WrappedInt(val value: Int)

class ClusterInt extends Cluster[Int] {
  var set = mutable.HashSet.empty[Int]
  var changes = new Promise[Spool[Cluster.Change[Int]]]

  def add(value: Int) = {
    set += value
    performChange(Cluster.Add(value))
  }

  def del(value: Int) = {
    set -= value
    performChange(Cluster.Rem(value))
  }

  private[this] def performChange(change: Cluster.Change[Int]) = {
    val newTail = new Promise[Spool[Cluster.Change[Int]]]
    changes() = Return(change *:: newTail)
    changes = newTail
  }

  def snap = (set.toSeq, changes)
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:31,代码来源:ClusterInt.scala


示例11: ResponseClassifierTest

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

import com.twitter.finagle.Failure
import com.twitter.finagle.service.ResponseClass._
import com.twitter.util.{Return, Throw}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class ResponseClassifierTest extends FunSuite {

  test("Default classification") {
    assert("DefaultResponseClassifier" == ResponseClassifier.Default.toString)
    assert(Success ==
      ResponseClassifier.Default(ReqRep(null, Return("hi"))))

    assert(RetryableFailure ==
      ResponseClassifier.Default(ReqRep(null, Throw(Failure.rejected))))

    assert(NonRetryableFailure ==
      ResponseClassifier.Default(ReqRep(null, Throw(Failure("nope")))))
  }

  test("composition") {
    val aThrow = Throw(Failure("nope"))
    val aReturn = Return("yep")

    val evens: ResponseClassifier = {
      case ReqRep(i: Int, Throw(_)) if i % 2 == 0 => RetryableFailure
    }
    val odds: ResponseClassifier = {
      case ReqRep(i: Int, Throw(_)) if i % 2 == 1 => NonRetryableFailure
    }
    val classifier = evens.orElse(odds)

    assert(RetryableFailure == classifier(ReqRep(2, aThrow)))
    assert(NonRetryableFailure == classifier(ReqRep(1, aThrow)))

    assert(!classifier.isDefinedAt(ReqRep(0, aReturn)))
    assert(Success == classifier.applyOrElse(ReqRep(0, aReturn), ResponseClassifier.Default))
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:45,代码来源:ResponseClassifierTest.scala


示例12: ReaderUtils

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

import com.twitter.finagle.netty3.ChannelBufferBuf
import com.twitter.finagle.transport.Transport
import com.twitter.io.{Buf, Reader}
import com.twitter.util.{Future, Return}
import org.jboss.netty.handler.codec.http.{HttpChunk, DefaultHttpChunk}

private[http] object ReaderUtils {
  
  def streamChunks(
    trans: Transport[Any, Any],
    r: Reader,
    // TODO Find a better number for bufSize, e.g. 32KiB - Buf overhead
    bufSize: Int = Int.MaxValue
  ): Future[Unit] = {
    r.read(bufSize) flatMap {
      case None =>
        trans.write(HttpChunk.LAST_CHUNK)
      case Some(buf) =>
        trans.write(chunkOfBuf(buf)) transform {
          case Return(_) => streamChunks(trans, r, bufSize)
          case _ => Future(r.discard())
        }
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:28,代码来源:ReaderUtils.scala


示例13: ConnectionClientIntegrationSuite

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

import com.twitter.finagle.redis._
import com.twitter.finagle.redis.tags.{RedisTest, ClientTest}
import com.twitter.util.{Await, Return}
import org.junit.Ignore
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@Ignore
@RunWith(classOf[JUnitRunner])
final class ConnectionClientIntegrationSuite extends RedisClientTest {

  test("Correctly perform the SELECT command", RedisTest, ClientTest) {
    withRedisClient { client =>
      assert(Await.result(client.select(1).liftToTry) == Return.Unit)
    }
  }

  test("Correctly perform the QUIT command", RedisTest, ClientTest) {
    withRedisClient { client =>
      assert(Await.result(client.quit().liftToTry) == Return.Unit)
    }
  }

  test("Correctly perform the PING command without arguments", RedisTest, ClientTest) {
    withRedisClient { client =>
      assert(Await.result(client.ping().liftToTry) == Return.Unit)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:32,代码来源:ConnectionClientIntegrationSuite.scala


示例14: HyperLogLogClientIntegrationSuite

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

import com.twitter.finagle.redis.RedisClientTest
import com.twitter.finagle.redis.tags.{ClientTest, RedisTest}
import com.twitter.util.{Await, Future, Return}
import org.junit.Ignore
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@Ignore
@RunWith(classOf[JUnitRunner])
final class HyperLogLogClientIntegrationSuite extends RedisClientTest {

  test("Correctly perform the PFADD command", RedisTest, ClientTest) {
    withRedisClient { client =>
      assert(Await.result(client.pfAdd(bufFoo, List(bufBar))).booleanValue)
    }
  }

  test("Correctly perform the PFCOUNT command", RedisTest, ClientTest) {
    withRedisClient { client =>
      val pfCountResult = client.pfAdd(bufFoo, List(bufBar, bufBaz)).flatMap(_ => client.pfCount(List(bufFoo)))
      assert(Await.result(pfCountResult) == 2)
    }
  }

  test("Correctly perform the PFMERGE command", RedisTest, ClientTest) {
    withRedisClient { client =>
      val addHll = List((bufFoo, List(bufBar, bufBaz)), (bufBar, List(bufFoo, bufBaz))) map (client.pfAdd _).tupled
      val pfMergeResult = Future.collect(addHll).flatMap(_ => client.pfMerge(bufBaz, List(bufFoo, bufBar)))
      assert(Await.result(pfMergeResult.liftToTry) == Return.Unit)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:35,代码来源:HyperLogLogClientIntegrationSuite.scala


示例15: apply

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

import com.twitter.finagle.http.filter.HttpNackFilter
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.service.{ReqRep, ResponseClass, ResponseClassifier}
import com.twitter.util.Return


  def apply(
    underlying: PartialFunction[(Request, Response), ResponseClass]
  ): ResponseClassifier = new ResponseClassifier {
    override def toString: String =
      s"HttpResponseClassifier($underlying)"

    def isDefinedAt(x: ReqRep): Boolean = x match {
      case ReqRep(req: Request, Return(rep: Response)) => underlying.isDefinedAt((req, rep))
      case _ => false
    }

    def apply(x: ReqRep): ResponseClass = x match {
      case ReqRep(req: Request, Return(rep: Response)) => underlying((req, rep))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:25,代码来源:HttpResponseClassifier.scala


示例16: HttpResponseClassifierTest

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

import com.twitter.finagle.http.filter.HttpNackFilter
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.service.{ReqRep, ResponseClass, ResponseClassifier}
import com.twitter.util.{Return, Try}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class HttpResponseClassifierTest extends FunSuite {
  private val req = Request()
  private def rep(code: Status): Try[Response] = Return(Response(code))

  test("ServerErrorsAsFailures") {
    val classifier = HttpResponseClassifier.ServerErrorsAsFailures
    assert("ServerErrorsAsFailures" == classifier.toString)

    assert(ResponseClass.NonRetryableFailure ==
      classifier(ReqRep(req, rep(Status.InternalServerError))))

    assert(!classifier.isDefinedAt(ReqRep(req, rep(Status.Ok))))
    assert(ResponseClass.NonRetryableFailure ==
      classifier.applyOrElse(
        ReqRep(req, rep(Status.InternalServerError)),
        ResponseClassifier.Default)
    )
  }

  test("ServerErrorsAsFailures for nacks") {
    val classifier = HttpResponseClassifier.ServerErrorsAsFailures
    val reply = Response(HttpNackFilter.ResponseStatus)
    reply.headerMap.set(HttpNackFilter.RetryableNackHeader, "true")

    assert(ResponseClass.RetryableFailure == classifier(ReqRep(req, Return(reply))))
  }

  test("apply") {
    val ok500 = HttpResponseClassifier {
      case (_, rep: Response) if rep.statusCode == 500 => ResponseClass.Success
    }
    val badReqs = HttpResponseClassifier {
      case (req: Request, _) if req.containsParam("fail") => ResponseClass.NonRetryableFailure
    }
    val classifier = ok500.orElse(badReqs)

    assert(ResponseClass.Success == classifier(ReqRep(req, rep(Status.fromCode(500)))))
    assert(ResponseClass.NonRetryableFailure ==
      classifier(ReqRep(Request("fail" -> "1"), rep(Status.Ok))))

    assert(!classifier.isDefinedAt(ReqRep(req, rep(Status.Ok))))
    assert(ResponseClass.Success ==
      classifier.applyOrElse(
        ReqRep(req, rep(Status.Ok)),
        ResponseClassifier.Default)
    )
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:61,代码来源:HttpResponseClassifierTest.scala


示例17: ThriftSerialClientDispatcher

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

import com.twitter.finagle.dispatch.GenSerialClientDispatcher.wrapWriteException
import com.twitter.finagle.dispatch.SerialClientDispatcher
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.transport.Transport
import com.twitter.util.{Future, Promise, Return, Throw}

private[finagle] class ThriftSerialClientDispatcher(
    transport: Transport[ThriftClientRequest, Array[Byte]],
    statsReceiver: StatsReceiver)
  extends SerialClientDispatcher[ThriftClientRequest, Array[Byte]](transport, statsReceiver) {

  
  override protected def dispatch(
    req: ThriftClientRequest,
    p: Promise[Array[Byte]]
  ): Future[Unit] = {
    if (!req.oneway) super.dispatch(req, p)
    else {
      write(req)
        .respond {
          case Return(_) => p.updateIfEmpty(ThriftSerialClientDispatcher.EmptyByteArray)
          case Throw(err) => wrapWriteException(err).respond(p.updateIfEmpty(_))
        }
    }

  }
}

private object ThriftSerialClientDispatcher {
  val EmptyByteArray = Return(new Array[Byte](0))
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:34,代码来源:ThriftSerialClientDispatcher.scala


示例18: DeserializeCtxTest

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

import com.twitter.scrooge.ThriftStruct
import com.twitter.util.Return
import java.util.concurrent.atomic.AtomicInteger
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class DeserializeCtxTest extends FunSuite
  with MockitoSugar {

  test("only deserializes once") {
    val times = new AtomicInteger()
    val theVal = Return("hi")

    val deserializer = { bytes: Array[Byte] =>
      times.incrementAndGet()
      theVal
    }

    val deserCtx = new DeserializeCtx(mock[ThriftStruct], deserializer)

    assert(theVal == deserCtx.deserialize(Array.empty))
    assert(1 == times.get)

    assert(theVal == deserCtx.deserialize(Array.empty))
    assert(1 == times.get)
  }

  test("deserialize ignores input after first deserialize") {
    val deserializer = { bytes: Array[Byte] =>
      Return(bytes.length)
    }
    val deserCtx = new DeserializeCtx(mock[ThriftStruct], deserializer)

    assert(Return(0) == deserCtx.deserialize(Array.empty))
    assert(Return(0) == deserCtx.deserialize(Array(9.toByte)))
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:44,代码来源:DeserializeCtxTest.scala


示例19: eqTry

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

import java.util.UUID

import algebra.Eq
import cats.Show
import com.twitter.io.Buf
import com.twitter.util.{Return, Throw, Try}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner


@RunWith(classOf[JUnitRunner])
trait MissingInstances {
  implicit def eqTry[A](implicit A: Eq[A]): Eq[Try[A]] = Eq.instance {
    case (Return(a), Return(b)) => A.eqv(a, b)
    case (Throw(x), Throw(y)) => x == y
    case _ => false
  }

  implicit def eqUUID: Eq[UUID] = Eq.fromUniversalEquals

  implicit def showUUID: Show[UUID] = Show.fromToString

  implicit def eqBuf: Eq[Buf] = Eq.fromUniversalEquals
} 
开发者ID:teodimoff,项目名称:rOut,代码行数:27,代码来源:MissingInstances.scala


示例20: decodeRootJson

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

import com.redbubble.util.http.Errors.jsonDecodeFailedError
import com.redbubble.util.json.CodecOps
import com.twitter.io.Buf
import com.twitter.util.{Return, Throw, Try}
import io.circe.Decoder
import io.finch.Decode

trait RequestOps {
  type JsonCleaner = (Buf) => Buf

  
  final def decodeRootJson[A](d: Decoder[A], c: JsonCleaner = identity): Decode.Json[A] =
    Decode.json((payload, _) => decodePayload(c(payload), rootObjectDecoder(d)))

  private def decodePayload[A](payload: Buf, decoder: Decoder[A]): Try[A] = {
    val decodedPayload = CodecOps.decode(payload)(decoder)
    decodedPayload.fold(
      error => Throw(jsonDecodeFailedError(s"Unable to decode JSON payload: ${error.getMessage}", error)),
      value => Return(value)
    )
  }

  private def dataFieldObjectDecoder[A](implicit d: Decoder[A]): Decoder[A] =
    Decoder.instance(c => c.downField("data").as[A](d))

  private def rootObjectDecoder[A](implicit d: Decoder[A]): Decoder[A] = Decoder.instance(c => c.as[A](d))
}

object RequestOps extends RequestOps 
开发者ID:redbubble,项目名称:finch-template,代码行数:32,代码来源:RequestOps.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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