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

Scala Future类代码示例

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

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



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

示例1: Service

//设置package包名称以及导入依赖的类
package onextent.oemap.server.http

import java.util.UUID

import onextent.oemap.server.entities.IdAble

import scala.concurrent.{ExecutionContext, Future}

class Service[T <: IdAble](implicit val executionContext: ExecutionContext) {

  var entries = Vector.empty[T]

  def create(entry: T): Future[Option[UUID]] =
    Future {
      entries.find(_.id == entry.id) match {
        case Some(_) => None // Conflict! id is already taken
        case None =>
          entries = entries :+ entry
          Some(entry.id)
      }
    }


  def get(id: UUID): Future[Option[T]] =
    Future {
      entries.find(_.id == id)
    }

  def delete(id: UUID): Future[Unit] =
    Future {
      entries = entries.filterNot(_.id == id)
    }
} 
开发者ID:navicore,项目名称:oemap-server,代码行数:34,代码来源:Service.scala


示例2: HomeController

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

import javax.inject._

import org.slf4j.LoggerFactory
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.mvc._
import play.modules.reactivemongo._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.{JSONCollection, _}
import reactivemongo.api.Cursor

import scala.concurrent.Future

@Singleton
class HomeController  @Inject() (val reactiveMongoApi: ReactiveMongoApi)
  extends Controller with MongoController with ReactiveMongoComponents {

  val logger = LoggerFactory.getLogger(this.getClass)

  def collection: JSONCollection = db.collection[JSONCollection]("scrawler1")

  def index = Action {
    Ok(views.html.index(""))
  }

  def query = Action.async { request =>
    val body = request.body
    val query = body.asFormUrlEncoded.get("query")

    val querySet = query.toSet[String]

    val keywords = querySet.flatMap({ string: String =>
      string.split(" ")
    })

    val searchQuery = Json.obj("keywords" -> Json.obj("$in" -> Json.toJson(keywords)))
    logger.info(s"Internal query from client: $searchQuery")
    val cursor: Cursor[JsObject] = collection.find(searchQuery).cursor[JsObject]

    val result: Future[List[JsObject]] = cursor.collect[List]()

    val resultJson: Future[JsValue] =
      result.map { persons => Json.toJson(persons) }

    resultJson.map { results =>
      val title = results \\ "title"
      val url = results \\ "url"
      val description = results \\ "body"
      val queryData: Seq[((JsValue, JsValue), JsValue)] = title.zip(url).zip(description)
      Ok(views.html.result(queryData))
    }
  }
} 
开发者ID:slideon,项目名称:Scrawler-frontend,代码行数:56,代码来源:HomeController.scala


示例3: ApiController

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

import java.util.UUID
import javax.inject.{Inject, Singleton}

import models.RestResource
import play.api.libs.json.{JsError, JsValue, Json}
import play.api.mvc._

import scala.concurrent.Future

@Singleton
class ApiController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def index: Action[AnyContent] = {
    val resources = Seq(RestResource(UUID.randomUUID(), "name 1", "link 2"),
                        RestResource(UUID.randomUUID(), "name 2", "link 2"))
    Action.async {
      val json = Json.toJson(resources)
      Future.successful(Ok(json))
    }
  }

  def show(id: UUID): Action[AnyContent] = {
    Action.async {
      implicit request =>
        val json = Json.toJson(RestResource(id, "name x", "link x"))
        Future.successful(Ok(json))
    }
  }

  def process: Action[JsValue] = Action(parse.json) { implicit request =>
    request.body.validate[RestResource]
      .fold(
        errors =>
          BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors))),
        restResource => {
          println(restResource)
          Ok(Json.toJson(restResource))
        }
      )
  }

  def delete(id: String) = ???

  def update(id: String) = ???

} 
开发者ID:kamilduda,项目名称:play-hateoas,代码行数:49,代码来源:ApiController.scala


示例4: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:27,代码来源:ApplicationTimer.scala


示例5: MerchantProfileServiceImpl

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

import java.util.UUID

import com.google.inject.Inject
import daos.merchant.MerchantProfileDAO
import models.MerchantInfo
import play.api.libs.concurrent.Execution.Implicits._
import services.merchant.MerchantProfileService

import scala.concurrent.Future

class MerchantProfileServiceImpl @Inject() (merchantProfileDAO: MerchantProfileDAO) extends MerchantProfileService {

