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

Scala Timeout类代码示例

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

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



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

示例1: Main

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

import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration._
import akka.actor._
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.{Config, ConfigFactory}

object Main extends LazyLogging with App with RestInterface {

  val config: Config = ConfigFactory.load().getConfig("main")
  val logLevel: String = config.getString("logLevel")
  val appName: String = config.getString("appName")
  val host: String = config.getString("host")
  val port: Int = config.getInt("port")

  implicit val system = ActorSystem("map-management-service")
  implicit val materializer = ActorMaterializer()

  implicit val executionContext = system.dispatcher
  implicit val timeout = Timeout(10 seconds)

  val api = routes

  Http().bindAndHandle(handler = api, interface = host, port = port) map {
    binding =>
      logger.info(s"REST interface bound to ${binding.localAddress}")
  } recover {
    case ex =>
      logger.error(s"REST interface could not bind to $host:$port",
                   ex.getMessage)
  }
} 
开发者ID:navicore,项目名称:oemap-server,代码行数:37,代码来源:Main.scala


示例2: Boot

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.util.Timeout

import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._

object Boot extends VoteService {

  implicit val system = ActorSystem("user-system")
  implicit val timeout: Timeout = Timeout(10.seconds)
  implicit val executionContext: ExecutionContextExecutor = system.dispatcher
  implicit val materializer = ActorMaterializer()

  def main(args: Array[String]) {
    val port = 5000
    val bindingFuture = Http().bindAndHandle(routes, "0.0.0.0", port)
    println(s"Server online at http://localhost:$port/")
//    bindingFuture
//      .onComplete(e => {
//        println(s"Binding failure, terminating: ${e}")
//        system.terminate()
//      }) // and shutdown when done
  }
} 
开发者ID:divanvisagie,项目名称:vote,代码行数:29,代码来源:Boot.scala


示例3: Request

//设置package包名称以及导入依赖的类
package org.freetrm.eventstore.http

import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.Config
import org.freetrm.eventstore.utils.Log
import org.freetrm.eventstore.{EventSourceReader, EventSourceWriter}
import scaldi.Module

import scala.concurrent.Future
import scala.concurrent.duration._


case class Request(client: ActorRef, req: HttpRequest)

class WebService extends Module with Log {
  implicit lazy val system = inject[ActorSystem]
  implicit lazy val mat = ActorMaterializer()

  def start(): Future[ServerBinding] = {

    val conf = inject[Config]

    implicit val timeout = Timeout(5.seconds)
    val interface = conf.getString("www-service.interface")
    val port = conf.getInt("www-service.port")

    log.info(s"Starting http server on $interface:$port")
    
    Http().bindAndHandle(service.flow, interface, port)
  }

  def stop() {}

  def service: EventStoreHttpServer = {
    implicit val system = inject[ActorSystem]
    val conf = inject[Config]

    val cookie = conf.getString("www-service.cookie")
    new EventStoreHttpServer(
      inject[EventSourceWriter],
      inject[EventSourceReader], 
      cookie)
  }
} 
开发者ID:topaztechnology,项目名称:eventstore,代码行数:50,代码来源:WebService.scala


示例4: User

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

import akka.util.Timeout
import com.github.dunnololda.scage.support.Vec
import com.sunway.screen.gamescreen.Character
import com.sunway.util.MutableString

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._

object User {

  val WAITING_STATE = 0
  val READY_STATE = 1
  val maxPlayerInRoom = 2
  val HOST_ROOM_ID = 0

  implicit val timeout = Timeout(5.seconds)


  val targetRoomNum: MutableString = new MutableString("0")
  var myName: MutableString = new MutableString(System.getProperty("user.name"))
  var myRoomPos: MutableString = new MutableString("")
  var myPassword: MutableString = new MutableString("")
  var playerNames = Array.fill[MutableString](maxPlayerInRoom)(new MutableString(""))
  var playerRoomStats = Array.fill[MutableString](maxPlayerInRoom)(new MutableString(""))
  var gameState = WAITING_STATE
  var mapState = WAITING_STATE
  var readyPlay = false
  var roomStateSeenUser = new MutableString("WAITING STATE")
  var newPlayerJoining = false
  var newPlayerPos: Option[Int] = None
  var newPlayerVec = Vec()
  var oldPlayerLeave = false
  var oldPlayerPos: Option[Int] = None


