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


Scala future类代码示例

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


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

示例6: 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

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

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

示例9: 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

示例10: 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

示例11: 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

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

示例13: 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

示例14: 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

示例15: 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


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