本文整理汇总了Scala中scala.concurrent.ExecutionContext.Implicits.global类的典型用法代码示例。如果您正苦于以下问题:Scala global类的具体用法?Scala global怎么用?Scala global使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了global类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
}
示例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
}
}
}
示例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]]]
}
}
示例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)
}
}
示例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()
}
}
示例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
}
}
}
示例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]
}
示例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
}
}
示例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
}
}
}
示例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
}
}
}
示例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()
}
}
示例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
}
}
}
示例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()
}
}
}
}
示例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))
}
}
}
示例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))
}
}
}