  //GAMEPLAY
  var charactersPos: Array[Vec] = Array(Vec(20, ConfigurationObject.windowHeight / 2 - 70), (Vec(150, ConfigurationObject.windowHeight / 2 - 70)))
  var charactersObj = Array.fill[Character](maxPlayerInRoom)(null)
  var mapInformation = List[ArrayBuffer[Tuple2[Float, Float]]]()

} 
开发者ID:MrRexZ,项目名称:Multiplayer-Race-Shooter-Game,代码行数:44,代码来源:User.scala


示例5: TestKitExtension

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

import com.typesafe.config.Config
import akka.util.Timeout
import akka.actor.{ ExtensionId, ActorSystem, Extension, ExtendedActorSystem }
import scala.concurrent.duration.FiniteDuration

object TestKitExtension extends ExtensionId[TestKitSettings] {
  override def get(system: ActorSystem): TestKitSettings = super.get(system)
  def createExtension(system: ExtendedActorSystem): TestKitSettings = new TestKitSettings(system.settings.config)
}

class TestKitSettings(val config: Config) extends Extension {

  import akka.util.Helpers._

  val TestTimeFactor = config.getDouble("akka.test.timefactor").
    requiring(tf ? !tf.isInfinite && tf > 0, "akka.test.timefactor must be positive finite double")
  val SingleExpectDefaultTimeout: FiniteDuration = config.getMillisDuration("akka.test.single-expect-default")
  val TestEventFilterLeeway: FiniteDuration = config.getMillisDuration("akka.test.filter-leeway")
  val DefaultTimeout: Timeout = Timeout(config.getMillisDuration("akka.test.default-timeout"))
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:23,代码来源:TestKitExtension.scala


示例6: TransactorExtension

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

import akka.actor.{ ActorSystem, ExtensionId, ExtensionIdProvider, ExtendedActorSystem }
import akka.actor.Extension
import com.typesafe.config.Config
import akka.util.Timeout
import scala.concurrent.duration.Duration
import java.util.concurrent.TimeUnit.MILLISECONDS


@deprecated("akka.transactor will be removed", "2.3")
object TransactorExtension extends ExtensionId[TransactorSettings] with ExtensionIdProvider {
  override def get(system: ActorSystem): TransactorSettings = super.get(system)
  override def lookup: TransactorExtension.type = TransactorExtension
  override def createExtension(system: ExtendedActorSystem): TransactorSettings = new TransactorSettings(system.settings.config)
}

@deprecated("akka.transactor will be removed", "2.3")
class TransactorSettings(val config: Config) extends Extension {
  import config._
  val CoordinatedTimeout: Timeout = Timeout(Duration(getMilliseconds("akka.transactor.coordinated-timeout"), MILLISECONDS))
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:23,代码来源:TransactorExtension.scala


示例7: ActorSpec

//设置package包名称以及导入依赖的类
package com.github.j5ik2o.reactive.redis

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.testkit.{ ImplicitSender, TestKit }
import akka.util.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, DiagrammedAssertions, FunSpecLike }

import scala.concurrent.duration._

abstract class ActorSpec(_system: ActorSystem)
    extends TestKit(_system)
    with ImplicitSender
    with FunSpecLike
    with DiagrammedAssertions
    with BeforeAndAfterAll
    with TimeFactorSupport
    with ScalaFutures {

  implicit override val patienceConfig: PatienceConfig = PatienceConfig(15 * timeFactor seconds)

  implicit val materializer = ActorMaterializer()

  implicit val timeout = Timeout(15 seconds)

  override protected def afterAll(): Unit = {
    shutdown()
    super.beforeAll()
  }

} 
开发者ID:j5ik2o,项目名称:reactive-redis,代码行数:33,代码来源:ActorSpec.scala


示例8: GoogleBooksApiStub

//设置package包名称以及导入依赖的类
package org.packtpublishing.stub

import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern._
import akka.util.Timeout

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

import spray.can.Http
import spray.can.server.ServerSettings
import spray.routing._
import Directives._

class GoogleBooksApiStub(val route: Route) {
  implicit val system = ActorSystem("google-books-api")
  implicit val timeout: Timeout = 3 seconds 

  val settings = ServerSettings(system).copy(sslEncryption = false)
  val handler = system.actorOf(Props(new GoogleBooksRestService(route)), name = "handler")

  def start(port: Int) = 
    Await.ready(IO(Http) ? Http.Bind(handler, 
      interface = "localhost", port = port, settings = Some(settings)), timeout.duration)
      