  def edit(userID: UUID, profile: MerchantInfo): Future[MerchantInfo] = {
    merchantProfileDAO.find(userID).flatMap {
      case Some(merchantInfo) =>
        merchantProfileDAO.save(userID, profile)
      case None => merchantProfileDAO.save(userID, profile)
    }
  }
  def view(userID: UUID): Future[Option[MerchantInfo]] = merchantProfileDAO.find(userID)

} 
开发者ID:Bakuchi,项目名称:certification,代码行数:25,代码来源:MerchantProfileServiceImpl.scala


示例6: BasicExemple

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

import helpers._
import helpers.SorusDSL._
import scala.concurrent.Future
import scalaz._

class BasicExemple extends Sorus {

  // Sample User class
  case class User(id:Option[Long], email:String, validate:Boolean)

  def doSomething(): Future[Fail\/User] = {
    for {
      user <- loadUser(12L)       ?| "Error while loading user"     // <- you don't create Fail yoursefl but the ?| operator do it for you
      _    <- user.validate       ?| "Account need to be validated"
      _    <- logUserAction(user) ?| ()                             // <- You can just forward underlying Fail without adding a message
    } yield {
      user
    }
  }

  private def loadUser(id:Long):Future[Option[User]] = {
    // Load it from DB / API / Services ...
    Future.successful(Some(User(Some(id), "[email protected]", false)))
  }

  private def logUserAction(user:User):Future[Fail\/Unit] = {
    for {
      id <- user.id ?| "Can't log action of user wihtout id"
    } yield {
      println(s"user $id access the resource")
    }
  }
} 
开发者ID:Driox,项目名称:sorus,代码行数:36,代码来源:ExampleSorus.scala


示例7: MerchantCertificatesServiceImpl

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

import java.util.UUID

import com.google.inject.Inject
import daos.merchant.{ MerchantAreasDAO, MerchantCertificatesDAO }
import daos.util.CertificateDAO
import models._
import services.merchant.{ MerchantAreasService, MerchantCertificatesService }

import scala.concurrent.ExecutionContext.Implicits._
import scala.concurrent.Future

class MerchantCertificatesServiceImpl @Inject() (merchantCertificatesDAO: MerchantCertificatesDAO, certDAO: CertificateDAO) extends MerchantCertificatesService {

  def add(userID: UUID, cert: MerchantCertificate): Future[MerchantCertificate] = merchantCertificatesDAO.save(userID, cert)
  def edit(cert: MerchantCertificate): Future[MerchantCertificate] = certDAO.save(cert)
  def view(userID: UUID): Future[MerchantCertificates] = merchantCertificatesDAO.find(userID)
  def clear(userID: UUID): Future[MerchantCertificates] = merchantCertificatesDAO.clear(userID)
  def deleteOne(userID: UUID, cert: MerchantCertificate): Future[MerchantCertificate] = {
    certDAO.delete(cert)
    merchantCertificatesDAO.deleteOne(userID, cert)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:25,代码来源:MerchantCertificatesServiceImpl.scala


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

} 
开发者ID:ZDevelop94,项目名称:ZolvedIT,代码行数:25,代码来源:ExampleFilter.scala


示例9: getDocuments

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

import scala.concurrent.Future


trait DocumentRepository {
  def getDocuments: Future[List[Ticket]]
  def getDocument(search: String): Future[List[Ticket]]
  def getNoWatermarks: Future[List[Ticket]]
  def getNoWatermark(search: String): Future[List[Ticket]]
}

final class DocumentRepositoryImpl extends DocumentRepository {

  private val documents = List(
    new Book("The Dark Code", "Bruce Wayne", "Science"),
    new Book("How to make money", "Dr. Evil", "Business"),
    new Book("How to make more money", "Dr. very Evil", "Business"),
    new Journal("Journal of human flight routes", "Clark Kent"),
    new Journal("Why can't all bats fly", "Bruce Wayne"),
//    two examples of documents without watermark
    new Journal("test journal", ""),
    new Book("test book", "", "")
  )

  val syncSet = scala.collection.mutable.LinkedHashSet.synchronized(documents)

  def getTickets(docs: List[Document]):List[Ticket] = {
    val t = docs.foldRight(List[Ticket]())((a,b) => Ticket(a.watermark)::b)

    val n = docs.grouped(5)

    def test(l: List[Document], acc: List[List[Document]], count: Int, temp: List[Document]): List[List[Document]] = l match {
      case Nil => acc
      case h :: t => if (count==0) test(t, temp::acc, 5, List()) else test(t, acc, count-1, h::temp)
    }

    n.flatMap(t => t.foldRight(List[Ticket]())((a,b) => Ticket(a.watermark)::b)).toList
  }

  def getDocuments: Future[List[Ticket]] = Future.successful(getTickets(documents))

