本文整理汇总了Scala中scala.concurrent.ExecutionContext类的典型用法代码示例。如果您正苦于以下问题:Scala ExecutionContext类的具体用法?Scala ExecutionContext怎么用?Scala ExecutionContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ExecutionContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CassandraSink
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.cassandra.scaladsl
import akka.Done
import akka.stream.scaladsl.{Flow, Keep, Sink}
import com.datastax.driver.core.{BoundStatement, PreparedStatement, Session}
import scala.concurrent.{ExecutionContext, Future}
import akka.stream.alpakka.cassandra.GuavaFutures._
object CassandraSink {
def apply[T](
parallelism: Int,
statement: PreparedStatement,
statementBinder: (T, PreparedStatement) => BoundStatement
)(implicit session: Session, ex: ExecutionContext): Sink[T, Future[Done]] =
Flow[T]
.mapAsyncUnordered(parallelism)(t ? session.executeAsync(statementBinder(t, statement)).asScala())
.toMat(Sink.ignore)(Keep.right)
}
示例2: ExampleFilter
//设置package包名称以及导入依赖的类
package filters
import akka.stream.Materializer
import javax.inject._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class ExampleFilter @Inject()(
implicit override val mat: Materializer,
exec: ExecutionContext) extends Filter {
override def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
// Run the next filter in the chain. This will call other filters
// and eventually call the action. Take the result and modify it
// by adding a new header.
nextFilter(requestHeader).map { result =>
result.withHeaders("X-ExampleFilter" -> "foo")
}
}
}
示例3: add
//设置package包名称以及导入依赖的类
package services
import com.google.inject.{ImplementedBy, Inject}
import model.{Artist, ArtistDAO, Temp}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.Logger
import scala.concurrent.ExecutionContext
@ImplementedBy(classOf[ArtistServicesImpl])
trait ArtistServices {
def add (discActor : Artist) : Boolean
def findAllByType(value: String) : ArtistResponse
}
case class ArtistResponse(artists : List[Artist])
object ArtistResponse {
//implicit val formatter1 = Json.format[Artist]
implicit val formatter2 = Json.format[ArtistResponse]
Logger.debug("Attempting risky calculation.")
implicit val implicitFooWrites = new Writes[ArtistResponse] {
def writes(discActors : ArtistResponse): JsValue = {
Json.obj(
"artists" -> discActors.artists
)
}
}
}
class ArtistServicesImpl @Inject()(dao: ArtistDAO )(implicit ec: ExecutionContext) extends ArtistServices {
override def add(artist : Artist ): Boolean = {
if(dao.addNew(artist)!=null)
true
else
false
}
override def findAllByType(value: String): ArtistResponse = {
println("Find Artist by Name: " + value)
ArtistResponse(dao.getAllByName(value).filter(a => a.isDefined).map(a => a.get))
}
}
示例4: extractBearerToken
//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk.authentication
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive1, Directives}
import com.github.cupenya.microservices.sdk.logging.Logging
import scala.concurrent.ExecutionContext
trait AuthorizationDirectives extends Logging {
self: Directives =>
implicit val ec: ExecutionContext
// TODO: dep injection
private val tokenVerifier = new JwtTokenVerifier
private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
authHeader.collect {
case Authorization(OAuth2BearerToken(token)) => token
}
def authorized: Directive1[AuthInfo] = {
optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken).flatMap {
case Some(token) =>
onComplete(tokenVerifier.verifyToken(token)).flatMap { x =>
x.map(authInfo => provide(authInfo))
.recover {
case ex =>
log.error("Couldn't log in using provided authorization token", ex)
reject(AuthorizationFailedRejection).toDirective[Tuple1[AuthInfo]]
}
.get
}
case None =>
reject(AuthorizationFailedRejection)
}
}
}
示例5: AuthServiceRoute
//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi.http.routes
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import com.noedominguez.class_orchestration.restapi.models.UserEntity
import com.noedominguez.class_orchestration.restapi.services.AuthService
import com.noedominguez.class_orchestration.restapi.http.SecurityDirectives
import de.heikoseeberger.akkahttpcirce.CirceSupport
import io.circe.generic.auto._
import io.circe.syntax._
import scala.concurrent.ExecutionContext
class AuthServiceRoute(val authService: AuthService)(implicit executionContext: ExecutionContext) extends CirceSupport with SecurityDirectives {
import StatusCodes._
import authService._
val route = pathPrefix("auth") {
path("signIn") {
pathEndOrSingleSlash {
post {
entity(as[LoginPassword]) { loginPassword =>
complete(signIn(loginPassword.login, loginPassword.password).map(_.asJson))
}
}
}
} ~
path("signUp") {
pathEndOrSingleSlash {
post {
entity(as[UserEntity]) { userEntity =>
complete(Created -> signUp(userEntity).map(_.asJson))
}
}
}
}
}
private case class LoginPassword(login: String, password: String)
}
示例6: StoryServiceImpl
//设置package包名称以及导入依赖的类
package io.soheila.cms.services.stories
import io.soheila.cms.daos.StoryDAO
import io.soheila.cms.entities.{ Media, Story, UserReference }
import io.soheila.cms.services.exceptions.CMSServiceException
import io.soheila.cms.types.StoryType
import scala.concurrent.{ ExecutionContext, Future }
class StoryServiceImpl(val storyDAO: StoryDAO) extends StoryService {
override def read(uuid: String)(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.findByUUID(uuid).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => s
}
}
override def initialize(uuid: String, storyType: StoryType.Value, userOption: Option[UserReference])(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.create(uuid, Story(storyType, userOption)).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => Some(s)
}
}
override def findByTypeAndSlug(storyType: StoryType.Value, slug: String)(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.findByTypeAndSlug(storyType, slug).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(story) => story
}
}
override def findAndUpdateLatest(story: Story, upsert: Boolean)(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.findAndUpdateLatest(story, upsert).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => s
}
}
override def editMedia(uuid: String, medias: Set[Media])(implicit ec: ExecutionContext): Future[Boolean] = {
storyDAO.editMedia(uuid, medias).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => s
}
}
override def delete(uuid: String)(implicit ec: ExecutionContext): Future[Boolean] = {
storyDAO.delete(uuid).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => true
}
}
}
示例7: PaginatedResponseRetriever
//设置package包名称以及导入依赖的类
package com.dwolla.awssdk.utils
import com.dwolla.awssdk.utils.ScalaAsyncHandler.Implicits._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.reflectiveCalls
import scala.reflect.ClassTag
object PaginatedResponseRetriever {
class PaginatedResponseRetriever[Req <: PaginatedRequest, Res <: PaginatedResult](requestFactory: () ? Req) {
def via(awsAsyncFunction: AwsAsyncFunction[Req, Res])(implicit ec: ExecutionContext): Future[List[Res]] = {
def impl(nextToken: Option[String] = Some(null), acc: List[Res] = Nil): Future[List[Res]] = nextToken match {
case None ? Future.successful(acc.reverse)
case Some(token) ?
val req = requestFactory()
req.setNextToken(token)
req.via(awsAsyncFunction)
.flatMap(res ? impl(Option(res.getNextToken()), res :: acc))
}
impl()
}
}
def fetchAll[Req <: PaginatedRequest, Res <: PaginatedResult](requestFactory: () ? Req,
awsAsyncFunction: AwsAsyncFunction[Req, Res])
(implicit ec: ExecutionContext): Future[List[Res]] = fetchAllWithRequestsLike(requestFactory).via(awsAsyncFunction)
def fetchAllWithRequestsLike[Req <: PaginatedRequest, Res <: PaginatedResult](requestFactory: () ? Req): PaginatedResponseRetriever[Req, Res] =
new PaginatedResponseRetriever(requestFactory)
def fetchAllWithDefaultRequestsVia[Req <: PaginatedRequest : ClassTag, Res <: PaginatedResult](awsAsyncFunction: AwsAsyncFunction[Req, Res])
(implicit ec: ExecutionContext): Future[List[Res]] =
fetchAllWithRequestsLike(() ? implicitly[ClassTag[Req]].runtimeClass.newInstance().asInstanceOf[Req]).via(awsAsyncFunction)
}
示例8: withMongoURL
//设置package包名称以及导入依赖的类
package io.scalajs.npm.mongoose
import io.scalajs.nodejs.process
import io.scalajs.npm.mongodb.{Db, MongoClient}
import org.scalatest.FunSpec
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait MongoDBTestSupport {
self: FunSpec =>
def withMongoURL[S](block: String => S): Any = {
process.env.get("MONGO_CONNECT") match {
case Some(url) => block(url)
case None =>
info("No MongoDB configuration. Set 'MONGO_CONNECT' (ex. MONGO_CONNECT=mongodb://localhost:27017/test)")
}
}
def withMongo[S](label: String)(block: Db => Future[S])(implicit ec: ExecutionContext): Any = {
process.env.get("MONGO_CONNECT") match {
case None =>
info("No MongoDB configuration. Set 'MONGO_CONNECT' (ex. MONGO_CONNECT=mongodb://localhost:27017/test)")
case Some(url) =>
val outcome = for {
db <- MongoClient.connectFuture(url)
result <- block(db)
} yield (db, result)
outcome onComplete {
case Success((db, _)) =>
info(s"$label: Closing connection....")
db.close()
case Failure(e) =>
throw new IllegalStateException(s"MongoDB connection failure: ${e.getMessage}")
}
}
}
}
示例9: MainAppActor
//设置package包名称以及导入依赖的类
package com.github.unknownnpc.remotedebugtool.actor
import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem}
import com.github.unknownnpc.remotedebugtool.message._
import scala.concurrent.ExecutionContext
class MainAppActor()(implicit actorSystem: ActorSystem) extends Actor with ActorLogging {
private implicit val dispatcher: ExecutionContext = actorSystem.dispatcher
private var jdiVmServiceActor: ActorRef = _
private var reportServiceActor: ActorRef = _
override def preStart(): Unit = {
log.info("Main app actor starts")
reportServiceActor = createReportServiceActor()
jdiVmServiceActor = createJdiVmServiceActor()
}
override def postStop() {
log.info("Main app actor stops")
}
override def receive: Receive = {
case MainAppActorStart =>
startServices()
case MainAppActorStop =>
stopServices()
context.stop(self)
context.system.terminate()
}
private def startServices() = {
jdiVmServiceActor ! JdiVmServiceStart
}
private def stopServices() = {
log.info("Received command to stop all services")
jdiVmServiceActor ! JdiVmServiceStop
reportServiceActor ! ReportServiceStop
}
private def createJdiVmServiceActor() = {
context.actorOf(JdiVmServiceActor.props(reportServiceActor), "jdi-vm-service")
}
private def createReportServiceActor() = {
context.actorOf(ReportServiceActor.props(self), "report-service")
}
}
示例10: MessageEventProcessor
//设置package包名称以及导入依赖的类
package sample.helloworldconsumer.impl
import akka.Done
import com.datastax.driver.core.{BoundStatement, PreparedStatement}
import com.lightbend.lagom.scaladsl.persistence.ReadSideProcessor.ReadSideHandler
import com.lightbend.lagom.scaladsl.persistence.cassandra.{CassandraReadSide, CassandraSession}
import com.lightbend.lagom.scaladsl.persistence.{AggregateEventTag, EventStreamElement, ReadSideProcessor}
import scala.concurrent.{ExecutionContext, Future}
class MessageEventProcessor(cassandraReadSide: CassandraReadSide, cassandraSession: CassandraSession)
(implicit ec: ExecutionContext) extends ReadSideProcessor[MessageEvent] {
private var insertWordStmt: PreparedStatement = _
override def buildHandler(): ReadSideHandler[MessageEvent] = {
cassandraReadSide.builder[MessageEvent]("message_offset")
.setGlobalPrepare(createTable)
.setPrepare { tags =>
prepareStatements
}
.setEventHandler[MessageSaved](insertWord)
.build()
}
override def aggregateTags: Set[AggregateEventTag[MessageEvent]] = Set(MessageEventTag.INSTANCE)
private def createTable(): Future[Done] = {
for {
_ <- cassandraSession.executeCreateTable(
""" CREATE TABLE IF NOT EXISTS wordcounttest (
words text,
insertion_time timestamp,
PRIMARY KEY (words,insertion_time)
)WITH CLUSTERING ORDER BY (insertion_time DESC)
""")
} yield Done
}
private def prepareStatements(): Future[Done] = {
for {
insert <- cassandraSession.prepare(
"""insert into wordcounttest(words ,insertion_time) values(? ,toTimestamp(now())) """)
} yield {
insertWordStmt = insert
Done
}
}
private def insertWord(started: EventStreamElement[MessageSaved]): Future[List[BoundStatement]] = {
Future.successful {
val words = started.event.msg.replaceAll("[^\\p{L}\\p{Nd}]+", " ").split(" ").toList
words.map{ word=> insertWordStmt.bind(word) }
}
}
}
示例11: ExecutionContextBackboneCoordinator
//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
import scala.util.control.NonFatal
import org.slf4j.LoggerFactory
import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }
class ExecutionContextBackboneCoordinator[DA](backbone: Backbone[DA], executionContext: ExecutionContext) {
import ExecutionContextBackboneCoordinator._
val localInitPhases = backbone.initializeTopLevelContexts
def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
Future {
val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
try {
backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
} finally {
releasePhases.foreach((phase: LocalReleasePhase) => {
Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
})
}
}(executionContext)
}
}
object ExecutionContextBackboneCoordinator {
val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
}
示例12: QQAsyncTestSuite
//设置package包名称以及导入依赖的类
package qq
import java.util.concurrent.TimeUnit
import monix.execution.schedulers.ExecutionModel
import monix.execution.{Cancelable, Scheduler}
import org.scalatest.AsyncFreeSpec
import scala.concurrent.ExecutionContext
abstract class QQAsyncTestSuite extends AsyncFreeSpec with QQTestSuite with AsyncTestUtil {
implicit val schedulerVal: Scheduler = scheduler(super.executionContext)
def scheduler(implicit executionContext: ExecutionContext): Scheduler =
new Scheduler {
override def execute(runnable: Runnable): Unit = executionContext.execute(runnable)
override def reportFailure(t: Throwable): Unit = executionContext.reportFailure(t)
override def scheduleOnce(initialDelay: Long, unit: TimeUnit, r: Runnable): Cancelable = {
executionContext.execute(r)
Cancelable.empty
}
override def scheduleWithFixedDelay(initialDelay: Long, delay: Long, unit: TimeUnit, r: Runnable): Cancelable = {
???
}
override def scheduleAtFixedRate(initialDelay: Long, period: Long, unit: TimeUnit, r: Runnable): Cancelable = {
???
}
override def currentTimeMillis(): Long = System.currentTimeMillis()
override def executionModel: ExecutionModel = ExecutionModel.SynchronousExecution
override def withExecutionModel(em: ExecutionModel): Scheduler = ???
}
}
示例13: Hello
//设置package包名称以及导入依赖的类
package com.github.cupenya.hello
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{ AuthorizationFailedRejection, Directives, RejectionHandler }
import akka.http.scaladsl.model.StatusCodes._
import com.github.cupenya.hello.authentication.AuthorizationDirectives
import spray.json._
import scala.concurrent.ExecutionContext
case class Hello(message: String)
case class AuthError(error: String)
trait Protocols extends DefaultJsonProtocol {
implicit val helloFormat = jsonFormat1(Hello)
}
trait HelloHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with Protocols with Logging {
implicit val ec: ExecutionContext
implicit val authErrorFormat = jsonFormat1(AuthError)
private val rh = RejectionHandler.newBuilder().handle {
case AuthorizationFailedRejection =>
complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
}.result()
val helloRoute = handleRejections(rh) {
authorized { authInfo =>
pathPrefix("hello") {
get {
complete(Hello(s"hello ${authInfo.userId}"))
}
}
}
}
}
示例14: LocationController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
//import models.City
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.play.json.collection._
import utils.Errors
import models._
import scala.concurrent.{ExecutionContext, Future}
import play.modules.reactivemongo.json._
@Singleton
class LocationController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {
def locationFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("location"))
def create(lat: Double, long: Double) = Action.async {
for {
locations <- locationFuture
lastError <- locations.insert(Location(lat, long))
} yield
Ok("Mongo LastError: %s".format(lastError))
}
def createFromJson = Action.async(parse.json) { request =>
Json.fromJson[Location](request.body) match {
case JsSuccess(location, _) =>
for {
locations <- locationFuture
lastError <- locations.insert(location)
} yield {
Logger.debug(s"Successfully inserted with LastError: $lastError")
Created("Created 1 location")
}
case JsError(errors) =>
Future.successful(BadRequest("Could not build a location from the json provided. " + Errors.show(errors)))
}
}
}
示例15: RegistryClient
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.protocol.registry
import scala.concurrent.{ ExecutionContext, Future }
import akka.actor.ActorSystem
import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse, RequestEntity }
import akka.stream.Materializer
import fommil.sjs.FamilyFormats._
class RegistryClient(baseUrl: String = "http://api.flowhub.io") extends SLF4JLogging {
def register(runtime: Runtime, token: String)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): Future[HttpResponse] = {
log.debug(s"PUT $baseUrl/runtimes/${runtime.id}")
Marshal(runtime).to[RequestEntity].flatMap { entity =>
Http().singleRequest(HttpRequest(
PUT,
s"$baseUrl/runtimes/${runtime.id}",
List(Authorization(OAuth2BearerToken(token))),
entity))
}
}
def unregister(runtimeId: String, token: String)(implicit system: ActorSystem, mat: Materializer): Future[HttpResponse] = {
log.debug(s"DELETE $baseUrl/runtimes/$runtimeId")
Http().singleRequest(HttpRequest(
DELETE,
s"$baseUrl/runtimes/$runtimeId",
List(Authorization(OAuth2BearerToken(token)))))
}
}