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


Scala blocking类代码示例

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


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

示例1: AuthService

//设置package包名称以及导入依赖的类
package de.innfactory.bootstrap.services

import de.innfactory.bootstrap.utils.Authentication

import scala.collection.JavaConverters._
import scala.concurrent.{ExecutionContext, Future, blocking}

class AuthService(auth : Authentication)(implicit executionContext: ExecutionContext) {

  def authenticate(accessToken: String): Future[Option[Map[String, AnyRef]]] = Future {
    blocking {
      val jwtCheck = auth.validateToken(accessToken)
      if (jwtCheck == null) {
        None
      } else {
        Some(jwtCheck.asScala.toMap)
      }
    }
  }

} 
开发者ID:innFactory,项目名称:bootstrap-akka-http,代码行数:22,代码来源:AuthService.scala

示例2: IOActor

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

import java.io.PrintStream

import akka.actor.{Actor, ActorRef}
import akka.event.Logging

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, blocking}
import scala.io.BufferedSource


class IOActor(protocolHandler: ActorRef) extends Actor {
  val log = Logging(context.system, this)

  val in: BufferedSource = io.Source.stdin
  val out: PrintStream = System.out

  override def preStart(): Unit = {
    log.debug("IOActor start")

    Future {
      blocking {
        for (line <- in.getLines()) {
          self ! line
        }
      }
    }
  }

  override def receive: Receive = {
    case s: String if sender() == protocolHandler =>
      log.debug("Engine -> GUI: " + s)
      out.println(s)
      out.flush()
    case s: String if sender() == self =>
      log.debug("GUI -> Engine: " + s)
      protocolHandler ! s.trim
  }
} 
开发者ID:Macok,项目名称:fafachess,代码行数:41,代码来源:IOActor.scala

示例3: TestRouter

//设置package包名称以及导入依赖的类
package ir.bayan.academy.web

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, blocking}



trait ReqRouter {
  val route: PartialFunction[HttpReq, Future[HttpRes]]
}


object TestRouter extends ReqRouter {
  override val route: PartialFunction[HttpReq, Future[HttpRes]] = {
    case HttpReq("GET", "/test", _) =>
      Future {
        val text = blocking {
          Thread.sleep(10000)
          "<h1>Hellooooo</h1>"
        }
        HttpRes(200, "Ok", text)
      }

    case [email protected]("GET", "/badtest", _) =>
      Future {
        val number = 10 / (a.method.length - 3)
        HttpRes(200, "Ok", number.toString)
      }


  }
} 
开发者ID:h-ayat,项目名称:simple-web,代码行数:33,代码来源:ReqRouter.scala

示例4: onSubscribe

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

import play.api.Logger
import _root_.redis.clients.jedis._
import scala.concurrent.blocking

trait RedisSupport {
  private[this] val logger = Logger(classOf[RedisSupport])

  protected[this] trait RedisPubSubNoOps { this: JedisPubSub =>
    override def onSubscribe(channel: String, subscribedChannels: Int) {}
    override def onMessage(channel: String, message: String) {}
    override def onPMessage(pattern: String, channel: String, message: String) {}
    override def onUnsubscribe(channel: String, subscribedChannels: Int) {}
    override def onPSubscribe(pattern: String, subscribedChannels: Int) {}
    override def onPUnsubscribe(pattern: String, subscribedChannels: Int) {}
  }

  protected def jedisPool: JedisPool

  // Execute a Redis command with a connection from the pool.
  protected[this] def withJedis[A](f: Jedis => A): A = blocking {
    val jedis = jedisPool.getResource
    try {
      f(jedis)
    } finally {
      jedisPool.returnResource(jedis: BinaryJedis)
    }
  }

  protected[this] def subscribeToChannels(channels: String*)(jedisPubSub: JedisPubSub): Unit = blocking {
    val jedis = jedisPool.getResource
    try {
      jedis.subscribe(jedisPubSub, channels: _*)
    } finally {
      jedisPool.returnBrokenResource(jedis: BinaryJedis)
    }
  }

  protected class LuaScript(val script: String) {
    val id = withJedis { _.scriptLoad(script) }
    logger.trace(s"Loaded Lua script $script with id $id")

    def eval(keys: String*)(args: String*) = withJedis { _.evalsha(id, keys.size, keys ++ args: _*) }
  }
} 
开发者ID:cubean,项目名称:play-blog-example,代码行数:47,代码来源:RedisSupport.scala

示例5: AmazonS3Extensions