  def getDocument(search: String): Future[List[Ticket]] = {
    val t = documents.filter(d => d.title.contains(search))

    Future.successful(getTickets(t))
  }

  def getNoWatermarks: Future[List[Ticket]] = {
    val t = documents.filter(d => d.noWatermark)
    Future.successful(getTickets(t))
  }

  def getNoWatermark(search: String): Future[List[Ticket]] = {
    val t = documents.filter(d => d.noWatermark && d.title.contains(search))
    Future.successful(getTickets(t))
  }


} 
开发者ID:devknutst,项目名称:watermarkAkka,代码行数:61,代码来源:DocumentRepository.scala


示例10: ResetPasswordController

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

import java.util.UUID
import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future

class ResetPasswordController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv],
  userService: UserService,
  authInfoRepository: AuthInfoRepository,
  passwordHasherRegistry: PasswordHasherRegistry,
  authTokenService: AuthTokenService
)
  extends Controller with I18nSupport {

  def view(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).map {
      case Some(authToken) => Ok(views.html.resetPassword(new myform.MyResetPasswordForm(), token))
      case None => Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link"))
    }
  }

  def submit(token: UUID) = silhouette.UnsecuredAction.async { implicit request =>
    authTokenService.validate(token).flatMap {
      case Some(authToken) =>
        new myform.MyResetPasswordForm().bindFromRequest match {
          case form: myform.MyResetPasswordForm => Future.successful(BadRequest(views.html.resetPassword(form, token)))
          case data: myform.MyResetPasswordFormData => userService.retrieve(authToken.userID).flatMap {
            case Some(user) if user.loginInfo.providerID == CredentialsProvider.ID =>
              val passwordInfo = passwordHasherRegistry.current.hash(data.password)
              authInfoRepository.update[PasswordInfo](user.loginInfo, passwordInfo).map { _ =>
                Redirect(routes.SignInController.view()).flashing("success" -> Messages("password.reset"))
              }
            case _ => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
          }
        }
      case None => Future.successful(Redirect(routes.SignInController.view()).flashing("error" -> Messages("invalid.reset.link")))
    }
  }
} 
开发者ID:serversideapps,项目名称:silhmojs,代码行数:53,代码来源:ResetPasswordController.scala


示例11: ForgotPasswordController

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.{ AuthTokenService, UserService }
import models.daos._
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ Email, MailerClient }
import play.api.mvc.Controller
import utils.auth.DefaultEnv

import scala.concurrent.Future

class ForgotPasswordController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv],
  userService: UserService,
  authTokenService: AuthTokenService,
  mailerClient: MailerClient,
  envDAO: EnvDAO
)
  extends Controller with I18nSupport {

  def view = silhouette.UnsecuredAction.async { implicit request =>
    Future.successful(Ok(views.html.forgotPassword(new myform.MyForgotPasswordForm())))
  }

  def submit = silhouette.UnsecuredAction.async { implicit request =>
    new myform.MyForgotPasswordForm().bindFromRequest match {
      case form: myform.MyForgotPasswordForm => Future.successful(BadRequest(views.html.forgotPassword(form)))
      case data: myform.MyForgotPasswordFormData => {
        val email = data.email
        val loginInfo = LoginInfo(CredentialsProvider.ID, email)
        val result = Redirect(routes.SignInController.view()).flashing("info" -> Messages("reset.email.sent"))
        userService.retrieve(loginInfo).flatMap {
          case Some(user) if user.email.isDefined =>
            authTokenService.create(user.userID).map { authToken =>
              val url = routes.ResetPasswordController.view(authToken.id).absoluteURL()
              println("url " + url)
              if (envDAO.getDosendmail) mailerClient.send(Email(
                subject = Messages("email.reset.password.subject"),
                from = Messages("email.from"),
                to = Seq(email),
                bodyText = Some(views.txt.emails.resetPassword(user, url).body),
                bodyHtml = Some(views.html.emails.resetPassword(user, url).body)
              ))
              result
            }
          case None => Future.successful(result)
        }
      }
    }
  }
} 
开发者ID:serversideapps,项目名称:silhmojs,代码行数:58,代码来源:ForgotPasswordController.scala


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

} 
开发者ID:scalajs-io,项目名称:mongoose,代码行数:44,代码来源:MongoDBTestSupport.scala


示例13: ConsulStoreActorMapper

//设置package包名称以及导入依赖的类
package io.vamp.persistence.consul

import java.util.Base64

import akka.http.scaladsl.model.ContentTypes
import io.vamp.common.{ ClassMapper, Config }
import io.vamp.persistence.KeyValueStoreActor

