scala.concurrent.Awaitable Scala Examples
The following examples show how to use scala.concurrent.Awaitable.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: DexExtensionGrpcConnector.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.tool.connectors import cats.instances.future._ import cats.instances.list._ import cats.syntax.either._ import cats.syntax.traverse._ import ch.qos.logback.classic.{Level, Logger} import com.wavesplatform.dex.cli.ErrorOr import com.wavesplatform.dex.domain.account.Address import com.wavesplatform.dex.domain.asset.Asset import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves} import com.wavesplatform.dex.grpc.integration.WavesBlockchainClientBuilder import com.wavesplatform.dex.grpc.integration.clients.WavesBlockchainClient import com.wavesplatform.dex.grpc.integration.dto.BriefAssetDescription import com.wavesplatform.dex.grpc.integration.settings.GrpcClientSettings.ChannelOptionsSettings import com.wavesplatform.dex.grpc.integration.settings.{GrpcClientSettings, WavesBlockchainClientSettings} import monix.execution.Scheduler.Implicits.{global => monixScheduler} import org.slf4j.LoggerFactory import scala.concurrent.ExecutionContext.Implicits.{global => executionContext} import scala.concurrent.duration._ import scala.concurrent.{Await, Awaitable, Future} import scala.util.Try case class DexExtensionGrpcConnector private (target: String, grpcAsyncClient: WavesBlockchainClient[Future]) extends Connector { import DexExtensionGrpcConnector._ private def sync[A](f: Awaitable[A]): A = Await.result(f, requestTimeout) private def getDetailedBalance(asset: Asset, balance: Long): Future[(Asset, (BriefAssetDescription, Long))] = asset match { case Waves => Future.successful(asset -> (BriefAssetDescription.wavesDescription -> balance)) case ia: IssuedAsset => grpcAsyncClient.assetDescription(ia).map(maybeDesc => ia -> (maybeDesc.get -> balance)) } def matcherBalanceAsync(address: Address): Future[DetailedBalance] = for { balances <- grpcAsyncClient.allAssetsSpendableBalance(address) balancesWithDescription <- balances.toList.traverse { case (a, b) => getDetailedBalance(a, b) } } yield balancesWithDescription.toMap def matcherBalanceSync(address: Address): DetailedBalance = sync { matcherBalanceAsync(address) } override def close(): Unit = Await.result(grpcAsyncClient.close(), 3.seconds) } object DexExtensionGrpcConnector { val requestTimeout: FiniteDuration = 10.seconds type DetailedBalance = Map[Asset, (BriefAssetDescription, Long)] def create(target: String): ErrorOr[DexExtensionGrpcConnector] = Try { LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger].setLevel(Level.OFF) val grpcSettings = GrpcClientSettings(target, 5, 5, true, 2.seconds, 5.seconds, 1.minute, ChannelOptionsSettings(5.seconds)) val clientSettings = WavesBlockchainClientSettings(grpcSettings, 100.milliseconds, 100) WavesBlockchainClientBuilder.async(clientSettings, monixScheduler, executionContext) }.toEither .bimap(ex => s"Cannot establish gRPC connection to DEX Extension! $ex", client => DexExtensionGrpcConnector(target, client)) }
Example 2
Source File: ConsulCoordinationSpec.scala From constructr-consul with Apache License 2.0 | 5 votes |
package com.tecsisa.constructr.coordination.consul import akka.Done import akka.actor.{ ActorSystem, AddressFromURIString } import akka.testkit.{ TestDuration, TestProbe } import com.typesafe.config.ConfigFactory import org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpec } import scala.concurrent.duration.{ Duration, DurationInt, FiniteDuration } import scala.concurrent.{ Await, Awaitable } import scala.util.Random object ConsulCoordinationSpec { private val coordinationHost = { val dockerHostPattern = """tcp://(\S+):\d{1,5}""".r sys.env .get("DOCKER_HOST") .collect { case dockerHostPattern(address) => address } .getOrElse("127.0.0.1") } } class ConsulCoordinationSpec extends WordSpec with Matchers with BeforeAndAfterAll { import ConsulCoordinationSpec._ private implicit val system = { val config = ConfigFactory .parseString(s"constructr.coordination.host = $coordinationHost") .withFallback(ConfigFactory.load()) ActorSystem("default", config) } private val address1 = AddressFromURIString("akka.tcp://default@a:2552") private val address2 = AddressFromURIString("akka.tcp://default@b:2552") "ConsulCoordination" should { "correctly interact with consul" in { val coordination = new ConsulCoordination(randomString(), system) // Getting nodes resultOf(coordination.getNodes()) shouldBe 'empty // Lock (ttl >= 10s) resultOf(coordination.lock(address1, 10.seconds)) shouldBe true resultOf(coordination.lock(address1, 10.seconds)) shouldBe true resultOf(coordination.lock(address2, 10.seconds)) shouldBe false // Add self resultOf(coordination.addSelf(address1, 10.seconds)) shouldBe Done resultOf(coordination.getNodes()) shouldBe Set(address1) // Refresh resultOf(coordination.refresh(address1, 10.seconds)) shouldBe Done resultOf(coordination.getNodes()) shouldBe Set(address1) val probe = TestProbe() import probe._ awaitAssert( resultOf(coordination.getNodes()) shouldBe 'empty, 25.seconds // Wait until open sessions expire ) } } override protected def afterAll() = { Await.ready(system.terminate(), Duration.Inf) super.afterAll() } private def resultOf[A](awaitable: Awaitable[A], max: FiniteDuration = 3.seconds.dilated) = Await.result(awaitable, max) private def randomString() = math.abs(Random.nextInt).toString }
Example 3
Source File: AwaitUtils.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.util import scala.concurrent.{Await, Awaitable} object AwaitUtils { def await[T](awaitable: Awaitable[T]): T = { import scala.concurrent.duration._ Await.result(awaitable, 5.seconds) } implicit class AwaitableExtension[T](awaitable: Awaitable[T]) { import scala.concurrent.duration._ def await: T = { Await.result(awaitable, 5.seconds) } } }
Example 4
Source File: GraphQlClientSpec.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.graphql import org.scalatest.{FlatSpec, Matchers} import scala.concurrent.{Await, Awaitable} class GraphQlClientSpec extends FlatSpec with Matchers { import cool.graph.stub.Import._ import scala.concurrent.ExecutionContext.Implicits.global val stub = Request("POST", "/graphql-endpoint").stub(200, """{"data": {"id": "1234"}}""").ignoreBody "sendQuery" should "send the correct the correct JSON structure to the server" in { withStubServer(List(stub)).withArg { server => val uri = s"http://localhost:${server.port}${stub.path}" val client = GraphQlClient(uri) val query = """ { mutation { createTodo(title:"the title"){id} }} """ val result = await(client.sendQuery(query)) val expectedBody = s"""{"query":"${escapeQuery(query)}"}""" server.lastRequest.body should equal(expectedBody) result.status should equal(stub.stubbedResponse.status) result.body should equal(stub.stubbedResponse.body) } } "sendQuery" should "send the specified headers to the server" in { withStubServer(List(stub)).withArg { server => val uri = s"http://localhost:${server.port}${stub.path}" val header1 = "Header1" -> "Header1Value" val header2 = "Header2" -> "Header2Value" val headers = Map(header1, header2) val client = GraphQlClient(uri, headers) val query = """ { mutation { createTodo(title:"the title"){id} }} """ val result = await(client.sendQuery(query)) server.lastRequest.headers should contain(header1) server.lastRequest.headers should contain(header2) result.status should equal(stub.stubbedResponse.status) result.body should equal(stub.stubbedResponse.body) } } def escapeQuery(query: String) = query.replace("\"", "\\\"") def await[T](awaitable: Awaitable[T]): T = { import scala.concurrent.duration._ Await.result(awaitable, 5.seconds) } }
Example 5
Source File: EtcdCoordinationSpec.scala From constructr with Apache License 2.0 | 5 votes |
package de.heikoseeberger.constructr.coordination.etcd import akka.Done import akka.actor.{ ActorSystem, AddressFromURIString } import akka.testkit.{ TestDuration, TestProbe } import com.typesafe.config.ConfigFactory import org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpec } import scala.concurrent.duration.{ Duration, DurationInt, FiniteDuration } import scala.concurrent.{ Await, Awaitable } import scala.util.Random object EtcdCoordinationSpec { private val coordinationHost = { val dockerHostPattern = """tcp://(\S+):\d{1,5}""".r sys.env .get("DOCKER_HOST") .collect { case dockerHostPattern(address) => address } .getOrElse("127.0.0.1") } } class EtcdCoordinationSpec extends WordSpec with Matchers with BeforeAndAfterAll { import EtcdCoordinationSpec._ private implicit val system = { val config = ConfigFactory .parseString(s"constructr.coordination.host = $coordinationHost") .withFallback(ConfigFactory.load()) ActorSystem("default", config) } private val address = AddressFromURIString("akka.tcp://default@a:2552") private val address2 = AddressFromURIString("akka.tcp://default@b:2552") "EtcdCoordination" should { "correctly interact with etcd" in { val coordination = new EtcdCoordination(randomString(), system) resultOf(coordination.getNodes()) shouldBe 'empty resultOf(coordination.lock(address, 10.seconds.dilated)) shouldBe true resultOf(coordination.lock(address, 10.seconds.dilated)) shouldBe true resultOf(coordination.lock(address2, 10.seconds.dilated)) shouldBe false resultOf(coordination.addSelf(address, 10.seconds.dilated)) shouldBe Done resultOf(coordination.getNodes()) shouldBe Set(address) resultOf(coordination.refresh(address, 1.second.dilated)) shouldBe Done resultOf(coordination.getNodes()) shouldBe Set(address) val probe = TestProbe() probe.within(5.seconds.dilated) { // 2 seconds should be enough, but who knows hows ... probe.awaitAssert { resultOf(coordination.getNodes()) shouldBe 'empty } } } } override protected def afterAll() = { Await.ready(system.terminate(), Duration.Inf) super.afterAll() } private def resultOf[A](awaitable: Awaitable[A], max: FiniteDuration = 3.seconds.dilated) = Await.result(awaitable, max) private def randomString() = math.abs(Random.nextInt).toString }