  def stop() = {
    IO(Http) ? Http.CloseAll
    system.stop(handler)
  }
}

sealed class GoogleBooksRestService(val route: Route) extends HttpServiceActor {
  def receive = runRoute {
    route
  }
} 
开发者ID:allansene,项目名称:spray-scala-akka-book-catalog,代码行数:38,代码来源:GoogleBooksApiStub.scala


示例9: HttpClientAsActor

//设置package包名称以及导入依赖的类
package com.scalaio.http.client.actor

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.stream.{ActorMaterializer, ActorMaterializerSettings}
import akka.util.{ByteString, Timeout}
import play.api.libs.json.Json

import scala.concurrent.Future
import scala.concurrent.duration._

class HttpClientAsActor(notifier: ActorRef) extends Actor with ActorLogging {

  import akka.pattern.pipe
  import context.dispatcher
  implicit val timeout = Timeout(5 seconds)
  implicit val materializer = ActorMaterializer(ActorMaterializerSettings(context.system))

  val http = Http(context.system)

  override def preStart() = {
    http
      .singleRequest(HttpRequest(method = GET, uri = "https://jsonplaceholder.typicode.com/posts/1"))
      .pipeTo(self)
  }

  def receive = {
    case HttpResponse(StatusCodes.OK, headers, entity, _) =>
      val response: Future[ByteString] = entity.dataBytes.runFold(ByteString(""))(_ ++ _)
      log.info(s"got response $headers $entity")
      response pipeTo self
      context become handlingMessage

    case [email protected](code, _, _, _) =>
      log.warning("Request failed, response code: " + code)
      resp.discardEntityBytes()
  }

  def handlingMessage: Receive = {
    case content: ByteString =>
      log.info("Success was OK: " + content)
      val contentAsString = (Json.parse(content.utf8String) \ "title").as[String]
      notifier ! contentAsString
      context become receive
  }

}

object HttpClientAsActor {

  def props(notifier: ActorRef) = Props(classOf[HttpClientAsActor], notifier)

} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:56,代码来源:HttpClientAsActor.scala


示例10: SampleRoutes

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

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.util.Timeout
import com.queirozf.utils.ResponseUtils._


class SampleRoutes(implicit val system: ActorSystem) {

  import system.dispatcher
  implicit val timeout = Timeout(32, TimeUnit.MILLISECONDS)

  // sample route: localhost:5000/v1/999/test
  def routes = {
    pathPrefix(LongNumber) { param =>
      path("test") {
        get {
          getTest(param)
        }
      }
    }
  }

  private def getTest(param: Long): Route = {
    complete {
      JsonOk(param.toString)
    }
  }
} 
开发者ID:queirozfcom,项目名称:akka-http-docker-aws-code-pipeline-beanstalk,代码行数:34,代码来源:SampleRoutes.scala


示例11: Main

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

import akka.actor.PoisonPill
import akka.util.Timeout
import com.bau5.sitetracker.common.BaseProvider
import com.bau5.sitetracker.common.Events.{Message, MessageAll, SaveRequest}

import scala.concurrent.duration._
import scala.io.StdIn


object Main extends BaseProvider("ServerSystem", "") {
  override implicit val timeout: Timeout = Timeout(5 seconds)

  val messageAll = "message-all (.+)".r

  def main(args: Array[String]) {
    val serverActor = newActor[ServerActor]("server")
    serverActor ! LoadSavedData

    while (true) StdIn.readLine("> ") match {
      case "save" =>
        serverActor ! SaveRequest
      case "quit" =>
        serverActor ! SaveRequest
        serverActor ! PoisonPill
        sys.exit(0)
      case messageAll(msg) =>
        serverActor ! MessageAll(Message(msg))
      case _ =>
        println("Unrecognized input.")
    }
  }
} 
开发者ID:rickbau5,项目名称:SiteTracker,代码行数:35,代码来源:Main.scala


示例12: handleProof

//设置package包名称以及导入依赖的类
package wow.auth.handlers

import akka.pattern.ask
import akka.util.Timeout
import wow.auth.AccountsState
import wow.auth.AccountsState.IsOnline
import wow.auth.data.Account
import wow.auth.protocol.AuthResults
import wow.auth.protocol.packets.{ClientLogonProof, ServerLogonProof, ServerLogonProofFailure, ServerLogonProofSuccess}
import wow.auth.session.AuthSession.EventIncoming
import wow.auth.session._
import wow.auth.utils.PacketSerializer

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


trait LogonProofHandler {
  this: AuthSession =>

