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

Scala CountDownLatch类代码示例

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

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



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

示例1: PinnedActorSpec

//设置package包名称以及导入依赖的类
package akka.actor.dispatch

import java.util.concurrent.{ CountDownLatch, TimeUnit }

import akka.testkit._
import akka.actor.{ Props, Actor }
import akka.testkit.AkkaSpec
import org.scalatest.BeforeAndAfterEach
import akka.dispatch.{ PinnedDispatcher, Dispatchers }
import scala.concurrent.Await
import akka.pattern.ask

object PinnedActorSpec {
  val config = """
    pinned-dispatcher {
      executor = thread-pool-executor
      type = PinnedDispatcher
    }
    """

  class TestActor extends Actor {
    def receive = {
      case "Hello"   ? sender() ! "World"
      case "Failure" ? throw new RuntimeException("Expected exception; to test fault-tolerance")
    }
  }
}

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class PinnedActorSpec extends AkkaSpec(PinnedActorSpec.config) with BeforeAndAfterEach with DefaultTimeout {
  import PinnedActorSpec._

  private val unit = TimeUnit.MILLISECONDS

  "A PinnedActor" must {

    "support tell" in {
      var oneWay = new CountDownLatch(1)
      val actor = system.actorOf(Props(new Actor { def receive = { case "OneWay" ? oneWay.countDown() } }).withDispatcher("pinned-dispatcher"))
      val result = actor ! "OneWay"
      assert(oneWay.await(1, TimeUnit.SECONDS))
      system.stop(actor)
    }

    "support ask/reply" in {
      val actor = system.actorOf(Props[TestActor].withDispatcher("pinned-dispatcher"))
      assert("World" === Await.result(actor ? "Hello", timeout.duration))
      system.stop(actor)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:52,代码来源:PinnedActorSpec.scala


示例2: DispatcherActorsSpec

//设置package包名称以及导入依赖的类
package akka.actor.dispatch

import java.util.concurrent.CountDownLatch
import akka.actor._
import akka.testkit.AkkaSpec


@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class DispatcherActorsSpec extends AkkaSpec {
  class SlowActor(finishedCounter: CountDownLatch) extends Actor {

    def receive = {
      case x: Int ? {
        Thread.sleep(50) // slow actor
        finishedCounter.countDown()
      }
    }
  }

  class FastActor(finishedCounter: CountDownLatch) extends Actor {
    def receive = {
      case x: Int ? {
        finishedCounter.countDown()
      }
    }
  }

  "A dispatcher and two actors" must {
    "not block fast actors by slow actors" in {
      val sFinished = new CountDownLatch(50)
      val fFinished = new CountDownLatch(10)
      val s = system.actorOf(Props(new SlowActor(sFinished)))
      val f = system.actorOf(Props(new FastActor(fFinished)))

      // send a lot of stuff to s
      for (i ? 1 to 50) {
        s ! i
      }

      // send some messages to f
      for (i ? 1 to 10) {
        f ! i
      }

      // now assert that f is finished while s is still busy
      fFinished.await
      assert(sFinished.getCount > 0)
      sFinished.await
      assert(sFinished.getCount === 0)
      system.stop(f)
      system.stop(s)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:55,代码来源:DispatcherActorsSpec.scala


示例3: TestLatch

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

import scala.concurrent.duration.Duration
import akka.actor.ActorSystem
import scala.concurrent.{ Await, CanAwait, Awaitable }
import java.util.concurrent.{ TimeoutException, CountDownLatch, TimeUnit }
import scala.concurrent.duration.FiniteDuration


object TestLatch {
  val DefaultTimeout = Duration(5, TimeUnit.SECONDS)

  def apply(count: Int = 1)(implicit system: ActorSystem) = new TestLatch(count)
}

class TestLatch(count: Int = 1)(implicit system: ActorSystem) extends Awaitable[Unit] {
  private var latch = new CountDownLatch(count)

  def countDown() = latch.countDown()
  def isOpen: Boolean = latch.getCount == 0
  def open() = while (!isOpen) countDown()
  def reset() = latch = new CountDownLatch(count)

  @throws(classOf[TimeoutException])
  def ready(atMost: Duration)(implicit permit: CanAwait) = {
    val waitTime = atMost match {
      case f: FiniteDuration ? f
      case _                 ? throw new IllegalArgumentException("TestLatch does not support waiting for " + atMost)
    }
    val opened = latch.await(waitTime.dilated.toNanos, TimeUnit.NANOSECONDS)
    if (!opened) throw new TimeoutException(
      "Timeout of %s with time factor of %s" format (atMost.toString, TestKitExtension(system).TestTimeFactor))
    this
  }
  @throws(classOf[Exception])
  def result(atMost: Duration)(implicit permit: CanAwait): Unit = {
    ready(atMost)
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:40,代码来源:TestLatch.scala


示例4: ReqRealTimeBarsHandler

//设置package包名称以及导入依赖的类
package name.kaeding.fibs
package ib
package impl
package handlers

import java.util.concurrent.CountDownLatch
import scalaz._, Scalaz._
import scalaz.concurrent._
import messages._
import contract._
import java.util.concurrent.{ LinkedBlockingQueue, BlockingQueue }
import com.ib.client.EClientSocket
import com.github.nscala_time.time.Imports._
import grizzled.slf4j.Logging

class ReqRealTimeBarsHandler(security: Stock  ,
                             ibActor: Actor[FibsPromiseMessage \/ IBMessage],
                             tickerId: Int, socket: EClientSocketLike) extends FibsPromise[CloseableStream[RealTimeBar]] with Logging { 
  private[this] val TickerId = tickerId
  val latch = new CountDownLatch(0) // don't need to block
  val actor = Actor[IBMessage] {
    case RealTimeBarResp(TickerId, time, open, high, low, close, volume, count, wap) ? 
      queue.add(RealTimeBar(new DateTime(time * 1000), open, high, low, close, volume, count, wap).some)
    case _ ? ???
  }
  val barHandler: PartialFunction[IBMessage, Unit] = {
    case [email protected](TickerId, time, open, high, low, close, volume, count, wap) ? actor ! m
  }
  val patterns = List(barHandler)
  private[this] def toStream: EphemeralStream[RealTimeBar] = {
    val ret: EphemeralStream[RealTimeBar] = queue.take match {
      case Some(d) ? EphemeralStream.cons(d, toStream)
      case None    ? EphemeralStream.emptyEphemeralStream
    }
    ret
  }
  private[this] val queue: BlockingQueue[Option[RealTimeBar]] =
    new LinkedBlockingQueue[Option[RealTimeBar]]()
  private[this] def closeStream = {
    queue add None
    socket.cancelRealTimeBars(tickerId)
    ibActor ! UnregisterFibsPromise(this).left
  }
  def get = new CloseableStream[RealTimeBar] {
    def close = closeStream 
    lazy val as = toStream
  }
} 
开发者ID:carrot-garden,项目名称:vendor_ibrk_fibs-scala,代码行数:49,代码来源:ReqRealTimeBarsHandler.scala


示例5: ReqHistoricalDataHandler

//设置package包名称以及导入依赖的类
package name.kaeding.fibs
package ib
package impl
package handlers

import java.util.concurrent.CountDownLatch
import java.util.concurrent.{ LinkedBlockingQueue, BlockingQueue }

import scalaz._, Scalaz._
import scalaz.concurrent._
import com.github.nscala_time.time.Imports._

import messages._
import contract._

class ReqHistoricalDataHandler(security: Stock  ,
  ibActor: Actor[FibsPromiseMessage \/ IBMessage],
  tickerId: Int) extends FibsPromise[Stream[HistoricalDataPeriod]] {
  private[this] val TickerId = tickerId
  val actor = Actor[IBMessage]{
    case d @ HistoricalData(TickerId, time, _, _, _, _, _, _, _, _) if (!time.startsWith("finished-")) =>
      enqueue(transformMsg(d))
    case d @ HistoricalData(TickerId, time, _, _, _, _, _, _, _, _) if (time.startsWith("finished-")) =>
      close
    case d @ HistoricalDataError(TickerId, 162, msg) if (msg contains "HMDS query returned no data") =>
      close
    case _ => ???
  }
  val historicalDataHandler: PartialFunction[IBMessage, Unit] = {
    case d @ HistoricalData(TickerId, _, _, _, _, _, _, _, _, _) => actor ! d
    case d @ HistoricalDataError(TickerId, 162, msg) if (msg contains "HMDS query returned no data") =>
      actor ! d
  }
  val patterns = List(historicalDataHandler)
  val latch = new CountDownLatch(0) // don't need to block
  def get = toStream
  private[this] def transformMsg(i: HistoricalData) = 
    HistoricalDataPeriod(
      new DateTime(i.date.parseLong.toOption.getOrElse(0L) * 1000),
      i.open,
      i.high,
      i.low,
      i.close,
      i.volume,
      i.count,
      i.wap,
      i.hasGaps)
  private[this] val queue: BlockingQueue[Option[HistoricalDataPeriod]] =
    new LinkedBlockingQueue[Option[HistoricalDataPeriod]]()
  private[this] def close = {
    queue add None
    ibActor ! UnregisterFibsPromise(this).left
  }
  private[this] def enqueue(d: HistoricalDataPeriod) = queue add d.some
  private[this] def toStream(): Stream[HistoricalDataPeriod] = queue.take match {
    case Some(d) => Stream.cons(d, toStream)
    case None => Stream.empty
  }
} 
开发者ID:carrot-garden,项目名称:vendor_ibrk_fibs-scala,代码行数:60,代码来源:ReqHistoricalDataHandler.scala


示例6: ReqMarketTickDataStreamHandler

//设置package包名称以及导入依赖的类
package name.kaeding.fibs
package ib
package impl
package handlers

import java.util.concurrent.CountDownLatch
import scalaz._, Scalaz._
import scalaz.concurrent._
import messages._
import contract._
import java.util.concurrent.{ LinkedBlockingQueue, BlockingQueue }
import com.ib.client.EClientSocket
import com.github.nscala_time.time.Imports._
import grizzled.slf4j.Logging

class ReqMarketTickDataStreamHandler(security: Stock  ,
                                 ibActor: Actor[FibsPromiseMessage \/ IBMessage],
                                 tickerId: Int, socket: EClientSocketLike) extends FibsPromise[CloseableStream[MarketTickDataResult]] with Logging {
  private[this] val TickerId = tickerId
  val latch = new CountDownLatch(0) // don't need to block
  private[this] val RTVolumePattern = "(\\d+\\.?\\d*);(\\d+);(\\d+);(\\d+);(\\d+\\.?\\d*);(true|false)".r
  val actor = Actor[IBMessage] {
    case TickString(TickerId, RTVolume, v) ? 
      parseInput(v).cata(some = t => queue.add(t.some),
                         none = warn(s"error parsing tick data: $v"))
    case _ ? ???
  }
  def parseInput(s: String) = s match {
    case RTVolumePattern(p, s, t, v, w, f) => 
      (p.parseDouble.toOption |@|
       s.parseInt.toOption |@|
       v.parseInt.toOption |@| 
       t.parseLong.toOption |@|
       w.parseDouble.toOption |@|
       f.parseBoolean.toOption)(MarketTickDataResult.apply)
    case _ => none
  }
  val stringHandler: PartialFunction[IBMessage, Unit] = {
    case [email protected](tickerId, RTVolume, _) ? actor ! m
  }
  val patterns = List(stringHandler)
  private[this] val queue: BlockingQueue[Option[MarketTickDataResult]] =
    new LinkedBlockingQueue[Option[MarketTickDataResult]]()
  private[this] def closeStream = {
    queue add None
    socket.cancelMktData(TickerId)
    ibActor ! UnregisterFibsPromise(this).left
  }
  private[this] def toStream: EphemeralStream[MarketTickDataResult] = {
    val ret: EphemeralStream[MarketTickDataResult] = queue.take match {
      case Some(d) ? EphemeralStream.cons(d, toStream)
      case None    ? EphemeralStream.emptyEphemeralStream
    }
    ret
  }
  def get = new CloseableStream[MarketTickDataResult] {
    def close = closeStream 
    lazy val as = toStream
  }
} 
开发者ID:carrot-garden,项目名称:vendor_ibrk_fibs-scala,代码行数:61,代码来源:ReqMarketTickDataStreamHandler.scala


示例7: Nonblocking

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

import java.util.concurrent.{Callable, CountDownLatch, ExecutorService}
import java.util.concurrent.atomic.AtomicReference
import language.implicitConversions

object Nonblocking {

  trait Future[+A] {
    private[parallelism] def apply(k: A => Unit): Unit
  }

  type Par[+A] = ExecutorService => Future[A]

  object Par {

    def run[A](es: ExecutorService)(p: Par[A]): A = {
      val ref = new java.util.concurrent.atomic.AtomicReference[A] // A mutable, threadsafe reference, to use for storing the result
      val latch = new CountDownLatch(1) // A latch which, when decremented, implies that `ref` has the result
      p(es) { a => ref.set(a); latch.countDown } // Asynchronously set the result, and decrement the latch
      latch.await // Block until the `latch.countDown` is invoked asynchronously
      ref.get // Once we've passed the latch, we know `ref` has been set, and return its value
    }

    def unit[A](a: A): Par[A] =
      es => new Future[A] {
        def apply(cb: A => Unit): Unit =
          cb(a)
      }

    
    implicit def toParOps[A](p: Par[A]): ParOps[A] = new ParOps(p)

    // infix versions of `map`, `map2`
    class ParOps[A](p: Par[A]) {
      def map[B](f: A => B): Par[B] = Par.map(p)(f)
      def map2[B,C](b: Par[B])(f: (A,B) => C): Par[C] = Par.map2(p,b)(f)
      def zip[B](b: Par[B]): Par[(A,B)] = p.map2(b)((_,_))
    }
  }
} 
开发者ID:bernardoleary,项目名称:fpinscala,代码行数:42,代码来源:Nonblocking.scala


示例8: SchedulerSpec

//设置package包名称以及导入依赖的类
package knot.core.scheduler

import java.util.concurrent.{CountDownLatch, TimeUnit}

import org.scalatest.FunSpec
import org.scalatest.Matchers._

class SchedulerSpec extends FunSpec {
  val s = new Schedulers()

  describe("scheduler") {
    it("scheduler is singleton") {
      s.single should be theSameInstanceAs s.single
    }

    it("singl scheduler") {
      val cdl = new CountDownLatch(2)
      val start = System.currentTimeMillis()
      s.single.schedule(() => cdl.countDown(), 1, 1, TimeUnit.SECONDS)
      cdl.await()
      val end = System.currentTimeMillis()
      end - start should be(2000L +- 100L)
    }

    it("singl scheduler / wait next command") {
      val cdl = new CountDownLatch(4)
      val start = System.currentTimeMillis()

      s.single.schedule(() => {
        Thread.sleep(1000) // heavy job
        cdl.countDown()
      }, 1, 1, TimeUnit.SECONDS)

      s.single.schedule(() => cdl.countDown(), 1, 1, TimeUnit.SECONDS)
      cdl.await()
      val end = System.currentTimeMillis()
      end - start should be(4000L +- 100L)
    }
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:41,代码来源:SchedulerSpec.scala


示例9: SubscribeSignalSpec

//设置package包名称以及导入依赖的类
package knot.core.emitters

import java.util.concurrent.{CountDownLatch, TimeUnit}

import knot.core.Signals.{Start, Subscribe}
import knot.core.Workbench
import knot.core.adapter.LocalAdapter
import knot.core.config.Configs
import knot.core.sources.IteratorSource
import knot.testKit.ThroughParser
import org.scalatest.{BeforeAndAfter, FunSpec}

class SubscribeSignalSpec extends FunSpec with BeforeAndAfter {
  implicit val wb: Workbench = Workbench.on("test")
  var ctl = new CountDownLatch(1)

  private def getTestEmitter: (LocalAdapter, LocalAdapter) = {
    val s = PublishEmitter[Int](wb, Configs.defaultPartConfig, IteratorSource(0 until 1))
    val p = ProcessEmitter[Int, Int](wb, Configs.defaultPartConfig, ThroughParser[Int](_ => ctl.countDown()))
    (LocalAdapter(s), LocalAdapter(p))
  }

  before {
    ctl = new CountDownLatch(1)
  }

  describe("subscribe signal") {
    it("source subscribe -> start") {
      val te = getTestEmitter
      te._1.send(Subscribe(te._2))
      Thread.sleep(100)
      te._1.send(Start)
      ctl.await(10, TimeUnit.SECONDS)
    }

    it("source start -> subscribe") {
      val te = getTestEmitter
      te._1.send(Start)
      Thread.sleep(100)
      te._1.send(Subscribe(te._2))
      ctl.await(10, TimeUnit.SECONDS)
    }

    it("parser start -> subscribe") {
      val te = getTestEmitter
      te._1.send(Start)
      te._2.send(Start)
      Thread.sleep(100)
      te._1.send(Subscribe(te._2))
      ctl.await(10, TimeUnit.SECONDS)
    }
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:54,代码来源:SubscribeSignalSpec.scala


示例10: withFixture

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

import java.util.concurrent.CountDownLatch
import javafx.application.Platform
import org.scalatest.{Outcome, TestSuite, TestSuiteMixin}

trait RunOnApplicationThread extends TestSuiteMixin {
  this: TestSuite =>
  abstract override def withFixture(test: NoArgTest): Outcome = {
    BootstrapApplication.launch()
    val appThreadLatch = new CountDownLatch(1)
    val superWith = super.withFixture _  // required to access to super withFixture method from within runnable for a trait
    var testException: Exception = null
    var outcome: Outcome = null
    Platform.runLater(new Runnable() {
      override def run() {
        try {
          outcome = superWith(test)
        } catch {
          case e: Exception => testException = e
        } finally {
          appThreadLatch.countDown()
        }
      }
    })
    appThreadLatch.await()
    if (testException != null) {
      throw testException
    }
    outcome
  }
} 
开发者ID:haraldmaida,项目名称:ScalaTestFX,代码行数:33,代码来源:RunOnApplicationThread.scala


示例11: BootstrapApplication

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

import java.util.concurrent.CountDownLatch
import javafx.application.Application
import javafx.stage.Stage

object BootstrapApplication {
  private val launchLatch = new CountDownLatch(1)
  var launched = false
  def launch() {
    if (!launched) {
      new Thread(new Runnable() {
        def run() {
          Application.launch(classOf[BootstrapApplication])
        }
      }).start()
      launchLatch.await()
      launched = true
    }
  }
}

class BootstrapApplication extends Application {
  override def start(stage: Stage) {
    BootstrapApplication.launchLatch.countDown()
  }
} 
开发者ID:haraldmaida,项目名称:ScalaTestFX,代码行数:28,代码来源:BootstrapApplication.scala


示例12: SyncManagerTest

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.tests.sync

import java.util.concurrent.{CountDownLatch, TimeUnit}

import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.sync.SyncType.SyncType
import com.flipkart.connekt.commons.sync.{SyncDelegate, SyncManager, SyncMessage, SyncType}
import com.flipkart.connekt.commons.tests.ConnektUTSpec

class SyncManagerTest extends ConnektUTSpec with SyncDelegate {

  "Sync operation" should "sync" in {
    SyncManager.create("127.0.0.1:2181")
    //Subscribe to the NF
    SyncManager.get().addObserver(this, List(SyncType.TEMPLATE_CHANGE))
    SyncManager.get().publish(SyncMessage(SyncType.TEMPLATE_CHANGE, List("Hello via Curator", "Hello via Zookeeper" + System.currentTimeMillis())))
    noException should be thrownBy  SyncTestVariables.lock.await(120, TimeUnit.SECONDS)
    assert(null != SyncTestVariables.receivedData )
  }

  override def onUpdate(_type: SyncType, args: List[AnyRef]): Any = {
    ConnektLogger(LogFile.SERVICE).info("Recieved Async [" + _type + "] with data " + args)
    SyncTestVariables.receivedData = args
    SyncTestVariables.lock.countDown()
  }
}

object SyncTestVariables {

  
  val lock = new CountDownLatch(1)
  var receivedData: Any = null

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:35,代码来源:SyncManagerTest.scala


示例13: ChanTest

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

import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import java.util.concurrent.CyclicBarrier
import scala.collection.mutable.Buffer
import java.util.concurrent.CountDownLatch

@RunWith(classOf[JUnitRunner])
class ChanTest extends FunSuite {
  test("Proc should admit one at a time, in the order received, queueing items") {
    val threads = Buffer[Thread]()
    val l = new CountDownLatch(1)
    val b = new CyclicBarrier(2)

    val p = Proc[Thread] { t => threads += t; l.countDown(); b.await() }

    val t0 = new Thread {
      override def run() {
        p ! this
      }
    }

    val t1 = new Thread {
      override def run() {
        l.await()
        p ! this
        b.await()
        b.await()
      }
    }

    t0.start();
    t1.start()
    t0.join();
    t1.join()

    assert(threads.toSeq == Seq(t0, t1))
  }

  test("Proc should swallow exceptions") {
    val p = Proc[Int] { _ => throw new RuntimeException }
    assert((p ! 4) ===((): Unit))
  }

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


示例14: UpdaterTest

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

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import java.util.concurrent.{CyclicBarrier, CountDownLatch}

@RunWith(classOf[JUnitRunner])
class UpdaterTest extends FunSuite {
  test("Prioritization") {
    case class Work(p: Int)
    @volatile var worked: Seq[Work] = Nil
    val barrier = new CyclicBarrier(2)
    val first = new CountDownLatch(1)

    val u = new Updater[Work] {
      protected def preprocess(elems: Seq[Work]) =
        Seq(elems.minBy(_.p))

      def handle(w: Work) {
        worked :+= w
        first.countDown()
        barrier.await()
        ()
      }
    }

    val w0 = Work(0)
    val thr = new Thread("Test-Updater") {
      override def run() {
        u(w0)
      }
    }

    thr.start()
    first.await()
    assert(worked == Seq(Work(0)))

    u(Work(3))
    u(Work(10))
    u(Work(1))
    u(Work(3))
    barrier.await()
    barrier.await()
    thr.join()
    assert(worked == Seq(Work(0), Work(1)))
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:49,代码来源:UpdaterTest.scala


示例15: Yolo

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

import eveapi.oauth._
import OAuth2._
import scalaz._, Scalaz._
import scalaz.concurrent.Task
import eveapi.errors._
import org.http4s._, org.http4s.dsl._
import org.http4s.server.Server
import org.http4s.server.blaze._
import org.atnos.eff._, org.atnos.eff.syntax.all._, org.atnos.eff.all._
import java.time.Clock
import java.util.concurrent.CountDownLatch

case class Yolo(oauth: OAuth2, token: OAuth2Token) {
  def run[T](api: Api[T]): T = Yolo.deeff(api).run((oauth, token)).unsafePerformSync.leftMap(err => throw err).merge
  def run[T](free: Free[Lift.Link, T]): T = Yolo.deeff(free.foldMap(Execute.OAuthInterpreter)).run((oauth, token)).unsafePerformSync.leftMap(err => throw err).merge
}

object Yolo {
  def deeff[T](api: Api[T]): Reader[(OAuth2, OAuth2Token), Task[\/[EveApiError, T]]] =
    Reader({case (oauth, token) =>
      Eff.detach[Task, \/[EveApiError, T]](api.runReader[OAuth2](oauth).runState(token).map(_._1).runDisjunction)
    })

  val client = org.http4s.client.blaze.PooledHttp1Client()
  val seed = new java.security.SecureRandom().nextLong
  val clock = Clock.systemUTC()

  def oauth2(callback: Uri, clientId: String, clientSecret: String, scope: String): OAuth2 = OAuth2(client,
    OAuth2Settings(
      Uri.uri("https://login.eveonline.com/oauth/authorize"),
      Uri.uri("https://login.eveonline.com/oauth/token"),
      callback,
      Uri.uri("https://login.eveonline.com/oauth/verify"),
      clientId,
      clientSecret,
      Uri.uri("https://login.eveonline.com/oauth/token"),
      Some(scope)
    ), OAuth2State(seed), clock, OAuth2ClientSettings("login"))

  // Thanks to @rossabaker
  def genToken(oauth: OAuth2): Task[Yolo] =
    Task.async[Yolo]({ k =>
      val latch = new CountDownLatch(1)
      val service = oauth.oauthService({
        token => k(\/-(Yolo(oauth, token))); Ok("Done.").map({x =>latch.countDown(); x})
      })
      val port = oauth.settings.callbackUri.port.getOrElse(80)
      val server: Server = BlazeBuilder.mountService(Kleisli(service).local({x => println(x); x})).bindHttp(port, "localhost").run
      println(s"Go to http://localhost:${port}/login")
      latch.await()
      server.shutdown.unsafePerformSync
    })
} 
开发者ID:scala-eveapi,项目名称:eveapi,代码行数:56,代码来源:yolo.scala


示例16: VideoTranscoderTest

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

import java.io.File
import java.util.concurrent.CountDownLatch

import android.content.Context
import android.net.Uri
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.waz.api.AssetFactory.LoadCallback
import com.waz.api.{AssetFactory, AssetForUpload}
import com.waz.bitmap.video.VideoTranscoder
import com.waz.service.ZMessaging
import com.waz.threading.Threading
import org.junit.runner.RunWith
import org.junit.{Assert, Before, Test}

import scala.concurrent.Await
import scala.concurrent.duration._

@RunWith(classOf[AndroidJUnit4])
class VideoTranscoderTest {

  @Before def setUp(): Unit = {
    Threading.AssertsEnabled = false
    ZMessaging.onCreate(context)
  }

  @Test def audioTranscodingFrom8kHz(): Unit = {
    val transcoder = VideoTranscoder(context)
    val out = File.createTempFile("video", ".mp4", context.getCacheDir)

    val future = transcoder(Uri.parse("content://com.waz.test/8khz.mp4"), out, { _ => })

    Assert.assertEquals(out, Await.result(future, 15.seconds))
  }

  @Test def assetLoadingWithNoAudio(): Unit = {
    val latch = new CountDownLatch(1)
    var asset = Option.empty[AssetForUpload]

    AssetFactory.videoAsset(Uri.parse("content://com.waz.test/no_audio.mp4"), new LoadCallback {
      override def onLoaded(a: AssetForUpload): Unit = {
        asset = Some(a)
        latch.countDown()

      }
      override def onFailed(): Unit = {
        println(s"transcode failed")
        latch.countDown()
      }
    })

    latch.await()
    Assert.assertTrue(asset.isDefined)
  }

  def context: Context = instr.getTargetContext
  def instr = InstrumentationRegistry.getInstrumentation
} 
开发者ID:wireapp,项目名称:wire-android-sync-engine,代码行数:61,代码来源:VideoTranscoderTest.scala


示例17: TestSpec

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

import java.util.concurrent.CountDownLatch

import com.ecfront.ez.framework.core.test.BasicSpec
import com.mdataset.lib.basic.model.MdsCollectStatusDTO
import com.mdataset.lib.worker.basic.MdsWorkerBasicContext
import com.mdataset.lib.worker.basic.exchange.MdsMockAPIExchangeWorker
import com.mdataset.worker.test.ServiceAdapter


class TestSpec extends BasicSpec {

  test("Test Test") {
    com.mdataset.lib.worker.basic.MdsWorkerBasicContext.apiExchangeWorker=MdsMockAPIExchangeWorker
    com.mdataset.lib.worker.basic.MdsStartup.init(ServiceAdapter)
    MdsWorkerBasicContext.source.items.foreach {
      item =>
        val status = new MdsCollectStatusDTO
        ServiceAdapter.collectExec(item.item_code, item, status)
    }
    new CountDownLatch(1).await()
  }
} 
开发者ID:MDataSet,项目名称:mds,代码行数:25,代码来源:TestSpec.scala


示例18: SocketSpec

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

import java.util.concurrent.CountDownLatch

import com.ecfront.ez.framework.core.EZContext
import io.vertx.core.buffer.Buffer
import io.vertx.core.net.NetSocket
import io.vertx.core.{AsyncResult, Handler}

class SocketSpec extends MockStartupSpec {

  test("Socket Test") {
    EZContext.vertx.createNetClient()
      .connect(MdsContext.socketPort, MdsContext.socketHost, new Handler[AsyncResult[NetSocket]] {
        override def handle(event: AsyncResult[NetSocket]): Unit = {
          val socket = event.result()
          socket.handler(new Handler[Buffer] {
            override def handle(event: Buffer): Unit = {
              val data = event.getString(0, event.length())
              println(data)
            }
          })
          socket.write("test")
        }
      })
    new CountDownLatch(1).await()
  }
} 
开发者ID:MDataSet,项目名称:mds,代码行数:29,代码来源:SocketSpec.scala


示例19: SingleNodeRunnerTests

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

import java.util.concurrent.{CountDownLatch, TimeUnit}

import com.bwsw.imp.activity.{Activity, Environment}
import com.bwsw.imp.event.Event
import org.scalatest.{FlatSpec, Matchers}


class SingleNodeRunnerTests extends FlatSpec with Matchers {
  it should "run and stop properly" in {
    val runner = new SingleNodeRunner
    runner.start()
    runner.stop()
  }

  it should "get message and transform it to activity" in {
    val latch = new CountDownLatch(1)
    val runner = new SingleNodeRunner
    runner.start()
    runner.registerActivityMatcher((environment: Environment, event: Event) => List(new Activity {
      override def activate(e: Environment): Seq[Activity] = {
        latch.countDown()
        Nil
      }
    }))
    runner.getEventQueue().put(new Event {})
    latch.await(10, TimeUnit.SECONDS) shouldBe true
    runner.stop()
  }
} 
开发者ID:bwsw,项目名称:imp,代码行数:32,代码来源:SingleNodeRunnerTests.scala


示例20: SubscriptionAction

//设置package包名称以及导入依赖的类
package de.tu_berlin.formic.gatling.action

import java.util.concurrent.{CountDownLatch, TimeUnit}

import de.tu_berlin.formic.client.FormicSystem
import de.tu_berlin.formic.common.DataStructureInstanceId
import de.tu_berlin.formic.common.datastructure.FormicDataStructure
import io.gatling.commons.util.TimeHelper
import io.gatling.core.action.{Action, ChainableAction}
import io.gatling.core.session.{Expression, Session}
import io.gatling.core.stats.StatsEngine

import scala.concurrent.Promise
import scala.util.{Failure, Success}


case class SubscriptionAction(dataTypeInstanceId: Expression[String], statsEngine: StatsEngine, next: Action) extends ChainableAction {

  override def name: String = "Subscription action"

  override def execute(session: Session): Unit = {
    val start = TimeHelper.nowMillis
    val formicSystemOption = session(SessionVariables.FORMIC_SYSTEM).asOption[FormicSystem]
    val validatedDataTypeInstanceId = dataTypeInstanceId.apply(session)
    validatedDataTypeInstanceId.foreach { id =>
      formicSystemOption match {

        case Some(formicSystem) =>
          formicSystem.requestDataType(DataStructureInstanceId.valueOf(id))

          val callback = session(SessionVariables.CALLBACK).validate[CollectingCallbackWithListener].get //when the FormicSystem is present, this one must be, too
          val promise = Promise[FormicDataStructure]()
          val latch = new CountDownLatch(1)
          val callbackMethod = (d: FormicDataStructure) => {
            val suc = promise success d
            latch.countDown()
            suc
          }
          val callbackCondition = (d: FormicDataStructure) => d.dataStructureInstanceId == DataStructureInstanceId.valueOf(id)
          callback.addListener(callbackCondition, callbackMethod)
          //gotta block here, because the session is immutable
          latch.await(10, TimeUnit.SECONDS)
          promise.future.value match {
            case None =>
              FormicActions.logKoTimingValues(start, TimeHelper.nowMillis, session, statsEngine, name)
              next ! session
            case Some(Failure(ex)) =>
              FormicActions.logKoTimingValues(start, TimeHelper.nowMillis, session, statsEngine, name)
              throw ex
            case Some(Success(string)) =>
              val modifiedSession = session.set(id, string)
              FormicActions.logOkTimingValues(start, TimeHelper.nowMillis, session, statsEngine, name)
              next ! modifiedSession
          }
        case None => throw new IllegalArgumentException("Users have to connect first!")
      }
    }
  }
} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:60,代码来源:SubscriptionAction.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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