//设置package包名称以及导入依赖的类
package com.gilt.gfc.aws.s3.akka

import java.util.Date

import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.model.{S3Object, S3ObjectSummary}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

object AmazonS3Extensions {

  implicit class S3Extensions(val amazonS3: AmazonS3) extends AnyVal {

    import scala.concurrent.blocking

    def mostRecentObject(bucketName: String, prefix: String): Future[Option[S3Object]] = {
      Future {
        mostRecentObjectSummary(bucketName, prefix)
      }.map { objectSummaryOpt =>
        objectSummaryOpt.map { summary =>
          val key = summary.getKey
          amazonS3.getObject(bucketName, key)
        }
      }
    }

    private def mostRecentObjectSummary(bucketName: String, prefix: String): Option[S3ObjectSummary] = {
      import scala.collection.JavaConversions._
      blocking {
        amazonS3.listObjects(bucketName, prefix).getObjectSummaries.toList
      }.sortBy(_.getLastModified)(Ordering[Date].reverse).headOption
    }
  }

} 
开发者ID:gilt,项目名称:gfc-aws-s3,代码行数:37,代码来源:AmazonS3Extensions.scala

示例6: createImage

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

import akka.actor.ActorSystem
import net.sourceforge.plantuml.SourceStringReader

import scala.concurrent.{ExecutionContext, blocking}
import scala.concurrent.Future
import java.io.ByteArrayOutputStream
import java.io.IOException
import javax.inject._

trait PlantUml {
  def createImage(text: String): Future[Array[Byte]]
}

@Singleton
class PlantUmlCreator @Inject() (actorSystem: ActorSystem) extends PlantUml {

  private val myExecutionContext: ExecutionContext = actorSystem.dispatchers.lookup("contexts.plantuml")
  def createImage(text: String): Future[Array[Byte]] = {
    Future {
      blocking {
        val reader = new SourceStringReader(text, "UTF8")
        val baos = new ByteArrayOutputStream()
        val image = reader.generateImage(baos)
        try {
          baos.toByteArray()
        } finally {
          try {
            if (baos != null) { // scalastyle:ignore
              baos.close();
            }
          } catch {
            case e: IOException => // ¯\_(?)_/¯
          }
        }
      }
    }(myExecutionContext)
  }
} 
开发者ID:d1egoaz,项目名称:plantuml-rest-service,代码行数:41,代码来源:PlantUML.scala

示例7: IdentifiersDao

//设置package包名称以及导入依赖的类
package uk.ac.wellcome.platform.idminter.database

import javax.inject.Singleton

import com.google.inject.Inject
import com.twitter.inject.Logging
import scalikejdbc._
import uk.ac.wellcome.platform.idminter.model.{Identifier, IdentifiersTable}
import uk.ac.wellcome.utils.GlobalExecutionContext.context

import scala.concurrent.{Future, blocking}

@Singleton
class IdentifiersDao @Inject()(db: DB, identifiers: IdentifiersTable)
    extends Logging {

  implicit val session = AutoSession(db.settingsProvider)

  def findSourceIdInDb(miroId: String): Future[Option[Identifier]] =
    Future {
      blocking {
        info(s"About to search for MiroID $miroId in Identifiers")
        val i = identifiers.i
        withSQL {
          select.from(identifiers as i).where.eq(i.MiroID, miroId)
        }.map(Identifier(i)).single.apply()
      }
    } recover {
      case e: Throwable =>
        error(s"Failed getting MiroID $miroId in DynamoDB", e)
        throw e
    }

  def saveIdentifier(identifier: Identifier): Future[Unit] = {
    val insertIntoDbFuture = Future {
      blocking {
        info(s"putting new identifier $identifier")
        withSQL {
          insert
            .into(identifiers)
            .namedValues(
              identifiers.column.CanonicalID -> identifier.CanonicalID,
              identifiers.column.MiroID -> identifier.MiroID)
        }.update().apply()
        ()
      }
    }
    insertIntoDbFuture.onFailure {
      case e: Exception =>
        error(s"Failed inserting identifier $identifier in database", e)
    }
    insertIntoDbFuture
  }
} 
开发者ID:wellcometrust,项目名称:platform-api,代码行数:55,代码来源:IdentifiersDao.scala

示例8: PublishAttempt

//设置package包名称以及导入依赖的类
package uk.ac.wellcome.sns