  def handleProof: StateFunction = {
    case Event(EventIncoming(bits), ChallengeData(login, srp6Identity, srp6Challenge)) =>
      log.debug("Received proof")
      val packet = PacketSerializer.deserialize[ClientLogonProof](bits)
      log.debug(packet.toString)

      srp6.verify(login, packet.clientKey, packet.clientProof, srp6Identity, srp6Challenge) match {
        case Some(srp6Validation) =>
          val accountState = context.actorSelection(AccountsState.ActorPath)

          implicit val timeout = Timeout(5 seconds)
          val askIsOnline = (accountState ? IsOnline(login)).mapTo[Boolean]
          val isOnline = Await.result(askIsOnline, timeout.duration)

          if (isOnline) {
            sendPacket(ServerLogonProof(AuthResults.FailAlreadyOnline, None, Some(ServerLogonProofFailure())))

            goto(StateFailed) using NoData
          } else {
            Account.saveSessionKey(login, srp6Validation.sharedKey)

            sendPacket(ServerLogonProof(AuthResults.Success,
              Some(ServerLogonProofSuccess(srp6Validation.serverProof)),
              None))

            goto(StateRealmlist) using NoData
          }
        case None =>
          sendPacket(ServerLogonProof(AuthResults.FailUnknownAccount, None, Some(ServerLogonProofFailure())))
          goto(StateFailed) using NoData
      }
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:54,代码来源:LogonProofHandler.scala


示例13: Withdraw

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

import scala.concurrent.stm.atomic
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.util.Timeout

import scala.concurrent.duration._

case class Withdraw(amount:Int)
case class Deposit(amount:Int)

case class TransferMessage(amount: Int,
                           from: ActorRef,
                           to: ActorRef)

class Account(name: String, var balance: Int) extends Actor {
  override def receive: Receive = {
    case Withdraw(amount) => {
      if(this.balance > amount) {
        this.balance -= this.balance
        println(s"${name} withdraw: ${amount}, balance: ${balance}")
      } else throw new Exception("insufficient balance")
    }
    case Deposit(amount) => {
      this.balance += amount
      println(s"${name} deposit: ${amount}, balance: ${balance}")
    }
  }
}

class Transfer extends Actor {
  implicit val timeout = new Timeout(1 seconds)

  override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
    message.foreach(_ => sender ! "Failed")
    super.preRestart(reason, message)
  }

  override def receive: Receive = {
    case TransferMessage(amount, from, to) => {
       atomic { implicit tnx => {
        from ! Withdraw(amount)
        to ! Deposit(amount)
      }}
    }
  }
}

object TransferTransaction extends App {
  implicit val system = ActorSystem("actor-system")
  import system.dispatcher

  val transfer = system.actorOf(Props(new Transfer), "transfer")
  val from = system.actorOf(Props(new Account("from", 60)))
  val to = system.actorOf(Props(new Account("to", 20)))

  transfer ! TransferMessage(70, from, to)

} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:60,代码来源:TransferTransaction.scala


示例14: Boot

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

import java.io.InputStream
import java.security.{KeyStore, SecureRandom}
import javax.net.ssl._

import akka.http.scaladsl._
import akka.util.Timeout
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._
import scala.io.{Source, StdIn}

object Boot extends App with MyRouteService {

  import ActorImplicits._

  implicit val timeout = Timeout(5.seconds)

  val conf = ConfigFactory.load().getConfig("settings.server")
  val host = conf.getString("host")
  val httpBindingFuture = Http().bindAndHandle(myRoute, host, conf.getInt("http_port"))
  val httpsBindingFuture =
    Http().bindAndHandle(myRoute, host, conf.getInt("https_port"), SSLConfig.https)
  println(s"Server online at http://$host:8080/\nPress RETURN to stop...")
  if (System.getProperty("dev") != null) {
    StdIn.readLine() // let it run until user presses return
    Seq(httpBindingFuture, httpsBindingFuture).foreach { _
      .flatMap(_.unbind())
      .onComplete(_ ? system.terminate())
    }
  }
}

object SSLConfig {
  val https: HttpsConnectionContext = {

    val password: Array[Char] = Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("password")).toArray.filter(_ != '\n')

    val ks: KeyStore = KeyStore.getInstance("jks")
    val keystore: InputStream = getClass.getClassLoader.getResourceAsStream("zhranklin.com.jks")

    require(keystore != null, "Keystore required!")
    ks.load(keystore, password)

    val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(ks, password)

    val tmf: TrustManagerFactory = TrustManagerFactory.getInstance("SunX509")
    tmf.init(ks)

