本文整理汇总了Scala中scala.concurrent.Await类的典型用法代码示例。如果您正苦于以下问题:Scala Await类的具体用法?Scala Await怎么用?Scala Await使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Await类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: MongoDBSink
//设置package包名称以及导入依赖的类
package com.jetprobe.fastgen.io
import org.mongodb.scala.bson.BsonDocument
import org.mongodb.scala.{Completed, MongoClient, MongoCollection, Observer}
import org.mongodb.scala.bson.collection.mutable.Document
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
case class MongoDBSink(db: String, collection: String, host: String)
extends DataSink {
import MongoDBSink._
override def write(data: Array[String]): Unit = {
val collection = getCollection(this)
data
.grouped(1000)
.foreach(docs => {
val observable =
collection.insertMany(docs.map(str => Document(BsonDocument(str))))
Await.result(observable.head(), 10 seconds)
})
logger.info(s"Total docs inserted : ${data.length}")
}
}
object MongoDBSink {
import org.json4s._
import org.json4s.jackson.JsonMethods._
def apply(uri: String): MongoDBSink = {
val splitUri = uri.substring(10).split("/")
val hostname = "mongodb://" + splitUri(0)
val database = splitUri(1)
val collection = splitUri(2).split("\\?")(0)
MongoDBSink(database, collection, hostname)
}
def getCollection(mongo: MongoDBSink): MongoCollection[Document] = {
val mongoClient = MongoClient(mongo.host)
mongoClient.getDatabase(mongo.db).getCollection(mongo.collection)
}
def jsonStrToMap(jsonStr: String): Map[String, Any] = {
implicit val formats = org.json4s.DefaultFormats
parse(jsonStr).extract[Map[String, Any]]
}
}
示例2: beforeAll
//设置package包名称以及导入依赖的类
package placeholder.base
import java.net.InetSocketAddress
import com.twitter.finagle
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import org.scalatest._
import placeholder.Main
import scala.concurrent.Await
import scala.concurrent.duration._
trait IntegrationTestBase extends FeatureSpec with GivenWhenThen with Matchers with BeforeAndAfterAll {
val server = Main
var serverAddress: InetSocketAddress = _
var client: Service[Request, Response] = _
var requestHost: String = _
server.main(Array())
override def beforeAll(): Unit = {
serverAddress = Await.result(server.getServerAddress, 10.seconds)
requestHost = s"localhost:${serverAddress.getPort.toString}"
client = finagle.Http.newService(requestHost)
}
def performRequest(request: Request): Future[Response] = {
request.host = requestHost
client(request)
}
}
示例3: ProcessorHierarchySpec
//设置package包名称以及导入依赖的类
package akka.stream
import akka.stream.testkit.AkkaSpec
import akka.stream.scaladsl.Flow
import akka.actor.ActorContext
import scala.concurrent.Await
import scala.concurrent.duration._
import akka.actor.ActorRef
import scala.collection.immutable.TreeSet
import scala.util.control.NonFatal
import akka.stream.impl.ActorBasedFlowMaterializer
class ProcessorHierarchySpec extends AkkaSpec("akka.actor.debug.lifecycle=off\nakka.loglevel=INFO") {
val materializer = FlowMaterializer(MaterializerSettings())
def self = ActorBasedFlowMaterializer.currentActorContext().self
"An ActorBasedFlowMaterializer" must {
"generate the right level of descendants" in {
val f = Flow(() ? {
testActor ! self
Flow(List(1)).map(x ? { testActor ! self; x }).toProducer(materializer)
}).take(3).foreach(x ? {
testActor ! self
Flow(x).foreach(_ ? testActor ! self).consume(materializer)
}).toFuture(materializer)
Await.result(f, 3.seconds)
val refs = receiveWhile(idle = 250.millis) {
case r: ActorRef ? r
}
try {
refs.toSet.size should be(8)
refs.distinct.map(_.path.elements.size).groupBy(x ? x).mapValues(x ? x.size) should be(Map(2 -> 2, 3 -> 6))
} catch {
case NonFatal(e) ?
println(refs.map(_.toString).to[TreeSet].mkString("\n"))
throw e
}
}
}
}
示例4: ConstructorsPopulationSpec
//设置package包名称以及导入依赖的类
package com.github.astonbitecode.di
import java.util.concurrent.TimeUnit
import scala.concurrent.Await
import scala.concurrent.duration.FiniteDuration
import org.junit.runner.RunWith
import org.specs2.mutable
import org.specs2.runner.JUnitRunner
import org.specs2.specification.BeforeEach
@RunWith(classOf[JUnitRunner])
class ConstructorsPopulationSpec extends mutable.Specification with BeforeEach {
val timeout = FiniteDuration(1000, TimeUnit.MILLISECONDS)
override def before() {
TestUtil.clean
}
sequential
"A spec for the Constructors population in the DI ".txt
"A constructor should be populated in the DI" >> {
val f = diDefine { () => MyInjectableClass("One") }
Await.result(f, timeout)
cache must haveSize(1)
}
"A constructor should be replaced in the DI if it already exists" >> {
val f1 = diDefine { () => MyInjectableClass("One") }
Await.result(f1, timeout)
val f2 = diDefine { () => MyInjectableClass("Two") }
Await.result(f2, timeout)
cache must haveSize(1)
cache.head._2.constructor.apply().asInstanceOf[MyInjectableClass].id === "Two"
}
"A constructor with scope SINGLETON_EAGER should create the instance upon the call" >> {
val f = diDefine(() => MyInjectableClass("One"), DIScope.SINGLETON_EAGER)
Await.result(f, timeout)
cache must haveSize(1)
cache.head._2.cachedInstance.isDefined === true
}
"A constructor with scope SINGLETON_LAZY should not create the instance upon the call" >> {
val f = diDefine(() => MyInjectableClass("One"), DIScope.SINGLETON_LAZY)
Await.result(f, timeout)
cache must haveSize(1)
cache.head._2.cachedInstance.isDefined === false
}
case class MyInjectableClass(id: String)
}
示例5: FileSourceSpec
//设置package包名称以及导入依赖的类
package knot.core.sources
import java.nio.charset.StandardCharsets.UTF_8
import java.nio.file.Files
import knot.core.collectors.Last
import knot.core.{Knot, Workbench}
import knot.data.ByteNode
import knot.testKit.ThroughParser
import org.scalatest.Matchers._
import org.scalatest.{BeforeAndAfter, FunSpec}
import scala.concurrent.Await
import scala.concurrent.duration.Duration
class FileSourceSpec extends FunSpec with BeforeAndAfter {
implicit val wb: Workbench = Workbench.on("test")
private val testText = {
("a" * 513) +
("b" * 513) +
("c" * 513)
}
private val testFile = {
val f = Files.createTempFile("file-source-spec", ".tmp")
Files.newBufferedWriter(f, UTF_8).append(testText).close()
f
}
private def test(): Seq[String] = {
var actual = Seq[String]()
val f = Knot
.from(FileSource(testFile, 512, 5))
.to(ThroughParser[ByteNode](e => actual = actual :+ e.utf8String))
.start(Last[ByteNode]())
Await.result(f, Duration.Inf)
actual
}
after {
Files.delete(testFile)
}
describe("file source") {
it("file") {
val actual = test()
actual should be(Seq(
"a" * 512,
"a" + ("b" * 511),
"bb" + ("c" * 510),
"ccc"
))
}
}
}
示例6: UnMarshalling
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{HttpMethods, HttpRequest, HttpResponse, MessageEntity}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.{ActorMaterializer, Materializer}
import akka.util.ByteString
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import spray.json._
object UnMarshalling {
def main(args: Array[String]) {
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
//type FromStringUnmarshaller[T] = Unmarshaller[String, T]
val intFuture = Unmarshal("42").to[Int]
val int = Await.result(intFuture, 1.second)
println("int unmarshalling "+int)
//type FromStringUnmarshaller[T] = Unmarshaller[String, T]
val boolFuture = Unmarshal("off").to[Boolean]
val bool = Await.result(boolFuture, 1.second)
println("off unmarshalling "+bool)
//type ToEntityMarshaller[T] = Marshaller[T, MessageEntity]
val string = "Yeah"
val entityFuture = Marshal(string).to[MessageEntity]
val entity = Await.result(entityFuture, 1.second) // don't block in non-test code!
println(entity)
//type ToResponseMarshaller[T] = Marshaller[T, HttpResponse]
val errorMsg = "Not found, pal!"
val responseFuture = Marshal(404 -> errorMsg).to[HttpResponse]
val response = Await.result(responseFuture, 1.second)
println(response)
//type FromEntityUnmarshaller[T] = Unmarshaller[HttpEntity, T]
val jsonByteString = ByteString("""{"name":"Hello"}""")
val httpRequest = HttpRequest(HttpMethods.POST, entity = jsonByteString)
val jsonDataUnmarshalledFuture = Unmarshal(httpRequest).to[String]
val jsonDataUnmarshalled = Await.result(jsonDataUnmarshalledFuture, 1.second)
println(jsonDataUnmarshalled)
sys.terminate()
}
}
示例7: UserTokenDaoSpec
//设置package包名称以及导入依赖的类
package daos
import scala.concurrent.Await
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.test._
import play.api.test.Helpers._
import org.joda.time.DateTime
import org.specs2.mutable.Specification
import java.util.UUID
import scala.concurrent.Await
import scala.concurrent.duration.DurationInt
import models.UserToken
class UserTokenDaoSpec extends Specification {
val timeout = DurationInt(10).seconds
def fakeApp = FakeApplication(additionalConfiguration = Map("mongodb.uri" -> "mongodb://localhost:27017/test"))
def withUserTokenDao[T](t:UserTokenDao => T):T = running(fakeApp) {
val userTokenDao = new MongoUserTokenDao
Await.ready(userTokenDao.tokens.drop(), timeout)
t(userTokenDao)
}
val token = UserToken(id=UUID.randomUUID(), userId=UUID.randomUUID(), "[email protected]", new DateTime(), true)
"UserTokenDao" should {
"Persist and find a token" in withUserTokenDao { userTokenDao =>
val future = for {
_ <- userTokenDao.save(token)
maybeToken <- userTokenDao.find(token.id)
} yield maybeToken.map(_ == token)
Await.result(future, timeout) must beSome(true)
}
"Remove a token" in withUserTokenDao { userTokenDao =>
val future = for {
_ <- userTokenDao.save(token)
_ <- userTokenDao.remove(token.id)
maybeToken <- userTokenDao.find(token.id)
} yield maybeToken
Await.result(future, timeout) must beNone
}
}
}
示例8: ListenerSpec
//设置package包名称以及导入依赖的类
package akka.actor.routing
import akka.testkit._
import akka.actor._
import akka.actor.Actor._
import akka.routing._
import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.Await
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class ListenerSpec extends AkkaSpec {
"Listener" must {
"listen" in {
val fooLatch = TestLatch(2)
val barLatch = TestLatch(2)
val barCount = new AtomicInteger(0)
val broadcast = system.actorOf(Props(new Actor with Listeners {
def receive = listenerManagement orElse {
case "foo" ? gossip("bar")
}
}))
def newListener = system.actorOf(Props(new Actor {
def receive = {
case "bar" ?
barCount.incrementAndGet
barLatch.countDown()
case "foo" ?
fooLatch.countDown()
}
}))
val a1 = newListener
val a2 = newListener
val a3 = newListener
broadcast ! Listen(a1)
broadcast ! Listen(a2)
broadcast ! Listen(a3)
broadcast ! Deafen(a3)
broadcast ! WithListeners(_ ! "foo")
broadcast ! "foo"
Await.ready(barLatch, TestLatch.DefaultTimeout)
barCount.get should be(2)
Await.ready(fooLatch, TestLatch.DefaultTimeout)
for (a ? List(broadcast, a1, a2, a3)) system.stop(a)
}
}
}
示例9: Customer
//设置package包名称以及导入依赖的类
package model
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.BSONDocument
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
case class Customer(username:String,password:String,name:String,email:String,mobile:String)
case class Login(username:String,password:String)
class CustomerService {
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
val database = Await.result(connection.database("sonu"),10.seconds)
val collection= database.collection[BSONCollection]("customer")
def insert(username:String,password:String,name:String,email:String,mobile:String):String ={
try {
val document = BSONDocument("username" -> username, "password" -> password, "name" -> name,
"email" -> email, "mobile" -> mobile)
Await.result(collection.insert(document), 10.seconds)
"Inserted"
}
catch {
case error:Exception => "Duplicate"
}
}
def find(username:String,password:String):Boolean={
try {
val document = BSONDocument("username" -> username,"password" -> password)
val result = Await.result(collection.find(document).one[BSONDocument], 10.seconds)
if(result.isDefined) true else false
}
catch {
case error:Exception => false
}
}
}
object CustomerService extends CustomerService
示例10: PacketConsumer
//设置package包名称以及导入依赖的类
package edu.uw.at.iroberts.wirefugue.kafka.consumer
import akka.actor.ActorSystem
import akka.kafka.scaladsl.Consumer
import akka.kafka.{ConsumerSettings, Subscriptions}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Keep, Sink, Source}
import com.typesafe.config.ConfigFactory
import edu.uw.at.iroberts.wirefugue.kafka.producer.KafkaKey
import edu.uw.at.iroberts.wirefugue.kafka.serdes.{PacketDeserializer, PacketSerde}
import edu.uw.at.iroberts.wirefugue.pcap.Packet
import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
import org.apache.kafka.common.serialization.IntegerDeserializer
import scala.concurrent.Await
import scala.concurrent.duration._
object PacketConsumer extends App {
type PacketRecord = ConsumerRecord[KafkaKey, Array[Byte]]
val config = ConfigFactory.load("application.conf")
implicit val system = ActorSystem("stream-consumer-system", config)
implicit val materializer = ActorMaterializer()
val consumerSettings = ConsumerSettings(system, new IntegerDeserializer, new PacketDeserializer)
.withGroupId("group1")
.withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest")
// Separate streams for each partition
val maxPartitions = 100
val consumerGroup = Consumer.plainPartitionedSource(consumerSettings, Subscriptions.topics("packets"))
val done = consumerGroup.map {
case (topicPartition, source) =>
val p: Int = topicPartition.partition
source
.map { (cr: ConsumerRecord[Integer, Packet]) => cr.value() }
.filter(_.ip.isDefined)
.toMat(Sink.foreach(packet => println(s"[$p] $packet")))(Keep.both)
.run()
}
.mapAsyncUnordered(maxPartitions)(_._2)
.runWith(Sink.ignore)
Await.result(done, Duration.Inf)
system.terminate()
}
示例11: DatabaseInitializer
//设置package包名称以及导入依赖的类
package essentials.petstore.database
import slick.basic.DatabaseConfig
import slick.jdbc.meta.MTable
import slick.jdbc.JdbcProfile
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.duration._
import scala.concurrent.Await
class DatabaseInitializer(val dbConfig: DatabaseConfig[JdbcProfile], petsRepo: PetsRepository, recordsRepo: PetRecordsRepository) extends Db with LazyLogging {
import dbConfig.profile.api._
def initDatabaseTables(): Unit = {
logger.info("Setting up database")
// Get all existing tables
val tables = Await.result(db.run(MTable.getTables), 10 seconds)
val petsTableName = petsRepo.pets.baseTableRow.tableName
if (!tables.exists(existingTable => existingTable.name.name == petsTableName)) {
logger.info(s"Creating table '$petsTableName'")
Await.result(db.run(petsRepo.pets.schema.create), 10 seconds)
} else {
logger.info(s"Table '$petsTableName' already exists")
}
val recordsTableName = recordsRepo.records.baseTableRow.tableName
if (!tables.exists(existingTable => existingTable.name.name == recordsTableName)) {
logger.info(s"Creating table '$recordsTableName'")
Await.result(db.run(recordsRepo.records.schema.create), 10 seconds)
} else {
logger.info(s"Table '$recordsTableName' already exists")
}
logger.info("Finished setting up database")
}
}
示例12: ScheduleDownloadActor
//设置package包名称以及导入依赖的类
package logic.actors.schedule
import java.nio.charset.StandardCharsets
import javax.inject._
import akka.actor.{Actor, ActorRef}
import helpers.SpiritHelper
import logic.actors.schedule.ScheduleDownloadActor.DownloadSchedule
import logic.actors.schedule.ScheduleParseActor._
import org.fhs.spirit.scheduleparser.enumerations.EScheduleKind
import org.jsoup.Jsoup
import play.api.libs.ws.WSClient
import scala.collection.JavaConversions._
import scala.concurrent.Await
import scala.concurrent.duration._
@Singleton
class ScheduleDownloadActor @Inject()(ws: WSClient, @Named("parseActor") parseActor: ActorRef) extends Actor with SpiritHelper {
override def receive: Receive = {
case DownloadSchedule =>
val baseUrl = configuration.underlying.getString("schedule.baseUrl")
val lectureResults = uncachedCourseNames.map {
courseName =>
val outcome = "s_" + courseName + ".html"
val httpResult = Await.result(ws.url(baseUrl + outcome).get(), 10 seconds)
if (httpResult.status != 404) {
Some((httpResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString), courseName))
} else {
None
}
}.filter(_.nonEmpty).map(rs => (Jsoup.parse(rs.get._1).toString, rs.get._2)).map(rs => (EScheduleKind.REGULAR, rs))
val blockBaseResult = Await.result(ws.url(baseUrl + "bindex.html").get(), 10 seconds)
val bindex = Jsoup.parse(blockBaseResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString))
val blockRefs = bindex.select("a").map(_.attr("href")).toSet
val blockResult = blockRefs.map {
block =>
val httpResult = Await.result(ws.url(baseUrl + block).get(), 10 seconds)
if (httpResult.status != 404) {
Some((httpResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString), block))
} else {
None
}
}.filter(_.nonEmpty).map(rs => (Jsoup.parse(rs.get._1).toString, rs.get._2)).map(rs => (EScheduleKind.BLOCK, rs))
parseActor ! ParseSchedule(lectureResults ++ blockResult)
}
}
示例13: Hello
//设置package包名称以及导入依赖的类
package com.example
import redis.clients.jedis._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success}
import scalacache._
import scalacache.redis.RedisCache
import scala.concurrent.ExecutionContext.Implicits.global
object Hello {
def main(args: Array[String]): Unit = {
val jedis = new JedisPool("192.168.99.100", 6379)
implicit val scalaCache = ScalaCache(RedisCache(jedis))
jedis.getResource.set("key1", "foo")
import scalacache._
put("myKey")("myValue")
val myKey = get("myKey")
myKey.onComplete({
case Success(result) => println(result) // Some(myValue)
case Failure(t) => println(t.getMessage)
})
Await.ready(myKey, Duration.Inf)
put("key1")("foo")
val key1 = get("key1")
key1.onComplete({
case Success(result) => println(result) // null
case Failure(t) => println(t.getMessage)
})
Await.ready(key1, Duration.Inf)
val otherKey = get("other-key")
otherKey.onComplete({
case Success(result) => println(result) // None
case Failure(t) => println(t.getMessage)
})
Await.ready(otherKey, Duration.Inf)
println("Hello, world!")
}
}
示例14: EnvironmentCacheEntry
//设置package包名称以及导入依赖的类
package com.galacticfog.gestalt.lambda.impl
import java.util.concurrent.TimeoutException
import org.apache.mesos.Protos
import org.joda.time.DateTime
import scala.collection.mutable
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
case class EnvironmentCacheEntry( lambdaId : String, env : Protos.Environment, queuedTime : DateTime = DateTime.now )
class EnvironmentCache {
val cache : mutable.Map[String, EnvironmentCacheEntry] = mutable.Map[String, EnvironmentCacheEntry]()
val EXPIRATION_SECONDS = sys.env.getOrElse( "ENV_CACHE_EXPIRATION_SECONDS", "900" ).toInt
def getEnvironment( lambdaId : String, env : Future[Map[String,String]] ) : Protos.Environment = {
val cacheEntry = cache.get( lambdaId )
if( !cacheEntry.isDefined || cacheEntry.get.queuedTime.plusSeconds( EXPIRATION_SECONDS ).isBeforeNow ) {
//wait for the future
try {
val result = Await.result( env, 5 seconds )
val builder = Protos.Environment.newBuilder
result.foreach{ entry =>
builder.addVariables( Protos.Environment.Variable.newBuilder
.setName( entry._1 )
.setValue( entry._2 )
)
}
val newEnv = builder.build
cache( lambdaId ) = new EnvironmentCacheEntry( lambdaId, newEnv )
newEnv
}
catch {
case ex : TimeoutException => {
println( "TIMEOUT" )
Protos.Environment.newBuilder.build
}
}
}
else {
cache( lambdaId ).env
}
}
}
示例15: StreetEdge
//设置package包名称以及导入依赖的类
package tosidewalk.model
import tosidewalk.model.driver.MyPostgresDriver.api._
import com.vividsolutions.jts.{ geom => jtsg }
import scala.concurrent.Await
import scala.concurrent.duration.Duration
case class StreetEdge(streetEdgeId: Int, geom: jtsg.LineString, source: Option[Int], target: Option[Int]) {
def reverse: StreetEdge = {
StreetEdge(this.streetEdgeId, this.geom.reverse().asInstanceOf[jtsg.LineString], this.target, this.source)
}
}
class StreetEdgeTable(tag: Tag) extends Table[StreetEdge](tag, Some("pittsburgh"), "street_edge_small") {
def streetEdgeId = column[Int]("street_edge_id", O.AutoInc, O.PrimaryKey)
def geom = column[jtsg.LineString]("geom")
def source = column[Option[Int]]("source")
def target = column[Option[Int]]("target")
def * = (streetEdgeId, geom, source, target) <> (StreetEdge.tupled, StreetEdge.unapply)
}
object StreetEdgeTable {
val db = Database.forConfig("default")
val streetEdgeTable = TableQuery[StreetEdgeTable]
def selectStreets: List[StreetEdge] = {
Await.result(db.run(streetEdgeTable.result), Duration.Inf).toList
}
def updateStreetEdgeTarget(streetEdgeId: Int, streetNodeId: Int) = {
val q = for { r <- streetEdgeTable if r.streetEdgeId === streetEdgeId } yield r.target
val updateAction = q.update(Some(streetNodeId))
Await.result(db.run(updateAction), Duration.Inf)
}
}