import com.amazonaws.services.sns.AmazonSNS
import com.amazonaws.services.sns.model.PublishRequest
import com.google.inject.Inject
import com.twitter.inject.Logging
import uk.ac.wellcome.models.aws.SNSConfig
import uk.ac.wellcome.utils.GlobalExecutionContext.context

import scala.concurrent.{Future, blocking}

case class PublishAttempt(id: Either[Throwable, String])

class SNSWriter @Inject()(snsClient: AmazonSNS, snsConfig: SNSConfig)
    extends Logging {
  val defaultSubject = "subject-not-specified"

  def writeMessage(message: String,
                   subject: Option[String]): Future[PublishAttempt] =
    Future {
      blocking {
        info(
          s"about to publish message $message on the SNS topic ${snsConfig.topicArn}")
        snsClient.publish(toPublishRequest(message, subject))
      }
    }.map { publishResult =>
        info(s"Published message ${publishResult.getMessageId}")
        PublishAttempt(Right(publishResult.getMessageId))
      }
      .recover {
        case e: Throwable =>
          error("Failed to publish message", e)
          throw e
      }

  private def toPublishRequest(message: String, subject: Option[String]) = {
    new PublishRequest(snsConfig.topicArn,
                       message,
                       subject.getOrElse(defaultSubject))
  }
} 
开发者ID:wellcometrust,项目名称:platform-api,代码行数:42,代码来源:SNSWriter.scala

示例9: BlockingMatcherSpec

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

import com.dwolla.testutils.concurrency.BlockingMatcher.invokeBlockingFunction
import org.specs2.concurrent.{ExecutionEnv, NoImplicitExecutionContextFromExecutionEnv}
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.concurrent.{ExecutionContext, Future, blocking}

class BlockingMatcherSpec(implicit ee: ExecutionEnv) extends Specification with NoImplicitExecutionContextFromExecutionEnv {

  trait Setup extends Scope

  "BlockingAssertions" should {
    "fail a test when the blocking keyword is called for but not used in the implementation" in new Setup {
      { implicit ec: ExecutionContext ?
        Future {
          Thread.sleep(100)
        }
      } must not(invokeBlockingFunction(ee))
    }

    "succeed when the blocking keyword is called for and used in the implementation" in new Setup {
      { implicit ec: ExecutionContext ?
        Future {
          blocking {
            Thread.sleep(100)
          }
        }
      } must invokeBlockingFunction(ee)
    }
  }
} 
开发者ID:Dwolla,项目名称:scala-test-utils,代码行数:34,代码来源:BlockingMatcherSpec.scala

示例10: executionContext

//设置package包名称以及导入依赖的类
package de.is24.jest4s

import java.net.URI
import java.nio.file.Files
import java.util
import java.util.UUID

import de.is24.jest4s.utils.SLF4JLogging
import org.apache.commons.io.FileUtils
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.node.{ InternalSettingsPreparer, Node }
import org.elasticsearch.plugins.Plugin
import org.elasticsearch.transport.Netty3Plugin

import scala.concurrent.{ ExecutionContext, Future, blocking }
import scala.util.control.NonFatal

trait EmbeddedElasticSearchSupport extends SLF4JLogging {

  implicit def executionContext: ExecutionContext

  private lazy val clusterId = UUID.randomUUID().toString
  private lazy val clusterName = "embedded-elasticsearch-$clusterId"
  private lazy val dataDir = Files.createTempDirectory(s"${clusterName}_data").toFile
  private lazy val settings = Settings.builder
    .put("path.home", dataDir.toString)
    .put("path.data", dataDir.toString)
    .put("cluster.name", clusterName)
    .put("http.enabled", true)
    .put("transport.type", "local")
    .put("http.type", "netty3")
    .build

  private lazy val node = new PluginConfigurableNode(settings, util.Arrays.asList(classOf[Netty3Plugin]))

  def startEmbeddedElasticSearch(): ElasticSearchHttpUri = {
    node.start()
    val uri = ElasticSearchHttpUri(new URI("http://localhost:9200"))
    log.info(s"Embedded elasticsearch starting at $uri")
    uri
  }

  def stopEmbeddedElasticSearch(): Future[Unit] = {
    Future {
      blocking {
        node.close()
        try {
          FileUtils.forceDelete(dataDir)
        } catch {
          case NonFatal(e) ?
            log.warn(s"Failed to cleanup elasticsearch data at $dataDir", e)
        }
      }
    }
  }