    val sslContext: SSLContext = SSLContext.getInstance("TLS")
    sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom)
    ConnectionContext.https(sslContext)
  }

} 
开发者ID:zhranklin,项目名称:Private_Blog,代码行数:58,代码来源:Boot.scala


示例15: AkkademyDbSpec

//设置package包名称以及导入依赖的类
import akka.actor.{ActorSystem, Props}
import akka.testkit.TestActorRef
import akka.util.Timeout
import com.example.{AkkademyDb, ScalaPongActor, SetRequest}
import org.scalatest.{FunSpecLike, _}

import scala.concurrent.duration._

class AkkademyDbSpec extends FunSpecLike with Matchers {
  implicit val system = ActorSystem()
  implicit val timeout = Timeout(5 seconds)

  describe("akkademyDb") {
    describe("given SetRequest") {
      it("should place key/value into your map") {
        
        val actorRef = TestActorRef(new AkkademyDb)
        actorRef ! SetRequest("key", "value")

        val akkademyDb = actorRef.underlyingActor
        akkademyDb.map.get("key") should equal(Some("value"))
      }
    }
  }
}

class ScalaPongActorSpec extends FunSpecLike with Matchers {
  implicit val system = ActorSystem()
  implicit val timeout = Timeout(5 seconds)

  describe("scalaPongActor") {
    describe("given Ping") {
      it("should return message Pong") {

        val actorRef = system.actorOf(Props[ScalaPongActor], "PongFoo")
        actorRef ! "ping"

        true
      }
    }
  }
} 
开发者ID:hanchenyi,项目名称:FirstAkkaProject,代码行数:43,代码来源:AkkademyDbSpec.scala


示例16: ault

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.event

import java.util.concurrent.TimeUnit

import akka.util.Timeout
import org.rogach.scallop.ScallopConf
import mesosphere.marathon.api.v2.Validation.urlIsValid

import scala.concurrent.duration.FiniteDuration
import scala.concurrent.duration._

trait EventConf extends ScallopConf {
  lazy val eventSubscriber = opt[String](
    "event_subscriber",
    descr = "The event subscription module to use. E.g. http_callback.",
    required = false,
    noshort = true)

  lazy val httpEventEndpoints = opt[String](
    "http_endpoints",
    descr = "The URLs of the event endpoints added to the current list of subscribers on startup. " +
      "You can manage this list during runtime by using the /v2/eventSubscriptions API endpoint.",
    required = false,
    validate = { parseHttpEventEndpoints(_).forall(urlIsValid(_).isSuccess) },
    noshort = true).map(parseHttpEventEndpoints)

  lazy val httpEventCallbackSlowConsumerTimeout = opt[Long](
    "http_event_callback_slow_consumer_timeout",
    descr = "A http event callback consumer is considered slow, if the delivery takes longer than this timeout (ms)",
    required = false,
    noshort = true,
    default = Some(10.seconds.toMillis)
  )

  lazy val httpEventRequestTimeout = opt[Long](
    "http_event_request_timeout",
    descr = "A http event request timeout (ms)",
    required = false,
    noshort = true,
    default = Some(10.seconds.toMillis)
  )

  lazy val eventStreamMaxOutstandingMessages = opt[Int](
    "event_stream_max_outstanding_messages",
    descr = "The event stream buffers events, that are not already consumed by clients. " +
      "This number defines the number of events that get buffered on the server side, before messages are dropped.",
    noshort = true,
    default = Some(50)
  )

  private[event] def httpCallbacksEnabled: Boolean = eventSubscriber.get.contains("http_callback")

  private[this] def parseHttpEventEndpoints(str: String): List[String] = str.split(',').map(_.trim).toList

  def slowConsumerDuration: FiniteDuration = httpEventCallbackSlowConsumerTimeout().millis

  def eventRequestTimeout: Timeout = Timeout(httpEventRequestTimeout(), TimeUnit.MILLISECONDS)

  def zkTimeoutDuration: FiniteDuration
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:61,代码来源:EventConf.scala


示例17: UserService

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

import akka.util.Timeout
import com.pacbio.common.auth.{AuthenticatorProvider, Authenticator}
import com.pacbio.common.dependency.Singleton
import com.pacbio.common.models._
import spray.httpx.SprayJsonSupport._
import spray.json._
import DefaultJsonProtocol._

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits._

class UserService(authenticator: Authenticator) extends PacBioService {

  import PacBioJsonProtocol._

  implicit val timeout = Timeout(10.seconds)

