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


Scala Return类代码示例

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


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


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