本文整理汇总了Scala中scalaz.concurrent.Task类的典型用法代码示例。如果您正苦于以下问题:Scala Task类的具体用法?Scala Task怎么用?Scala Task使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Task类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Server
//设置package包名称以及导入依赖的类
package foobar
import foobar.page.{Contact, Index}
import org.http4s.MediaType.`text/html`
import org.http4s.dsl._
import org.http4s.headers.`Content-Type`
import org.http4s.server.ServerApp
import org.http4s.server.blaze._
import org.http4s.{HttpService, Response, StaticFile}
import scala.io.Source
import scala.util.Try
import scalatags.Text.TypedTag
import scalaz.concurrent.Task
object Server extends ServerApp {
def page(p: TypedTag[String]): Task[Response] =
Ok(p.render).withContentType(Some(`Content-Type`(`text/html`)))
val service = HttpService {
case GET -> Root => page(Index.page)
case GET -> Root / "contact" => page(Contact.page)
case req @ GET -> Root / path =>
println("file: " + Try(Source.fromFile(path).getLines().mkString))
StaticFile.fromResource(path.toString, Some(req)).fold(NotFound())(Task.now)
}
def server(args: List[String]) =
BlazeBuilder.bindHttp(8080)
.mountService(service, "/")
.start
}
示例2: b64T
//设置package包名称以及导入依赖的类
package codes.mark.geilematte
import org.http4s._
import org.http4s.headers.{Accept, `Content-Type`}
import scodec.{Codec, DecodeResult}
import scodec.bits.{BitVector, ByteVector}
import scodec.codecs.implicits._
import org.http4s.{DecodeResult => DecRes}
import scalaz.concurrent.Task
trait EntityEncoders {
def b64T[A:Codec]:EntityEncoder[Task[A]] =
EntityEncoder.simple(`Content-Type`(MediaType.`application/base64`))(
(a:Task[A]) => ByteVector(Codec.encode(a.unsafePerformSync).require.toBase64.getBytes)
)
def b64[A:Codec]:EntityEncoder[A] =
EntityEncoder.simple(`Content-Type`(MediaType.`application/base64`))(
(a:A) => ByteVector(Codec.encode(a).require.toBase64.getBytes)
)
}
trait EntityDecoders {
def fromB64[A:Codec]:EntityDecoder[A] =
new EntityDecoder[A] {
override def consumes = Set(MediaType.`application/base64`)
override def decode(msg: Message, strict: Boolean) =
DecRes.success(
msg.as[String]
.map(s => Codec.decode[A](BitVector.fromBase64(s).get).require)
.unsafePerformSync.value
)
}
}
示例3: Blaze
//设置package包名称以及导入依赖的类
package org.mdoc.rendering.service
import eu.timepit.properly.Property
import eu.timepit.properly.Property.PropertySyntax
import org.http4s.server.Server
import org.http4s.server.blaze.BlazeBuilder
import scalaz.concurrent.Task
object Blaze {
val httpHost: Property[String] = {
val defaultHost = "::"
Property.getOrElse("HTTP_HOST", defaultHost)
}
val httpPort: Property[Int] = {
val defaultPort = 8081
Property.getAsIntOrElse("HTTP_PORT", defaultPort)
}
val serverBuilder: Property[BlazeBuilder] =
for {
host <- httpHost
port <- httpPort
} yield {
BlazeBuilder
.bindHttp(port, host)
.mountService(Service.route)
}
val server: Task[Server] =
serverBuilder.runTask.flatMap(_.start)
}
示例4: Card
//设置package包名称以及导入依赖的类
package org.emv
import javax.smartcardio.{CardException, CardTerminal, CommandAPDU, ResponseAPDU, _}
import scala.collection.JavaConversions._
import collection.JavaConverters._
import scalaz.concurrent.Task
object Card {
val defaultProtocol: String = "*"
def getReaders: Task[Seq[CardTerminal]] = Task {
TerminalFactory.getDefault.terminals.list.asScala
}
def selectReader(preferedReader: Option[String]): Task[Option[CardTerminal]] =
getReaders.map(readers => {
val selectedPreferedReader: Option[CardTerminal] = preferedReader.flatMap(x => readers.find(y => y.getName == x))
val selectedReader = selectedPreferedReader match {
case Some(x) => Some(x)
case None => readers.find(y => y.isCardPresent)
}
selectedReader match {
case Some(x) => Some(x)
case None if (readers.size > 0) => Some(readers(0))
case None => None
}
})
def waitForCardOnTerminal(terminal: CardTerminal, timeout: Long): Task[Unit] = Task {
terminal.waitForCardPresent(timeout)
}
def connectToCard(terminal: CardTerminal, protocol: String = defaultProtocol): Task[javax.smartcardio.Card] = Task {
terminal.connect(protocol)
}
def waitAndConnect(terminal: CardTerminal, timeout: Long,
protocol: String = defaultProtocol): Task[javax.smartcardio.Card] = for {
_ <- waitForCardOnTerminal(terminal, timeout)
card <- connectToCard(terminal, protocol)
} yield (card)
def transmit(card: javax.smartcardio.Card, commandBytes: Seq[Byte]): Task[Seq[Byte]] = Task {
val channel: CardChannel = card.getBasicChannel
val responseCommand = channel.transmit(new CommandAPDU(commandBytes.toArray))
responseCommand.getBytes.toList
}
}
示例5: ImageHttpService
//设置package包名称以及导入依赖的类
package com.imageintelligence.pix.api.http.services
import scalaz._
import org.http4s._
import org.http4s.dsl._
import org.http4s.headers.{`Cache-Control`, `Content-Type`}
import org.log4s.Logger
import scalaz.concurrent.Task
import com.imageintelligence.http4c.ArgonautInstances._
import com.imageintelligence.http4c.ApiResponse
import com.imageintelligence.http4c.headers.`X-Proxy-Cache`
import com.imageintelligence.pix.api.http.domain.ImageUploadRequestDto
import com.imageintelligence.pix.core._
import com.imageintelligence.pix.services.ImageService
import com.imageintelligence.pix.api.http.HttpMatchers.{createImageRetrieveQueryRequestDto, ImageIdMatcher}
import org.http4s.CacheDirective
case class ImageHttpService(imageService: ImageService, logger: Logger) {
val service = HttpService {
case req @ POST -> Root / "images" / "upload" => req.decode[ImageUploadRequestDto] { request =>
imageService.uploadImages(request.images).flatMap { response =>
Ok(ApiResponse.success(response))
}
}
case req @ GET -> Root / "images" / ImageIdMatcher(id) => {
createImageRetrieveQueryRequestDto(req.params) match {
case \/-(query) => imageService.getImageBytes(id, query).run.flatMap {
case -\/(error) => handleServiceError(error)
case \/-(None) => NotFound()
case \/-(Some((image, s))) => Ok(image)
.putHeaders(`Content-Type`(MediaType.`image/jpeg`))
.putHeaders(`Cache-Control`(CacheDirective.public))
.putHeaders(`X-Proxy-Cache`(ServedFrom.wasCacheHit(s)))
}
case -\/(err) => BadRequest(ApiResponse.failure(err))
}
}
}
def handleServiceError(error: ImageServiceError): Task[Response] = error match {
case e =>
logger.error(e.toString)
InternalServerError(ApiResponse.failure(e.toString))
}
}
示例6: ImageCacheService
//设置package包名称以及导入依赖的类
package com.imageintelligence.pix.services
import java.util.UUID
import com.redis.serialization.Parse.Implicits._
import com.redis.{RedisClientPool, Seconds}
import scalaz._
import Scalaz._
import com.imageintelligence.metrics.DogStatsDMetrics
import com.imageintelligence.pix.Metric
import com.imageintelligence.pix.Metrics
import com.imageintelligence.pix.config.RedisConfig
import com.imageintelligence.pix.core.ProcessedImage
import com.redis.RedisClient
import scalaz.concurrent.Task
case class ImageCacheService(config: RedisConfig, metrics: DogStatsDMetrics) {
type Result[A] = EitherT[Task, Throwable, A]
val redisClientPool = new RedisClientPool(config.host, config.port)
def set(image: ProcessedImage): Result[Unit] = {
runRedisOp(Metrics.Cache.setImageToCache) { client =>
client.set(image.id, image.blob, onlyIfExists = false, Seconds(config.ttl))
}
}
def get(imageId: UUID): Result[Option[Array[Byte]]] = {
val bytes = runRedisOp(Metrics.Cache.getImageFromCache) { client =>
client.get[Array[Byte]](imageId)
}
bytes.map {
case None =>
metrics.increment(Metrics.Cache.getImageCacheMiss.name)
None
case Some(image) =>
metrics.increment(Metrics.Cache.getImageCacheHit.name)
Some(image)
}
}
def runRedisOp[A](metric: Metric)(f: RedisClient => A): Result[A] = {
val op: Result[A] = EitherT {
Task {
redisClientPool.withClient(f)
}.attempt
}
Metrics.timeOp(op, metrics, metric)
}
}
示例7: Person
//设置package包名称以及导入依赖的类
package com.xebia.doobie.update
import doobie.imports._
import doobie.util.transactor
import scalaz.concurrent.Task
case class Person(id: String, name: String, age: Option[Int])
object InsertDataExample extends PersonRepository {
def persistThreeRecords(implicit xa: transactor.Transactor[Task]): Int = {
val rows = for {
row1 <- persist("Alice", Option(12)).run
row2 <- persist("Bob", None).run
row3 <- persist("John", Option(17)).run
} yield row1 + row2 + row3
val insertedRows = rows.transact(xa).unsafePerformSync
insertedRows
}
def findAllPerson(implicit xa: transactor.Transactor[Task]): List[Person] =
findAll().transact(xa).unsafePerformSync
def countAll(implicit xa: transactor.Transactor[Task]): Int =
count().transact(xa).unsafePerformSync
def deleteAll(implicit xa: transactor.Transactor[Task]): Int =
delete().run.transact(xa).unsafePerformSync
}
trait PersonRepository {
def findAll(): ConnectionIO[List[Person]] = {
sql"select id, name, age from person"
.query[Person]
.list
}
def count(): ConnectionIO[Int] = {
sql"select count(name) from person"
.query[Int]
.unique
}
def delete(): Update0 = {
sql"delete from person".update
}
def persist(name: String, age: Option[Short]): Update0 =
sql"insert into person (name, age) values ($name, $age)".update
}
示例8: Main
//设置package包名称以及导入依赖的类
package io.grhodes.mcm.server
import java.nio.file.Paths
import com.typesafe.config.ConfigFactory
import io.grhodes.mcm.server.apn.ApnService
import io.grhodes.mcm.server.gcm.XmppBuilder
import org.http4s.server.SSLSupport.StoreInfo
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.{Server, ServerApp}
import scalaz.concurrent.Task
object Main extends ServerApp {
//System.setProperty("javax.net.debug", "all")
System.setProperty("file.encoding", "UTF8")
val ServerConfig = ConfigFactory.load().getConfig("io.grhodes.mcm-server")
val KeyStoreConfig = ServerConfig.getConfig("apn.keystore")
val KeyPath = Paths.get(KeyStoreConfig.getString("path")).toAbsolutePath.toString
val ApnServer = BlazeBuilder.enableHttp2(true).withSSL(
StoreInfo(KeyPath, KeyStoreConfig.getString("password")),
keyManagerPassword = KeyStoreConfig.getString("manager-password"),
trustStore = Some(StoreInfo(KeyPath, KeyStoreConfig.getString("password")))
).mountService(McmService.service, "/").bindHttp(ServerConfig.getInt("apn.port"))
override def server(args: List[String]): Task[Server] = {
XmppBuilder.start()
ApnServer.start
}
override def shutdown(server: Server) = {
XmppBuilder.shutdown()
server.shutdown
}
}
示例9: ProfileEndpoint
//设置package包名称以及导入依赖的类
package pl.immutables.monads.endpoints
import io.circe.syntax._
import io.circe.generic.auto._
import org.http4s._
import org.http4s.circe._
import org.http4s.dsl._
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.util.CaseInsensitiveString
import scalaz._
import scalaz.Scalaz._
import pl.immutables.monads.models._
import pl.immutables.monads.services._
import scalaz.concurrent.Task
object ProfileEndpoint extends App {
lazy val tokenHeader = CaseInsensitiveString("token")
lazy val service = HttpService {
case req @ GET -> Root / "profile" => for {
token <- req.headers.get(tokenHeader) |>
Result.ofOption(BadRequest("missing token"))
user <- UserService.authenticate(token.value) |>
Result.ofTEither(e => Forbidden("invalid token"))
devices <- Task.gatherUnordered(
user.devices.map(id => DeviceService.getById(id))
) |> Result.ofTask
} yield Ok(UserWithDevices(user, devices.flatten).asJson)
}
BlazeBuilder
.mountService(service)
.run.awaitShutdown()
}
示例10: Main
//设置package包名称以及导入依赖的类
package demo
import doobie.imports._
import org.http4s.server.blaze._
import scalaz.concurrent.Task
object Main extends App {
val xa = DriverManagerTransactor[Task](
"org.postgresql.Driver", "jdbc:postgresql:demo", "postgres", "db#2700"
)
val server =
BlazeBuilder
.bindHttp(8080)
.mountService(DemoService.service(xa))
.run
server.awaitShutdown()
}
示例11: circeJsonDecoder
//设置package包名称以及导入依赖的类
package api
import java.util.NoSuchElementException
import javax.security.sasl.AuthenticationException
import io.circe.{Decoder, Encoder}
import org.http4s._
import org.http4s.dsl._
import scalaz._
import scalaz.concurrent.Task
trait BaseApi {
implicit def circeJsonDecoder[A](implicit decoder: Decoder[A]) = org.http4s.circe.jsonOf[A]
implicit def circeJsonEncoder[A](implicit encoder: Encoder[A]) = org.http4s.circe.jsonEncoderOf[A]
implicit def eitherToResponse[A](e: Throwable \/ A)(implicit encoder: Encoder[A]): Task[Response] =
e.fold(l => InternalServerError(l.getMessage), r => Ok(r))
implicit def eitherTaskToResponse[A](e: Task[Throwable \/ A])(implicit encoder: Encoder[A]): Task[Response] =
for {
t <- e
x <- t.fold(l => throwbe2response(l), r => Ok(r))
} yield (x)
val throwbe2response: Throwable => Task[Response] = t => t match {
case e: AuthenticationException => Unauthorized(Challenge("", "", Map()))
case e: IllegalArgumentException => BadRequest (e.getMessage)
case e: NoSuchElementException => NotFound (e.getMessage)
case e: Throwable => InternalServerError(e.getMessage)
}
}
示例12: Bootstrap
//设置package包名称以及导入依赖的类
import api.StatusApi
import com.typesafe.scalalogging.LazyLogging
import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder
import utils._
import Global._
import repository.Ds._
import scalaz._, Scalaz._
import scalaz.concurrent.Task
object Bootstrap extends ServerApp with LazyLogging {
case class ProgramStatus(s: Server, u: Unit)
def server(args: List[String]): Task[Server] = {
import CustomExecutor._
import ApplicativeTask._
val serverTask = BlazeBuilder.bindHttp(
port = cfgVevo.getInt("http.port"),
host = "0.0.0.0")
.mountService(StatusApi.service, "/status").start
T.apply2(
Task.fork(serverTask)(ec),
Task.fork(Task.delay(println("hellow world from Applicatives!")))(customExecutor))(ProgramStatus(_, _)
) map (_.s)
}
}
示例13: Ds
//设置package包名称以及导入依赖的类
package repository
import doobie.imports._
import scalaz._
import Scalaz._
import scalaz.concurrent.Task
import utils.Global._
import doobie.hikari.hikaritransactor._
object Ds {
val jdbcUrl = cfgVevo.getString("db.jdbc.url")
val jdbcUser = cfgVevo.getString("db.jdbc.user")
val jdbcPass = cfgVevo.getString("db.jdbc.password")
val jdbcDriver = cfgVevo.getString("db.jdbc.driver")
val connectionPoolThreads = cfgVevo.getInt("db.connection.pool.threads")
implicit val hxa: HikariTransactor[Task] =
HikariTransactor[Task](
"org.postgresql.Driver",
jdbcUrl,
jdbcUser,
jdbcPass) unsafePerformSync
val _= (hxa.configure(hx =>{
hx.setAutoCommit(false)
hx.setPoolName("qos_service")
hx.setMaximumPoolSize(connectionPoolThreads)
Task.delay(hx)
})) unsafePerformSync
def connectionStatus: Boolean = {
val program3 = sql"select 42".query[Int].unique
(program3.transact(hxa).unsafePerformSync == 42 )
}
}
示例14: TaskExtensions
//设置package包名称以及导入依赖的类
package kafka.console
import java.io.Closeable
import javax.management.MBeanServerConnection
import javax.management.remote.{JMXConnectorFactory, JMXServiceURL}
import scalaz.{-\/, \/-}
import scalaz.concurrent.Task
package object extensions extends Conversions with MBeanServerConnectionExtensions {
implicit final class TaskExtensions(val self: Task.type) extends AnyVal {
def use[A,B](obj: => A)(close: A => Unit)(body: A => Task[B]) =
Task.delay(obj).flatMap { body }.attempt.flatMap {
case \/-(content) => close(obj); Task.now(content)
case -\/(failure) => close(obj); Task.fail(failure)
}
def bracket[A<:Closeable,B](obj: A)(body: A => Task[B]) =
Task.now(obj).flatMap{body}.attempt.flatMap{
case \/-(content) => obj.close(); Task.now(content)
case -\/(failure) => obj.close(); Task.fail(failure)
}
}
}
示例15: MBeanInfoProvider
//设置package包名称以及导入依赖的类
package kafka.console
package core.providers.monitoring
import javax.management.{ObjectInstance, ObjectName}
import extensions._
import model.monitoring.MBeanMetricInfo
import scalaz.concurrent.Task
import scalaz._, Scalaz._
object MBeanInfoProvider {
def getAggregates = {
doWithConnection { mbcs => Task.delay {
mbcs.queryMBeans(null, null).toArray()
.map(_.asInstanceOf[ObjectInstance])
.map(_.getObjectName())
.filter(_.getDomain.startsWith("kafka."))
.map(a => MBeanMetricInfo(a, a.getDomain, getMetricType(a), extractSortedCanonicalKeys(a), mbcs.getMBeanInfo(a)))
}
}
}
private def extractSortedCanonicalKeys(a: ObjectName) = {
canonicalNameKeyListToMap(a.getCanonicalKeyPropertyListString)
.map{case (k, v) => s"$k=$v"}.mkString(",")
}
private def getMetricType(a: ObjectName) = canonicalNameKeyListToMap(a.getCanonicalKeyPropertyListString)
.find{case (k, _) => k === "type"}
.map{case (_, v) => v}
.getOrElse("unknown")
private def canonicalNameKeyListToMap(canonicalName: String) = canonicalName.split(',').sorted.map { a =>
val Array(left, right) = a.split('=')
left -> right
}.toMap
}