import scala.concurrent.Future

class ConsulStoreActorMapper extends ClassMapper {
  val name = "consul"
  val clazz = classOf[ConsulStoreActor]
}

class ConsulStoreActor extends KeyValueStoreActor {

  private lazy val url = Config.string("vamp.persistence.key-value-store.consul.url")()

  override protected def info(): Future[Any] = httpClient.get[Any](s"$url/v1/agent/self") map { consul ?
    Map("type" ? "consul", "consul" ? consul)
  }

  override protected def all(path: List[String]): Future[List[String]] = {
    val key = pathToString(path)
    checked[List[String]](httpClient.get[List[String]](urlOf(path, keys = true), logError = false) recover { case _ ? Nil }) map { list ?
      list.map(_.substring(key.length))
    }
  }

  override protected def get(path: List[String]): Future[Option[String]] = {
    httpClient.get[List[_]](urlOf(path), logError = false) recover { case _ ? None } map {
      case head :: Nil ? Option(result(head.asInstanceOf[Map[_, _]]))
      case _           ? None
    }
  }

  override protected def set(path: List[String], data: Option[String]): Future[Any] = data match {
    case None        ? httpClient.delete(urlOf(path), logError = false)
    case Some(value) ? httpClient.put[Any](urlOf(path), value, contentType = ContentTypes.`text/plain(UTF-8)`)
  }

  private def urlOf(path: List[String], keys: Boolean = false) = {
    s"$url/v1/kv${pathToString(path)}${if (keys) "?keys" else ""}"
  }

  private def result(map: Map[_, _]): String = map.asInstanceOf[Map[String, _]].get("Value") match {
    case Some(value) if value != null ? new String(Base64.getDecoder.decode(value.asInstanceOf[String]))
    case _                            ? ""
  }
} 
开发者ID:magneticio,项目名称:vamp-consul,代码行数:52,代码来源:ConsulStoreActor.scala


示例14: PullRequestSampleClient

//设置package包名称以及导入依赖的类
package de.stema.pullrequests.client

import java.io.{File, FileInputStream}
import javax.inject.Inject

import de.stema.pullrequests.dto.{ProjectDTO, PullRequestDTO}
import de.stema.util.JsonObjectMapper
import play.api.libs.json.Json

import scala.concurrent.Future


class PullRequestSampleClient @Inject()(jsonObjectMapper: JsonObjectMapper
                                       ) extends PullRequestClient {

  def getPullRequests(configuration: String): Seq[Future[ProjectDTO]] = {
    val jsonFile = new File("conf/testcontent.json")

    val stream = new FileInputStream(jsonFile)
    val json = try {
      Json.parse(stream)
    } finally {
      stream.close()
    }
    val prs = jsonObjectMapper.getInstances[PullRequestDTO](json.toString())
    Seq(Future.successful(ProjectDTO("testProject", prs)))
  }
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:29,代码来源:PullRequestSampleClient.scala


示例15: PullRequestClientModule

//设置package包名称以及导入依赖的类
package de.stema.pullrequests.client

import de.stema.pullrequests.dto.ProjectDTO
import play.api.inject.{Binding, Module}
import play.api.{Configuration, Environment}

import scala.concurrent.Future


class PullRequestClientModule extends Module {
  def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      if(configuration.getBoolean("offline").getOrElse(false)) {
        bind[PullRequestClient].to[PullRequestSampleClient]
    } else {
        bind[PullRequestClient].to[PullRequestGitHubClient]
    })
  }
}

abstract class PullRequestClient {
  def getPullRequests(configuration: String): Seq[Future[ProjectDTO]]
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:24,代码来源:PullRequestClientModule.scala


示例16: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:fahadaz,项目名称:birdie,代码行数:27,代码来源:ApplicationTimer.scala


示例17: PipeableFuture

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

import language.implicitConversions
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.{ Failure, Success }
import akka.actor.{ Status, ActorRef, Actor }
import akka.actor.ActorSelection

trait PipeToSupport {

  final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) {
    def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
      future onComplete {
        case Success(r) ? recipient ! r
        case Failure(f) ? recipient ! Status.Failure(f)
      }
      future
    }
    def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
      future onComplete {
        case Success(r) ? recipient ! r
        case Failure(f) ? recipient ! Status.Failure(f)
      }
      future
    }
    def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = {
      pipeTo(recipient)(sender)
      this
    }
    def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender)
    def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = {
      pipeToSelection(recipient)(sender)
      this
    }
  }

  
  implicit def pipe[T](future: Future[T])(implicit executionContext: ExecutionContext): PipeableFuture[T] = new PipeableFuture(future)
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:41,代码来源:PipeToSupport.scala