  val manifest = PacBioComponentManifest(
    toServiceId("user"),
    "User Service",
    "0.1.0", "User Service")

  val userRoute =
    path("user") {
      authenticate(authenticator.wso2Auth) { user =>
        get {
          complete {
            ok {
              user
            }
          }
        }
      }
    }

  val routes = userRoute ~ pathPrefix("smrt-link") {userRoute}
}


trait UserServiceProvider {
  this: AuthenticatorProvider =>

  val userService: Singleton[UserService] = Singleton(() => new UserService(authenticator())).bindToSet(AllServices)
}

trait UserServiceProviderx {
  this: AuthenticatorProvider with ServiceComposer =>

  val userService: Singleton[UserService] = Singleton(() => new UserService(authenticator()))

  addService(userService)
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:55,代码来源:UserService.scala


示例18: StatusService

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

import akka.util.Timeout
import com.pacbio.common.dependency.Singleton
import com.pacbio.common.models._
import com.pacbio.common.services.utils.{StatusGeneratorProvider, StatusGenerator}
import spray.httpx.SprayJsonSupport._
import spray.json._
import DefaultJsonProtocol._

import scala.concurrent.duration._

class StatusService(statusGenerator: StatusGenerator) extends PacBioService {

  import PacBioJsonProtocol._

  implicit val timeout = Timeout(10.seconds)

  val manifest = PacBioComponentManifest(
    toServiceId("status"),
    "Status Service",
    "0.2.0", "Subsystem Status Service")

  val statusServiceName = "status"

  val routes =
    path(statusServiceName) {
      get {
        complete {
          ok {
            statusGenerator.getStatus
          }
        }
      }
    }
}


trait StatusServiceProvider {
  this: StatusGeneratorProvider =>

  val statusService: Singleton[StatusService] =
    Singleton(() => new StatusService(statusGenerator())).bindToSet(AllServices)
}

trait StatusServiceProviderx {
  this: StatusGeneratorProvider
    with ServiceComposer =>

  final val statusService: Singleton[StatusService] =
    Singleton(() => new StatusService(statusGenerator()))

  addService(statusService)
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:55,代码来源:StatusService.scala


示例19: doSendReceive

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

import akka.actor.{ActorRefFactory, ActorSystem}
import akka.util.Timeout
import spray.client.pipelining._
import spray.http._
import spray.httpx.unmarshalling._
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}


trait RestClient {

  implicit val system: ActorSystem
  implicit lazy val executionContext: ExecutionContext = system.dispatcher

  def doSendReceive(implicit refFactory: ActorRefFactory, executionContext: ExecutionContext): SendReceive = sendReceive

  def webGet[Rs: FromResponseUnmarshaller](path: String): Future[Rs] = {
    Get(path) ~> pipeline
  }

  def webPost[Rs: FromResponseUnmarshaller](req: HttpRequest): Future[Rs] = {
    req ~> pipeline
  }

  def pipeline[T: FromResponseUnmarshaller]: HttpRequest => Future[T] = {

    implicit val timeout: Timeout = Timeout(2 seconds)
    (
      doSendReceive
        ~> unmarshal[T]
      )
  }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:36,代码来源:RestClient.scala


示例20: UserRepositorySpec

//设置package包名称以及导入依赖的类
package org.cristal.repository

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestKit}
import akka.util.Timeout
import com.github.t3hnar.bcrypt._
import org.cristal.model.{NewUser, User}
import org.cristal.repository.UserRepository.UserCreated
import org.cristal.repository.dao.UserDAO
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito.when
import org.scalatest.concurrent.Eventually
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.Future
import scala.concurrent.duration._

class UserRepositorySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll with Eventually with MockitoSugar {
  implicit val duration: Timeout = 10 seconds
  def this() = this(ActorSystem("UserRepositorySpecSystem"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "An UserRepository Actor" should {
    "Create a new user" in {
      val userDAO = mock[UserDAO]
      val passowod = "my_password"
      val encryptedPassword = passowod.bcrypt
      when(userDAO.insert(any())).thenReturn(Future.successful(()))
      val userRepository = system.actorOf(UserRepository.props(userDAO))
      val newUser = NewUser("name", passowod, "[email protected]", "John", "Doe")
      userRepository ! UserRepository.CreateUser(newUser, self)
      expectMsgPF() {
        case UserCreated(User("name", encryptedPassword, "[email protected]", "John", "Doe")) => ()
      }
    }
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:43,代码来源:UserRepositorySpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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