  private class PluginConfigurableNode(settings: Settings, classpathPlugins: util.Collection[Class[_ <: Plugin]]) extends Node(InternalSettingsPreparer.prepareEnvironment(settings, null), classpathPlugins)

} 
开发者ID:ImmobilienScout24,项目名称:jest4s,代码行数:60,代码来源:EmbeddedElasticSearchSupport.scala

示例11: successRace

//设置package包名称以及导入依赖的类
package org.sunnyshahmca.connect.mongodb
package object common {
  import scala.concurrent.{ExecutionContext, Future, Promise, blocking}
  import scala.concurrent.duration._
  import ExecutionContext.Implicits.global
  import scala.util.{Try, Success, Failure}
  import org.slf4j.{Logger,LoggerFactory}
  val logger = LoggerFactory.getLogger(this.getClass);  

  def successRace[T](f: Future[T], g: => Future[T]): Future[T] = {
    val p = Promise[T]()
    p.tryCompleteWith(f)
    if(!f.isCompleted) { p.tryCompleteWith(g) }
    p.future
  }

  trait Sleeper {
    def sleep[T](msSleep:Long, value:T, beforeSleepTrigger:()=>Unit, afterSleepTrigger:()=>Unit)
    (implicit ec:ExecutionContext):Future[T]
  }

  case class MaxRetriesAllowed(r:Int)
  case class DelayBetweenRetries(d:Duration)

  object OpRetrierImplicits  {
    implicit val m = MaxRetriesAllowed(10)
    implicit val d = DelayBetweenRetries(Duration(1, SECONDS))
  }
  
  def OpRetrier[T]( op: () => Future[T], retriesMade:Int = 0)
                    (implicit maxRetriesAllowed:MaxRetriesAllowed, delayBetweenRetries:DelayBetweenRetries):Future[T] = {

    val promise = Promise[T]
    if(retriesMade < 0 ) {
      promise.failure(new IllegalArgumentException("retriesMade =" + retriesMade + ", retriesMade can't be < 0 "))
    } else if (maxRetriesAllowed.r < retriesMade) {
      promise.failure(new IllegalArgumentException("maxRetriesAllowed = " + maxRetriesAllowed.r + " retriesMade = " + retriesMade + ", max_retries can't be < retriesMade"))
    } else {
      val resultF = if( retriesMade == 0 || delayBetweenRetries.d.toMillis <= 0 ) op()
                    else Future { blocking { Try{Thread.sleep(delayBetweenRetries.d.toMillis)} } }.flatMap((t) => op())
      resultF.onSuccess { case result => promise.success(result) } 
      resultF.onFailure { 
        case e:Throwable => 
          val nretriesMade = retriesMade + 1
          if(nretriesMade >= maxRetriesAllowed.r) {
            logger.info("That's it! Already made {} retries", nretriesMade)
            promise.failure(e)
          } else {
            logger.info("Might get one more chance, retries made = {}", nretriesMade)
            promise.completeWith(OpRetrier(op, retriesMade+1)(maxRetriesAllowed, delayBetweenRetries))
          }
      }
    }
    promise.future
  }
} 
开发者ID:ShahSunny,项目名称:Mongodb-kafka-connector,代码行数:57,代码来源:Common.scala

示例12: Server

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

import java.net.{ServerSocket, Socket}

import scala.concurrent.{Future, blocking}
import scala.util.Try
import scala.concurrent.ExecutionContext.Implicits.global

class Server(val port: Int) extends SocketOps {
  type SocketHandler = Socket => Unit

  def forEachConnection(f: SocketHandler): Unit = {
    var serverSocket: ServerSocket = createListenSocket.getOrElse(throw new RuntimeException(s"unable to create socket on port $port"))
    var keepRunning = true
    while(keepRunning) {
      val connection = acceptConnectionFromServer(serverSocket)
      connection.foreach(withOpenConnection(_)(f))
      connection.failed.foreach { ex =>
        keepRunning = false
        Console.err.println(s"Failed to accept a connection, exiting ($ex)")
      }
    }
  }

  private def createListenSocket: Try[ServerSocket] = Try(new ServerSocket(port))

  private def acceptConnectionFromServer(serverSocket: ServerSocket): Try[Socket] = blocking {
    Try(serverSocket.accept())
  }

  private def withOpenConnection(socket: Socket)(f: SocketHandler): Future[_] = {
    Future {
      f(socket)
    }
  }
} 
开发者ID:colindean,项目名称:scala-docker-pingpong,代码行数:37,代码来源:Server.scala

示例13: MoorMotionStudy1