示例18: DRoute

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl

import akka.http.documenteddsl.documentation.Documentation
import akka.http.scaladsl.server.{RequestContext, _}

import scala.concurrent.Future

class DRoute(
  underlying: Route,
  writer: Documentation => Documentation = identity) extends Route {

  def selfDescribe(doc: Documentation): Documentation = writer apply doc
  override def apply(ctx: RequestContext): Future[RouteResult] = underlying apply ctx
  override def toString = "DocumentedRoute()"
}

object DRoute {
  def apply(r: Route) = new DRoute(r)
  def maybe(r: Route): DRoute = {
    r match {
      case r: DRoute => r
      case _ => new DRoute(r)
    }
  }
  def copyDocumentation(from: DRoute, to: Route): DRoute = new DRoute(to, from.selfDescribe)
} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:27,代码来源:DRoute.scala


示例19: KmsDecrypter

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

import java.nio.ByteBuffer

import com.amazonaws.regions.Regions
import com.amazonaws.regions.Regions.US_WEST_2
import com.amazonaws.services.kms.model.DecryptRequest
import com.amazonaws.services.kms.{AWSKMSAsync, AWSKMSAsyncClientBuilder}
import com.dwolla.awssdk.kms.KmsDecrypter._
import com.dwolla.awssdk.utils.ScalaAsyncHandler.Implicits._

import scala.concurrent.{ExecutionContext, Future}

class KmsDecrypter(region: Regions = US_WEST_2) extends AutoCloseable {
  protected lazy val asyncClient: AWSKMSAsync = AWSKMSAsyncClientBuilder.standard().withRegion(US_WEST_2).build()

  def decrypt[A](transformer: Transform[A], cryptotext: A)(implicit ec: ExecutionContext): Future[Array[Byte]] = new DecryptRequest()
    .withCiphertextBlob(ByteBuffer.wrap(transformer(cryptotext)))
    .via(asyncClient.decryptAsync)
    .map(_.getPlaintext.array())

  def decrypt[A](transform: Transform[A], cryptotexts: (String, A)*)(implicit ec: ExecutionContext): Future[Map[String, Array[Byte]]] = {
    Future.sequence(cryptotexts.map {
      case (name, cryptotext) ? decrypt(transform, cryptotext).map(name ? _)
    }).map(Map(_: _*))
  }

  def decryptBase64(cryptotexts: (String, String)*)(implicit ec: ExecutionContext): Future[Map[String, Array[Byte]]] = decrypt(base64DecodingTransform, cryptotexts: _*)

  override def close(): Unit = asyncClient.shutdown()
}

object KmsDecrypter {
  type Transform[A] = A ? Array[Byte]

  val noopTransform: Transform[Array[Byte]] = (x: Array[Byte]) ? x
  val base64DecodingTransform: Transform[String] = javax.xml.bind.DatatypeConverter.parseBase64Binary
} 
开发者ID:Dwolla,项目名称:scala-aws-utils,代码行数:39,代码来源:KmsDecrypter.scala


示例20: ScalaAsyncHandler

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

import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.handlers.AsyncHandler

import scala.concurrent.{Future, Promise}

class ScalaAsyncHandler[A <: AmazonWebServiceRequest, B] extends AsyncHandler[A, B] {
  private val promise = Promise[B]
  val future: Future[B] = promise.future

  override def onError(exception: Exception): Unit = promise.failure(exception)
  override def onSuccess(request: A, result: B): Unit = promise.success(result)
}

object ScalaAsyncHandler {
  object Implicits {
    implicit class RequestHolder[S <: AmazonWebServiceRequest](req: S) {
      class BoundRequestHolder[T] {
        def via(body: AwsAsyncFunction[S, T]): Future[T] = {
          val handler = new ScalaAsyncHandler[S, T]
          body(req, handler)
          handler.future
        }
      }

      @deprecated(message = "use RequestHolder.via(…) directly", since = "1.3.0")
      def to[T]: BoundRequestHolder[T] = new BoundRequestHolder[T]

      def via[T](body: AwsAsyncFunction[S, T]): Future[T] = new BoundRequestHolder[T].via(body)
    }
  }
} 
开发者ID:Dwolla,项目名称:scala-aws-utils,代码行数:34,代码来源:ScalaAsyncHandler.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala ActorSystem类代码示例发布时间:2022-05-23
下一篇:
Scala FileInputFormat类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap