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

Scala Await类代码示例

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

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



在下文中一共展示了Await类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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]]
  }
} 
开发者ID:amezng,项目名称:fastgen,代码行数:53,代码来源:MongoDBSink.scala


示例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)
  }
} 
开发者ID:scala-academy,项目名称:skeleton-project,代码行数:35,代码来源:IntegrationTestBase.scala


示例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
      }
    }

  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:46,代码来源:ProcessorHierarchySpec.scala


示例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)

} 
开发者ID:astonbitecode,项目名称:kind-of-di,代码行数:55,代码来源:ConstructorsPopulationSpec.scala


示例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"
      ))
    }
  }

} 
开发者ID:defvar,项目名称:knot,代码行数:59,代码来源:FileSourceSpec.scala


示例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()

  }

} 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:58,代码来源:UnMarshalling.scala


示例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       
    }
  }
} 
开发者ID:Viva-con-Agua,项目名称:drops,代码行数:51,代码来源:UserTokenDaoSpec.scala


示例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)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:58,代码来源:ListenerSpec.scala


示例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 
开发者ID:sonumehrotra,项目名称:MongoAssignment,代码行数:48,代码来源:Customer.scala


示例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()
} 
开发者ID:robertson-tech,项目名称:wirefugue,代码行数:50,代码来源:PacketConsumer.scala


示例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")
  }
} 
开发者ID:littlenag,项目名称:scala-essentials-petstore,代码行数:39,代码来源:DatabaseInitializer.scala


示例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)
  }
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:56,代码来源:ScheduleDownloadActor.scala


示例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!")
  }
} 
开发者ID:shigemk2,项目名称:my-scalacache-redis-sample,代码行数:40,代码来源:Hello.scala


示例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
    }
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:49,代码来源:EnvironmentCache.scala


示例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)
  }
} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:38,代码来源:StreetEdgeTable.scala


示例16: SidewalkEdgeStreetNode

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

import tosidewalk.model.driver.MyPostgresDriver.api._
import com.vividsolutions.jts.geom.Point

import scala.concurrent.Await
import scala.concurrent.duration.Duration


case class SidewalkEdgeStreetNode(sidewalkEdgeId: Int, streetNodeId: Int)

class SidewalkEdgeStreetNodeTable(tag: Tag) extends Table[SidewalkEdgeStreetNode](tag, Some("pittsburgh"), "sidewalk_edge_street_node") {
  def sidewalkEdgeId = column[Int]("sidewalk_edge_id")
  def streetNodeId = column[Int]("street_node_id")
  def * = (sidewalkEdgeId, streetNodeId) <> (SidewalkEdgeStreetNode.tupled, SidewalkEdgeStreetNode.unapply)
}

object SidewalkEdgeStreetNodeTable {
  val db = Database.forConfig("default")
  val sidewalkEdgeStreetNodeTable = TableQuery[SidewalkEdgeStreetNodeTable]

  def insert(sidewalkEdge: SidewalkEdge, streetNode: StreetNode) = {
    val q = DBIO.seq(
      sidewalkEdgeStreetNodeTable += SidewalkEdgeStreetNode(sidewalkEdge.sidewalkEdgeId, streetNode.streetNodeId)
    )
    Await.result(db.run(q), Duration.Inf)
  }

  def delete(hardDelete: Boolean = false): Unit = {
    val action = sidewalkEdgeStreetNodeTable.delete
    Await.result(db.run(action), Duration.Inf)
  }
} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:34,代码来源:SidewalkEdgeStreetNodeTable.scala


示例17: StreetCurb

//设置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 StreetCurb(streetCurbId: Int, geom: jtsg.MultiLineString)

class StreetCurbTable(tag: Tag) extends Table[StreetCurb](tag, Some("pittsburgh"), "street_curb") {
  def streetCurbId = column[Int]("street_curb_id", O.AutoInc, O.PrimaryKey)
  def geom = column[jtsg.MultiLineString]("geom")
  def * = (streetCurbId, geom) <> (StreetCurb.tupled, StreetCurb.unapply)
}

object StreetCurbTable {
  val db = Database.forConfig("default")
  val streetCurbs = TableQuery[StreetCurbTable]

  def selectStreetCurbsIntersecting(buffer: jtsg.Geometry): List[StreetCurb] = {
    buffer.setSRID(4326)
    val q = streetCurbs.filter(_.geom.intersects(buffer.bind)).result
    Await.result(db.run(q), Duration.Inf).toList
  }
} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:27,代码来源:StreetCurbTable.scala


示例18: Init6

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

import java.util.concurrent.TimeUnit

import akka.actor.{ActorRef, PoisonPill}
import com.init6.channels.ChannelsActor
import com.init6.connection.websocket.WebSocketConnectionHandler
import com.init6.connection.{ConnectionHandler, IpLimitActor}
import com.init6.db.{DAO, DAOActor}
import com.init6.servers.{ServerAnnouncementActor, ServerRegistry}
import com.init6.users.{RankingActor, TopCommandActor, UsersActor}

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.Random


object Init6 extends App with Init6Component {

  DAO
  ServerRegistry()
  DAOActor()
  IpLimitActor(Config().Accounts.connectionLimit)
  UsersActor()
  ChannelsActor()
  TopCommandActor()
  RankingActor()
  ServerAnnouncementActor(args(0).toLong)

  val random = new Random(System.nanoTime())
  val delay =
    if (random.nextInt(100) < Config().Server.reconThreshold) {
      0
    } else {
      12
    }

  var connectionHandlers: Seq[ActorRef] = _

  import system.dispatcher
  system.scheduler.scheduleOnce(
    Duration(delay, TimeUnit.SECONDS)
  )({
    connectionHandlers = Config().Server.ports
      .map(port => {
        ConnectionHandler(Config().Server.host, port)
      }) :+
      WebSocketConnectionHandler()
  })

  sys.addShutdownHook({
    Option(connectionHandlers).foreach(_.foreach(_ ! PoisonPill))

    implicit val timeout = Duration(10, TimeUnit.SECONDS)
    Await.ready(system.terminate(), timeout)
    DAO.close()
  })
} 
开发者ID:fjaros,项目名称:init6,代码行数:59,代码来源:Init6.scala


示例19: actorSystemTerminateTimeout

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

import akka.actor.ActorSystem
import org.scalatest.{BeforeAndAfterEach, Suite}

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

trait AkkaFixture extends ConfigFixture with BeforeAndAfterEach { _: Suite =>
  import AkkaFixture._

  
  def actorSystemTerminateTimeout: Duration = DefaultActorSystemTerminateTimeout

  private var mutableActorSystem = Option.empty[ActorSystem]
  implicit def actorSystem: ActorSystem =
    mutableActorSystem.getOrElse(throw new IllegalArgumentException("The ActorSystem is not initialized"))

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    mutableActorSystem = Option(ActorSystem(s"test-${System.currentTimeMillis()}", config))
  }

  override protected def afterEach(): Unit = {
    Await.result(actorSystem.terminate(), actorSystemTerminateTimeout)
    super.afterEach()
  }
}

object AkkaFixture {
  val DefaultActorSystemTerminateTimeout: Duration = 10.seconds
} 
开发者ID:akka,项目名称:alpakka,代码行数:33,代码来源:AkkaFixture.scala


示例20: show

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

import com.google.inject.Inject
import models._
import play.api.mvc.{Controller, Action}
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import scala.concurrent.duration._
import scala.concurrent.Await


class [email protected]()(userRepo: UserRepo) extends Controller {

  def show = Action {
          val userList = Await.result(userRepo.getAll,2 second)
    //      val awardList =  Await.result(awardsRepo.getAll,2 second)
    //      val assignmentList = Await.result(assignmentRepo.getAll,2 second)
    //      val languageList = Await.result(languageRepo.getAll,2 second)
    //      val programminList = Await.result(programmingRepo.getAll,2 second)

    Ok(views.html.intern(userList))
  }
} 
开发者ID:aarwee,项目名称:PLAY-SLICK-DEEPTI-KUNAL-RISHABH,代码行数:24,代码来源:InternController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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