//设置package包名称以及导入依赖的类
package de.sciss.unlike

import de.sciss.file._

import scala.concurrent.duration.Duration
import scala.concurrent.{Future, Await, blocking}

object MoorMotionStudy1 extends App {
  val base        = userHome / "Documents" / "projects" / "Unlike"
  val mode        = "WRITE"
  val startFrame  =     1 + 60
  val endFrame    = 11945 - 60
  val jsonDir     = base / "moor_8024_json"
  val renderDir   = base / "moor_8024_out"

  val estConf = EstimateVideoMotion.Config(
    input   = base / "moor_8024" / "moor_8024-%05d.jpg",
    output  = Some(jsonDir / "moor_8024-%05d-%05d.json"),
    frames  = startFrame to endFrame
  )

  if (mode == "ANALYZE") {
    val p = EstimateVideoMotion(estConf)
    println("Analyze...")
    runAndMonitor(p, exit = true, printResult = false)

  } else if (mode == "WRITE") {
    val read    = Future(blocking(EstimateVideoMotion.read(estConf)))
    println("Read JSON...")
    val prod    = PhaseCorrelation.Product.identity +: Await.result(read, Duration.Inf)

    val input   = estConf.input
    val output  = renderDir / "moor_8024-out-%05d.jpg"
    val renCfg  = RenderVideoMotion.Config(input = input, output = output, format = ImageFormat.JPG(),
      frames = (startFrame to endFrame) zip prod )
    val p = RenderVideoMotion(renCfg)
    println("Render...")
    p.onFailure {
      case e => e.printStackTrace()
    }
    runAndMonitor(p, exit = true, printResult = false)

  } else {
    throw new UnsupportedOperationException(mode)
  }
} 
开发者ID:Sciss,项目名称:Unlike,代码行数:47,代码来源:MoorMotionStudy1.scala

示例14: AuthService

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

import $package$.utils.Authentication

import scala.collection.JavaConverters._
import scala.concurrent.{ExecutionContext, Future, blocking}

class AuthService(auth : Authentication)(implicit executionContext: ExecutionContext) {

  def authenticate(accessToken: String): Future[Option[Map[String, AnyRef]]] = Future {
    blocking {
      val jwtCheck = auth.validateToken(accessToken)
      if (jwtCheck == null) {
        None
      } else {
        Some(jwtCheck.asScala.toMap)
      }
    }
  }

} 
开发者ID:innFactory,项目名称:bootstrap-akka-http.g8,代码行数:22,代码来源:AuthService.scala

示例15: DockerService

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

import actors.DockerWSRequest.Filter
import actors.DockerActor._
import com.github.dockerjava.api.model.Filters
import com.github.dockerjava.core.{DockerClientBuilder, DockerClientConfig}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, blocking}


case class DockerService(dockerClientConfig: DockerClientConfig) extends DockerServiceCalls {
  val docker = DockerClientBuilder.getInstance(dockerClientConfig).build()

  override def getInfo: Future[InternalResponse] = Future {
    blocking {
      InternalInfo.response(docker.infoCmd().exec().toString)
    }
  }

  override def getImages: Future[InternalResponse] = Future {
    blocking {
      InternalImages.response(docker.listImagesCmd().exec().toString)
    }
  }

  override def getContainers(filter: Filter): Future[InternalResponse] = Future {
    blocking {
      if (filter.key == "") InternalContainers(filter).response(docker.listContainersCmd().withShowAll(true).exec().toString)
      else InternalContainers(filter).response(docker.listContainersCmd().withFilters(new Filters().withFilter(filter.key, filter.value)).exec().toString)
    }
  }

  override def startContainer(id: String): Future[InternalResponse] = Future {
    blocking {
      docker.startContainerCmd(id).exec()
      InternalStart(id).response(true) // TODO exception handling
    }
  }

  override def stopContainer(id: String): Future[InternalResponse] = Future {
    blocking {
      docker.stopContainerCmd(id).exec()
      InternalStop(id).response(true) // TODO exception handling
    }
  }
}

trait DockerServiceCalls {
  def getInfo: Future[InternalResponse]

  def getImages: Future[InternalResponse]

  def getContainers(filter: Filter): Future[InternalResponse]

  def startContainer(id: String): Future[InternalResponse]

  def stopContainer(id: String): Future[InternalResponse]
} 
开发者ID:grantzvolsky,项目名称:websecute,代码行数:60,代码来源:DockerService.scala


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