本文整理汇总了Scala中scala.concurrent.ExecutionContext.Implicits.global类的典型用法代码示例。如果您正苦于以下问题:Scala global类的具体用法?Scala global怎么用?Scala global使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了global类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: Hellp
//设置package包名称以及导入依赖的类
import scala.scalajs.js
import scala.scalajs.js.Dynamic.global
import org.scalajs.dom
import scalatags.JsDom.all._
import shared.SharedMessages
import org.scalajs.dom.ext.Ajax
import scala.concurrent.ExecutionContext
object Hellp extends js.JSApp {
def main(): Unit = {
if (!js.isUndefined(global.window.console)) {
global.console.log("Welcome to your Play application's JavaScript!");
}
addItems
}
def addItems = {
import scala.concurrent.ExecutionContext.Implicits.global
dom.document
.getElementById("scalajsclientDiv")
.appendChild(ul(id := "itemList")(li("ScalaJS shouts out: ", em(SharedMessages.itWorks))).render)
timeAt("UTC")
timeAt("ECT")
}
def timeAt(tz: String)(implicit ec: ExecutionContext) = {
Ajax.get("/api/timeAt/" + tz).onSuccess {
case xhr =>
dom.document
.getElementById("itemList").appendChild(li(s"Time service (timeAt $tz): ", em(xhr.responseText)).render)
}
}
}
开发者ID:oswaldo,项目名称:lagom-scala-scalajs-scalatags,代码行数:38,代码来源:Hello.scala
示例2: ResultFetcherTest
//设置package包名称以及导入依赖的类
package com.piotrglazar.receiptlottery.core
import com.piotrglazar.receiptlottery.Token
import com.piotrglazar.receiptlottery.utils.ScalajHttpAdapter
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.scalatest.time.{Seconds, Span}
import org.scalatest.{FlatSpec, Matchers}
import scala.concurrent.ExecutionContext.Implicits.global
class ResultFetcherTest extends FlatSpec with Matchers with ScalaFutures {
implicit val timeout = PatienceConfig(Span(1, Seconds))
val resultFetcher = new ResultFetcher("https://loteriaparagonowa.gov.pl/wyniki", new ScalajHttpAdapter(2000), global)
val tokens = Table(("token", "result"),
(Token("D2T1UGL9M34"), true),
(Token("C91B2MGBM5F"), false))
"ResultFetcher" should "find result for token" in {
forAll(tokens) { (token: Token, expectedResult: Boolean) =>
// when
val result = resultFetcher.hasResult(token)
// then
result.futureValue shouldBe expectedResult
}
}
}
开发者ID:piotrglazar,项目名称:receipt-lottery,代码行数:33,代码来源:ResultFetcherTest.scala
示例3: Repository
//设置package包名称以及导入依赖的类
package org.globalnames
package index
package api
import javax.inject.Inject
import thrift.nameresolver.{NameInput, Request, Response, Service => NameResolverService}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future => ScalaFuture}
import com.twitter.bijection.Conversion.asMethod
import com.twitter.bijection.twitter_util.UtilBijections._
class Repository @Inject() (nameResolverClient: NameResolverService.FutureIface) {
def nameResolver(namesInput: Seq[NameInput],
dataSourceIds: Option[Seq[Int]],
preferredDataSourceIds: Option[Seq[Int]]): ScalaFuture[Seq[Response]] = {
val req = Request(names = namesInput,
dataSourceIds = dataSourceIds.getOrElse(Seq()),
preferredDataSourceIds = preferredDataSourceIds.getOrElse(Seq())
)
nameResolverClient.nameResolve(req).as[ScalaFuture[Seq[Response]]]
}
}
开发者ID:GlobalNamesArchitecture,项目名称:gnindex,代码行数:24,代码来源:Repository.scala
示例4: Restaurants
//设置package包名称以及导入依赖的类
package dao;
import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile
import play.api.Play
import slick.driver.PostgresDriver.api._
import scala.concurrent.Future
import model.CompleteRestaurant
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile
import play.api.Play
import slick.driver.PostgresDriver.api._
import scala.concurrent.Future
import model.CompleteRestaurant
import scala.concurrent.ExecutionContext.Implicits.global
import model.RestaurantTableDef
object Restaurants {
val dbConfig=DatabaseConfigProvider.get[JdbcProfile](Play.current)
val restaurants=TableQuery[RestaurantTableDef]
def list:Future[Seq[CompleteRestaurant]]={
dbConfig.db.run(restaurants.result)
}
def getById(id:Long): Future[Option[CompleteRestaurant]]={
dbConfig.db.run(restaurants.filter(_.id===id).result.headOption)
}
def save(restaurant:CompleteRestaurant):Future[String]={
dbConfig.db.run(restaurants+=restaurant).map(res => "Restaurant saved").recover{
case ex: Exception => ex.getCause.getMessage
}
}
def update(restaurant:CompleteRestaurant):Future[Int]={
dbConfig.db.run(restaurants.filter(_.id===restaurant.id).update(restaurant))
}
def delete(id:Long):Future[Int]={
dbConfig.db.run(restaurants.filter(_.id===id).delete)
}
}
开发者ID:MartinEliasQ,项目名称:AppEmpre-Dojo3-Scala,代码行数:41,代码来源:Restaurants.scala
示例5: Example
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import io.waylay.kairosdb.driver.KairosDB
import io.waylay.kairosdb.driver.Implicits._
import io.waylay.kairosdb.driver.models.KairosCompatibleType.KNumber
import io.waylay.kairosdb.driver.models.KairosQuery.QueryTag
import io.waylay.kairosdb.driver.models.TimeSpan.RelativeStartTime
import io.waylay.kairosdb.driver.models._
import play.api.libs.ws.ahc.StandaloneAhcWSClient
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success, Try}
object Example extends App {
implicit val actorSystem = ActorSystem()
implicit val actorMaterializer = ActorMaterializer()
val wsClient = StandaloneAhcWSClient()
val kairosDB = new KairosDB(wsClient, KairosDBConfig(), global)
val res = for {
version <- kairosDB.version
names <- kairosDB.listMetricNames
_ <- kairosDB.addDataPoint(DataPoint("kairosdbscala.test", 9001, tags = Tag("awesome", "yes")))
// same as above, but without implicit conversions
_ <- kairosDB.addDataPoint(DataPoint(MetricName("kairosdbscala.test"), KNumber(9001), tags = Seq(Tag("awesome", "yes"))))
qr <- kairosDB.queryMetrics(
QueryMetrics(
Query("kairosscala.test", tags = QueryTag("awesome" -> "yes")), 5.minutes.ago.startTime
)
)
// same as above, but without implicits
_ <- kairosDB.queryMetrics(
QueryMetrics(Seq(
Query(MetricName("kairosscala.test"), tags = Seq(QueryTag("awesome", Seq("yes", "true"))))
), TimeSpan(RelativeStartTime(5.minutes)))
)
} yield {
println(s"The KairosDB version is $version.")
println(s"""Some of the metrics are ${names take 3 map (_.name) mkString ", "}.""")
println(s"The result of querying was ${qr.queries.head.results.head}.")
}
res.onComplete { _ =>
Try(wsClient.close())
Try(actorMaterializer.shutdown())
Try(actorSystem.terminate())
}
res.onComplete{
case Success(_) => println("done")
case Failure(e) => e.printStackTrace()
}
}
开发者ID:waylayio,项目名称:kairosdb-scala,代码行数:60,代码来源:Example.scala
示例6: FilesController
//设置package包名称以及导入依赖的类
package controllers.files
import java.text.SimpleDateFormat
import akka.stream.scaladsl.Source
import domain.storage.FileMeta
import play.api.libs.iteratee.Enumerator
import play.api.libs.json.Json
import play.api.libs.streams.Streams
import play.api.mvc._
import services.storage.{FileServices, FileTypeService}
import scala.concurrent.Future
class FilesController extends Controller {
// def upload = Action(parse.temporaryFile) { request =>
// request.body.moveTo(new File("/tmp/picture/uploaded"))
// Ok("File uploaded")
// }
//curl -v -X POST http://localhost:9000/api/upload -F "[email protected]/home/hashcode/0imagescript/images/image.jpg"
def upload = Action.async(parse.multipartFormData) { request =>
import scala.concurrent.ExecutionContext.Implicits.global
request.body.file("upload") match {
case Some(file) => {
val data = file.ref.file
val meta = FileMeta(file.filename, FileTypeService.detectFile(data))
val results = FileServices.processFile(data, meta)
results map (result => {
Ok(Json.toJson(result))
})
}
case None => {
Future {
BadRequest
}
}
}
}
def getFile(id: String, filename: String) = Action {
import scala.concurrent.ExecutionContext.Implicits.global
FileServices.getFile(id) match {
case Some(file) => {
val dataContent: Enumerator[Array[Byte]] = Enumerator.fromStream(file.inputStream)
val source = Source.fromPublisher(Streams.enumeratorToPublisher(dataContent))
Ok.chunked(source).as(file.contentType.getOrElse(BINARY))
}
case None => NotFound
}
}
}
开发者ID:Thulebona,项目名称:hashpvtapi,代码行数:56,代码来源:FilesController.scala
示例7: ProviderActor
//设置package包名称以及导入依赖的类
package uk.mm.mpp.actors
import akka.actor.{Actor, Props}
import akka.pattern.pipe
import org.apache.commons.lang3.StringUtils._
import org.json4s._
import org.json4s.native.JsonMethods._
import play.api.Logger
import play.api.Play.current
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import uk.mm.mpp.actors.ProviderActor.{ProductRequest, ProductResponse}
import uk.mm.mpp.globals._
import scala.concurrent.ExecutionContext.Implicits.global
object ProviderActor {
def props(uid: String, port: Int) = Props(classOf[ProviderActor], uid, port)
case class ProductRequest()
case class ProductResponse(products: JArray)
}
class ProviderActor(uid: String, port: Int) extends Actor {
private lazy val request: WSRequest = WS.client.url(providerUrl)
.withFollowRedirects(false)
.withRequestTimeout(15000)
val logger = Logger(MPP_WORKER_PREFIX + getClass.getSimpleName + "_" + uid + "_" + port)
val providerUrl: String = "http://localhost:" + port + "/3rd/products"
def receive = {
case ProductRequest =>
request.get()
.map(productUpdateFrom)
.recover(withEmptyJsonArray)
.pipeTo(sender)
}
val withEmptyJsonArray: PartialFunction[Throwable, ProductResponse] = {
case _ => ProductResponse(JArray(List()))
}
def productUpdateFrom(response: WSResponse): ProductResponse = if (response.status == 200) {
logger.debug(s"from: [$providerUrl]: [${piedPiper(response)}]")
ProductResponse(parseJsonFrom(response))
} else {
logger.warn(s"from: [$providerUrl]: [${response.body}]")
ProductResponse(JArray(List()))
}
def piedPiper(response: WSResponse) = {
abbreviate(replacePattern(response.body, """\s{2,}""", " "), 30)
}
def parseJsonFrom(response: WSResponse) = parse(response.body).asInstanceOf[JArray]
}
开发者ID:mikemey,项目名称:mpp,代码行数:60,代码来源:ProviderActor.scala
示例8: AkkaSimpleSettings
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import scala.concurrent.ExecutionContext
package object shared {
trait AkkaSettings {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
implicit val executionContext: ExecutionContext
}
object AkkaSimpleSettings extends AkkaSettings {
lazy val config = ConfigFactory.load()
implicit lazy val system = ActorSystem("my-system", config)
implicit lazy val materializer = ActorMaterializer()
implicit lazy val executionContext = system.dispatcher
}
object AkkaShardedSettings extends AkkaSettings {
lazy val config = ConfigFactory.load("sharded")
implicit lazy val system = ActorSystem("my-system", config)
implicit lazy val materializer = ActorMaterializer()
implicit lazy val executionContext = system.dispatcher
}
object DefaultThreadPool {
import scala.concurrent.ExecutionContext.Implicits.global
implicit lazy val executionContext = global
}
}
开发者ID:kkrzys,项目名称:eShop,代码行数:34,代码来源:package.scala
示例9: ListTagValuesSpec
//设置package包名称以及导入依赖的类
package unit
import io.waylay.kairosdb.driver.KairosDB
import io.waylay.kairosdb.driver.models._
import mockws.MockWS
import org.specs2.mutable.Specification
import play.api.libs.json.Json
import play.api.mvc.Action
import play.api.mvc.Results._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.{FutureMatchers, ResultMatchers}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class ListTagValuesSpec extends Specification with FutureMatchers with ResultMatchers {
"KairosDB#listTagValues" should {
"return the correct tag values" in { implicit ee: ExecutionEnv =>
val expected = Seq("mytag", "foo", "bar1")
val mockWs = MockWS {
case ("GET", "http://localhost:8080/api/v1/tagvalues") => Action {
Ok(Json.obj("results" -> expected))
}
}
val kairosDb = new KairosDB(StandaloneMockWs(mockWs), KairosDBConfig(), global)
val r = kairosDb.listTagValues must be_==(expected).await(1, 3.seconds)
mockWs.close()
r
}
}
}
开发者ID:waylayio,项目名称:kairosdb-scala,代码行数:35,代码来源:ListTagValuesSpec.scala
示例10: ListMetricNamesSpec
//设置package包名称以及导入依赖的类
package unit
import io.waylay.kairosdb.driver.KairosDB
import io.waylay.kairosdb.driver.models._
import mockws.MockWS
import org.specs2.mutable.Specification
import play.api.libs.json.Json
import play.api.mvc.Action
import play.api.mvc.Results._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.{FutureMatchers, ResultMatchers}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class ListMetricNamesSpec extends Specification with FutureMatchers with ResultMatchers {
"KairosDB#listMetricNames" should {
"return the correct metric names" in { implicit ee: ExecutionEnv =>
val expected = Seq("mymetric", "archive_file_search", "bar1")
val mockWs = MockWS {
case ("GET", "http://localhost:8080/api/v1/metricnames") => Action {
Ok(Json.obj("results" -> expected))
}
}
val kairosDb = new KairosDB(StandaloneMockWs(mockWs), KairosDBConfig(), global)
val r = kairosDb.listMetricNames must be_==(expected.map(MetricName)).await(1, 3.seconds)
mockWs.close()
r
}
}
}
开发者ID:waylayio,项目名称:kairosdb-scala,代码行数:35,代码来源:ListMetricNamesSpec.scala
示例11: VersionSpec
//设置package包名称以及导入依赖的类
package unit
import io.waylay.kairosdb.driver.KairosDB
import io.waylay.kairosdb.driver.models._
import mockws.MockWS
import org.specs2.mutable.Specification
import play.api.libs.json.Json
import play.api.mvc.Action
import play.api.mvc.Results._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.{FutureMatchers, ResultMatchers}
import play.api.libs.ws.{StandaloneWSClient, StandaloneWSRequest}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class VersionSpec extends Specification with FutureMatchers with ResultMatchers {
"KairosDB#version" should {
"return the correct version number" in { implicit ee: ExecutionEnv =>
val mockWs = MockWS {
case ("GET", "http://localhost:8080/api/v1/version") => Action {
Ok(Json.obj("version" -> "KairosDB 0.9.4"))
}
}
val kairosDb = new KairosDB(StandaloneMockWs(mockWs), KairosDBConfig(), global)
val r = kairosDb.version must be_==("KairosDB 0.9.4").await(1, 3.seconds)
mockWs.close()
r
}
}
// remove once this is fixed: https://github.com/leanovate/play-mockws/issues/20
object StandaloneMockWs{
def apply(mockWs: MockWS) = new StandaloneMockWs(mockWs)
}
class StandaloneMockWs(mockWs: MockWS) extends StandaloneWSClient{
override def underlying[T]: T = mockWs.underlying[T]
override def url(url: String): StandaloneWSRequest = mockWs.url(url)
override def close(): Unit = mockWs.close()
}
}
开发者ID:waylayio,项目名称:kairosdb-scala,代码行数:47,代码来源:VersionSpec.scala
示例12: ListTagNamesSpec
//设置package包名称以及导入依赖的类
package unit
import io.waylay.kairosdb.driver.KairosDB
import io.waylay.kairosdb.driver.models._
import mockws.MockWS
import org.specs2.mutable.Specification
import play.api.libs.json.Json
import play.api.mvc.Action
import play.api.mvc.Results._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.{FutureMatchers, ResultMatchers}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class ListTagNamesSpec extends Specification with FutureMatchers with ResultMatchers {
"KairosDB#listTagNames" should {
"return the correct tag names" in { implicit ee: ExecutionEnv =>
val expected = Seq("mytag", "foo", "bar1")
val mockWs = MockWS {
case ("GET", "http://localhost:8080/api/v1/tagnames") => Action {
Ok(Json.obj("results" -> expected))
}
}
val kairosDb = new KairosDB(StandaloneMockWs(mockWs), KairosDBConfig(), global)
val r = kairosDb.listTagNames must be_==(expected).await(1, 3.seconds)
mockWs.close()
r
}
}
}
开发者ID:waylayio,项目名称:kairosdb-scala,代码行数:35,代码来源:ListTagNamesSpec.scala
示例13: DeleteMetricSpec
//设置package包名称以及导入依赖的类
package unit
import io.waylay.kairosdb.driver.KairosDB
import io.waylay.kairosdb.driver.models._
import mockws.MockWS
import org.specs2.mutable.Specification
import play.api.mvc.Action
import play.api.mvc.Results._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.{FutureMatchers, ResultMatchers}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class DeleteMetricSpec extends Specification with FutureMatchers with ResultMatchers {
"KairosDB#deleteMetric" should {
"delete metric" in { implicit ee: ExecutionEnv =>
val mockWs = MockWS {
case ("DELETE", "http://localhost:8080/api/v1/metric/my.metric.123") => Action {
NoContent
}
}
val kairosDb = new KairosDB(StandaloneMockWs(mockWs), KairosDBConfig(), global)
try {
kairosDb.deleteMetric(MetricName("my.metric.123")) must beEqualTo(()).await(1, 3.seconds)
}finally {
mockWs.close()
}
}
}
}
开发者ID:waylayio,项目名称:kairosdb-scala,代码行数:34,代码来源:DeleteMetricSpec.scala
示例14: Application
//设置package包名称以及导入依赖的类
package controllers
import play.api.mvc._
import services.{SunService, WeatherService}
// you need to import this or you will get a compile error stating "Cannot find an
// implicit ExecutionContext. You might pass or import
// scala.concurrent.ExecutionContext.Implicits.global"
// That's actually a really helpful error message
import scala.concurrent.ExecutionContext.Implicits.global
class Application(sunService: SunService,
weatherService: WeatherService) extends Controller {
def index = Action.async {
val lat = -33.8830
val lon = 151.2167
val sunInfoF = sunService.getSunInfo(lat, lon)
val temperatureF = weatherService.getTemperature(lat, lon)
for {
sunInfo <- sunInfoF
temperature <- temperatureF
} yield {
Ok(views.html.index(sunInfo, temperature))
}
}
}
开发者ID:Ryan-Thomas,项目名称:WebDevScala,代码行数:28,代码来源:Application.scala
示例15: MongoCountAction
//设置package包名称以及导入依赖的类
package com.ringcentral.gatling.mongo.action
import com.ringcentral.gatling.mongo.command.MongoCountCommand
import com.ringcentral.gatling.mongo.response.MongoCountResponse
import io.gatling.commons.stats.KO
import io.gatling.commons.util.TimeHelper.nowMillis
import io.gatling.commons.validation._
import io.gatling.core.action.Action
import io.gatling.core.config.GatlingConfiguration
import io.gatling.core.session.{Expression, Session, _}
import io.gatling.core.stats.StatsEngine
import reactivemongo.api.DefaultDB
import reactivemongo.play.json.collection.JSONCollection
//TODO remove global context everywhere
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
class MongoCountAction(command: MongoCountCommand, database: DefaultDB, val statsEngine: StatsEngine, configuration: GatlingConfiguration, val next: Action) extends MongoAction(database) {
override def name: String = genName("Mongo count command")
override def commandName: Expression[String] = command.commandName
override def executeCommand(commandName: String, session: Session): Validation[Unit] =
for {
collectionName <- command.collection(session)
selectorDocument <- resolveOptionalExpression(command.selector, session)
hint <- resolveOptionalExpression(command.hint, session)
selector <- selectorDocument match {
case Some(d) => string2JsObject(d).map(Some.apply)
case None => NoneSuccess
}
} yield {
val sent = nowMillis
val collection: JSONCollection = database.collection[JSONCollection](collectionName)
collection.count(selector, command.limit, command.skip, hint).onComplete {
case Success(result) => processResult(session, sent, nowMillis, command.checks, MongoCountResponse(result), next, commandName)
case Failure(err) => executeNext(session, sent, nowMillis, KO, next, commandName, Some(err.getMessage))
}
}
}
开发者ID:RC-Platform-Disco-Team,项目名称:gatling-mongodb-protocol,代码行数:44,代码来源:MongoCountAction.scala
示例16: MongoUtils
//设置package包名称以及导入依赖的类
package com.ringcentral.gatling.mongo
import reactivemongo.api.MongoConnection.{ParsedURI, URIParsingException}
import reactivemongo.api.{DefaultDB, MongoConnection, MongoDriver}
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}
// fixme remove global context
import scala.concurrent.ExecutionContext.Implicits.global
object MongoUtils {
private val defaultPort: Int = 27017
private lazy val mongoDriver = new MongoDriver()
private def establishConnection(uri: ParsedURI, dbName: String, connectionTimeout: FiniteDuration): DefaultDB = {
Await.result(establishConnection(uri, dbName), connectionTimeout)
}
private def establishConnection(uri: ParsedURI, dbName: String): Future[DefaultDB] =
Try(mongoDriver.connection(uri).database(dbName))
match {
case Success(db) => db
case Failure(err) =>
throw new IllegalStateException(s"Can't connect to database ${printHosts(uri.hosts)}: ${err.getMessage}", err)
}
private def printHosts(hosts: List[(String, Int)]): String = hosts.map { case (host, port) => s"$host:$port" }.mkString(", ")
def connectToDB(uri: ParsedURI, connectionTimeout: FiniteDuration): DefaultDB =
uri.db match {
case Some(dbName) => establishConnection(uri, dbName, connectionTimeout)
case None => throw new IllegalStateException(s"Can't connect to database $uri.")
}
def connectToDB(uri: String, connectionTimeout: FiniteDuration): DefaultDB = connectToDB(parseUri(uri), connectionTimeout)
def parseHosts(hosts: Seq[String]): Seq[(String, Int)] = hosts.map { hostAndPort =>
hostAndPort.split(':').toList match {
case host :: port :: Nil =>
host -> Try(port.toInt).filter(p => p > 0 && p < 65536)
.getOrElse(throw new URIParsingException(s"Could not parse hosts '$hosts' from URI: invalid port '$port'"))
case host :: Nil =>
host -> defaultPort
case _ => throw new URIParsingException(s"Could not parse hosts from URI: invalid definition '$hosts'")
}
}
def parseUri(uri: String): ParsedURI = {
MongoConnection.parseURI(uri) match {
case Success(parsedUri) => parsedUri
case Failure(err) => throw new IllegalStateException(s"Can't parse database uri. $err")
}
}
}
开发者ID:RC-Platform-Disco-Team,项目名称:gatling-mongodb-protocol,代码行数:58,代码来源:MongoUtils.scala
示例17: Upload
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import actors.PigExecutorHandling
import com.google.inject.Inject
import models.{DatabaseAccess, LoginAccess, MetaDataAccess}
import play.api.Logger
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._
import util.HDFS
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.control.NonFatal
import scala.util.{Failure, Success}
@Singleton
class Upload @Inject()(implicit val app: play.api.Application, val messagesApi: MessagesApi) extends Controller with DatabaseAccess with LoginAccess with I18nSupport with PigExecutorHandling with MetaDataAccess {
def uploadGET = Action { request =>
Ok(views.html.upload())
}
def uploadPOST = Action(parse.multipartFormData) { implicit request =>
import util.FutureEnhancements._
import scala.concurrent.ExecutionContext.Implicits.global
Await.result(request.cookies.get("qgtoken").map(_.value) match {
case Some(token) => checkToken(token).mapAll {
case Failure(e) =>
Logger.error("Failed checking user with database: " + e.getMessage)
Unauthorized("not authed")
case Success(None) =>
Logger.info("Invalide token used")
Unauthorized("not authed")
case Success(Some(x)) =>
request.body.file("file").map { f =>
val filename = f.filename
val contentType = f.contentType
try {
HDFS.writeFile(globalSetting, filename, f.ref.file.getAbsoluteFile)
Ok("File uploaded to: " + globalSetting.qrygraphFolder + "/" + filename)
} catch {
case NonFatal(e) =>
Logger.error("Error uploading file to hdfs", e)
BadRequest("Upload failed - check your connection")
}
}.getOrElse {
Redirect(routes.Upload.uploadGET()).flashing("error" -> "Missing file")
}
}
case None => Future(Unauthorized("not authed"))
},100.seconds)
}
}
开发者ID:Starofall,项目名称:QryGraph,代码行数:62,代码来源:Upload.scala
示例18: Route
//设置package包名称以及导入依赖的类
package com.example
import akka.http.scaladsl.model.{StatusCodes, HttpEntity, ContentTypes}
import akka.http.scaladsl.server.{Directive1, Directives}
import com.example.model.Post
import com.example.service.{Health, HealthCheckService, PostService}
import scala.concurrent.Future
class Route(postService: PostService, healthCheckService: HealthCheckService) extends Directives {
private[this] def fetchPosts: Directive1[Seq[Post]] = {
import scala.concurrent.ExecutionContext.Implicits.global
onSuccess(Future(postService.all()))
}
private[this] def createPost(title: String, content: String): Directive1[Seq[Post]] = {
import scala.concurrent.ExecutionContext.Implicits.global
onSuccess {
Future(postService.create(title, content)).map(_ => postService.all())
}
}
private[this] def index(posts: Seq[Post]) = {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, html.index.render(posts).body))
}
val route = pathSingleSlash {
fetchPosts(index)
} ~ path("post") {
post {
formFields('title, 'content) { (title, content) =>
createPost(title, content)(index)
}
} ~ get {
fetchPosts(index)
}
} ~ path("health") {
healthCheckService.health() match {
case Health.Healthy => complete("ok")
case Health.Unhealthy => complete(StatusCodes.ServiceUnavailable)
}
}
}
开发者ID:ocadaruma,项目名称:introduction-to-kubernetes,代码行数:47,代码来源:Route.scala
示例19: BackoffTest
//设置package包名称以及导入依赖的类
package caustic.runtime
import Backoff._
import org.junit.runner.RunWith
import org.mockito.Mockito._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.JUnitRunner
import org.scalatest.{FunSuite, Matchers}
import org.scalatest.mockito.MockitoSugar
import scala.concurrent.{Await, Future, TimeoutException}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.language.postfixOps
@RunWith(classOf[JUnitRunner])
class BackoffTest extends FunSuite
with ScalaFutures
with Matchers
with MockitoSugar {
test("Backoff properly retries failures.") {
val fake = mock[Database]
when(fake.execute(literal(""))(global))
.thenReturn(Future.failed(new Exception("Retryable.")))
.thenReturn(Future("Success"))
.thenReturn(Future.failed(FatalException("Non-Retryable")))
.thenReturn(Future.failed(new Exception("Retryable")))
.thenReturn(Future("Success"))
// Verify that retries succeed on retryable failures.
whenReady(retry(Seq(100 millis))(fake.execute(literal(""))))(_ shouldEqual "Success")
// Verify that retries fail on fatal errors.
whenReady(retry(Seq(100 millis))(fake.execute(literal(""))).failed)(_ shouldBe an [FatalException])
// Verify that retry respects backoff durations.
assertThrows[TimeoutException] {
Await.result(retry(Seq(1 second))(fake.execute(literal(""))).failed, 500 millis)
}
verify(fake, times(4)).execute(literal(""))(global)
}
}
开发者ID:ashwin153,项目名称:caustic,代码行数:45,代码来源:BackoffTest.scala
示例20: CanvasSubscriber
//设置package包名称以及导入依赖的类
package eu.devtty.mboard.canvas
import eu.devtty.ipfs.IpfsNode
import eu.devtty.mboard.PubsubEvents
import eu.devtty.mboard.util.Buffer
import eu.devtty.multihash.MultiHash
import scala.util.Success
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
class CanvasSubscriber(ipfs: IpfsNode, chain: Chain, room: String, canvas: Canvas) {
private val _id = ipfs.id()
lazy val id = _id.value.get.get.id //TODO: That's baaaaaad
val initializer = new ChainInitializer(ipfs, room, canvas)
ipfs.pubsub.subscribe(room, { msg =>
if(msg.from != id) {
msg.data.readInt8(0) match {
case PubsubEvents.DRAW_CHUNK =>
ipfs.block.get(msg.data.slice(1)) andThen {
case Success(block) =>
canvas.drawImage(block.data.toString(), msg.from)
chain.put(MultiHash.toB58String(msg.data.slice(1)))
}
case PubsubEvents.LIVE_PART =>
val sx = msg.data.readDoubleLE(1)
val sy = msg.data.readDoubleLE(9)
val ex = msg.data.readDoubleLE(17)
val ey = msg.data.readDoubleLE(25)
canvas.drawPart(sx, sy, ex, ey, msg.from)
case PubsubEvents.REQUEST_CHAIN =>
if(chain.top != null) {
println("Answer chain request")
val msg = Buffer.alloc(chain.top.length + 1)
msg.writeInt8(PubsubEvents.CHAIN, 0)
msg.write(chain.top, 1)
ipfs.pubsub.publish(room, msg)
}
case PubsubEvents.CHAIN =>
initializer.registerBootCandidate(msg.data.slice(1).toString())
}
}
}).andThen {
case Success(_) => println(s"Subscribed to room $room")
}
js.Dynamic.global.peers = { () =>
ipfs.pubsub.peers(room).andThen {
case Success(list) => println("Peers:"); list.foreach(println)
}
}
js.Dynamic.global.speers = { () =>
ipfs.swarm.peers().andThen {
case Success(list) => println("Peers:"); list.map(_.addr.toString()).foreach(println)
}
}
}
开发者ID:magik6k,项目名称:milky-whiteboard,代码行数:61,代码来源:CanvasSubscriber.scala
注:本文中的scala.concurrent.ExecutionContext.Implicits.global类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论