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

Scala Process类代码示例

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

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



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

示例1: writeToString

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

import scalaz.Monoid
import scalaz.stream.Process
import scalaz.stream.text.utf8Decode
import scodec.bits.ByteVector

trait WriteToString {
  // In the real repo, this comes from Http4sSpec
  def writeToString[A](a: A)(implicit W: EntityEncoder[A]): String =
    Process.eval(W.toEntity(a))
      .collect { case EntityEncoder.Entity(body, _ ) => body }
      .flatMap(identity)
      .fold1Monoid
      .pipe(utf8Decode)
      .runLastOr("")
      .run

  implicit val byteVectorMonoidInstance: Monoid[ByteVector] = Monoid.instance(_ ++ _, ByteVector.empty)
} 
开发者ID:http4s,项目名称:http4s-argonaut61,代码行数:22,代码来源:WriteToString.scala


示例2: PersonDAO

//设置package包名称以及导入依赖的类
package demo

import java.time.Instant

import doobie.imports._

import scalaz.stream.Process

object PersonDAO {
  implicit val metaInstant =
    Meta[java.sql.Timestamp].nxmap(
      _.toInstant,
      (i: Instant) => new java.sql.Timestamp(i.toEpochMilli)
    )

  val streamPeople: Process[ConnectionIO, Person] =
    sql"select id, first_name, family_name, registered_at from people"
      .query[Person]
      .process

  val listPeople: ConnectionIO[List[Person]] =
    sql"select id, first_name, family_name, registered_at from people"
      .query[Person]
      .list

  def getPerson(id: Long): ConnectionIO[Option[Person]] =
    sql"select id, first_name, family_name, registered_at from people where id = $id"
      .query[Person]
      .option

  def updatePerson(id: Int, firstName: String, familyName: String): ConnectionIO[Person] =
    sql"update people set first_name=$firstName, family_name=$familyName where id=$id"
      .update
      .withUniqueGeneratedKeys("id", "first_name", "family_name", "registered_at")

  def insertPerson(firstName: String, familyName: String, registeredAt: Instant = Instant.now()): ConnectionIO[Person] =
    sql"insert into people (first_name, family_name, registered_at) values ($firstName, $familyName, $registeredAt)"
      .update
      .withUniqueGeneratedKeys("id", "first_name", "family_name", "registered_at")
} 
开发者ID:kbrumer,项目名称:http4s-talk,代码行数:41,代码来源:PersonDAO.scala


示例3: InMemoryJournal

//设置package包名称以及导入依赖的类
package fairshare.backend.eventsourcing.journals

import java.time.LocalDateTime

import fairshare.backend.eventsourcing._

import scala.collection.mutable
import scalaz.concurrent.Task
import scalaz.stream.Process
import scalaz.syntax.order._

class InMemoryJournal[E] extends Journal[E] {
  private var store = mutable.Buffer.empty[Fact[E]]
  private val lookup = mutable.Map[(Subject, Revision), Index]()
  private var entriesCount = 0

  def readAll(from: Index, to: Index): Process[Task, Fact[E]] =
    Process.emitAll(store.filter(e => e.index >= from && e.index <= to))

  def readSubject(key: Subject): Process[Task, Fact[E]] = {
    Process.emitAll(store.filter(e => e.subject == key))
  }

  def write(key: Subject, revision: Revision, data: E): Task[WriteResult[E]] = Task.delay {
    this.synchronized {
      lookup.get((key, revision)) match {
        case None =>
          val nextEntryNumber = Index(entriesCount)
          val newEl = Fact(nextEntryNumber, key, revision, data, LocalDateTime.now())

          lookup += (key, revision) -> nextEntryNumber
          store += newEl
          entriesCount += 1

          WriteSuccess(newEl)
        case Some(_) =>
          WriteFailure(s"Stream element ($key, $revision) already exists")
      }
    }
  }
}

object InMemoryJournal {
  def apply[E]: InMemoryJournal[E] = new InMemoryJournal[E]
} 
开发者ID:artempyanykh,项目名称:fair-share,代码行数:46,代码来源:InMemoryJournal.scala


示例4: Processes

//设置package包名称以及导入依赖的类
package com.gu.cloudwatch.metrics

import scala.concurrent.duration._

import scalaz.concurrent.Task
import scalaz.stream.{Process, process1, Process1, Wye}
import scalaz.stream.Process._
import scalaz.stream.ReceiveY.{ReceiveL, ReceiveR, HaltL, HaltR}
import scalaz.stream.DefaultScheduler

object Processes {

  implicit val scheduler = DefaultScheduler

  def unchunk[O]: Process1[Seq[O], O] =
    process1.id[Seq[O]].flatMap(emitAll)

  def sleepIfEmpty[A](duration: FiniteDuration)(p: Process[Task, Seq[A]]): Process[Task, Seq[A]] =
    p.flatMap(xs => if (xs.isEmpty) sleep(duration) else emit(xs))

  implicit class SourceSyntax[O](self: Process[Task, O]) {

    
  def emitEveryNth[A](n: Int): Process1[A, A] = {
    def go(acc: Map[A, Int]): Process1[A, A] =
      await1[A].flatMap { case a =>
        val newAcc = acc.insertWith(a, 1)(_ + _)
        if (newAcc(a) >= n)
          emit(a) fby go(acc - a)
        else
          go(newAcc)
      }
    go(Map.empty)
  }

} 
开发者ID:guardian,项目名称:scala-cloudwatch-metrics,代码行数:37,代码来源:Processes.scala


示例5: ProcessStepper

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

import java.util.concurrent.atomic.AtomicReference

import scalaz.concurrent.Task
import scalaz.std.option.none
import scalaz.stream.Process
import scalaz.syntax.monoid._
import scalaz.syntax.std.option._
import scalaz.Monoid

class ProcessStepper[A: Monoid](p: Process[Task, A]) {
  import scalaz.stream.Cause._
  import scalaz.stream.Process.{ Await, Emit, Halt, Step }

  private val cur = new AtomicReference[Process[Task, A]](p)

  def read: Task[Option[A]] = readFrom

  private val Done: Task[Option[A]] = Task.now(none[A])

  private def readFrom: Task[Option[A]] = {
    cur.get.step match {
      case s: Step[Task, A] @unchecked =>
        (s.head, s.next) match {
          case (Emit(os), cont) =>
            cur.set(cont.continue)
            Task.now(os.foldLeft[A](?)((a, o) => a |+| o).some)
          case (awt: Await[Task, Any, A] @unchecked, cont) =>
            awt.evaluate flatMap { p =>
              cur.set(p +: cont)
              readFrom
            }
        }
      case Halt(End) =>
        Done
      case Halt(Kill) =>
        Done
      case Halt(Error(rsn)) =>
        Task.fail(rsn)
    }
  }
} 
开发者ID:lukiano,项目名称:finagle-http4s,代码行数:44,代码来源:ProcessStepper.scala


示例6: Middleware

//设置package包名称以及导入依赖的类
package net.andimiller
package http4s
package cache

import java.time.{ZoneOffset, ZonedDateTime}
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

import org.http4s._
import org.http4s.util.CaseInsensitiveString

import scala.concurrent.duration._
import scala.util.Try
import scalaz.Kleisli
import scalaz.concurrent.Task
import scalaz.stream.Process

object Middleware {
  import KleisliMemo._
  import KleisliCache._

  type HttpMiddleware = Kleisli[Task, Request, Response] => Kleisli[Task, Request, Response]

  val memoMiddleware = new HttpMiddleware {
    override def apply(v1: Service[Request, Response]): Service[Request, Response] =
      v1.concurrentlyMemoize
  }

  val httpDateFormat =
    DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)

  def getCacheDuration(r: Response): FiniteDuration = {
    {
      for {
        now            <- r.headers.get(CaseInsensitiveString("date"))
        expires        <- r.headers.get(CaseInsensitiveString("expires"))
        nowInstant     <- Try(ZonedDateTime.parse(now.value, httpDateFormat)).toOption.map(_.toInstant)
        expiresInstant <- Try(ZonedDateTime.parse(expires.value, httpDateFormat)).toOption.map(_.toInstant)
      } yield ChronoUnit.SECONDS.between(nowInstant, expiresInstant).seconds
    }.filter(_.length > 0).getOrElse(Duration.Zero)
  }

  def cacheMiddleware(methods: List[Method] = Method.registered.toList) = new HttpMiddleware {
    override def apply(v1: Service[Request, Response]): Service[Request, Response] = {
      val cached = v1.map { r =>
        val body = r.body.runLog.unsafePerformSync
        ((r, body), getCacheDuration(r))
      }.concurrentlyCacheWithExpiringMap
      HttpService {
        case r if methods.contains(r.method) =>
          cached(r).map {
            case (resp, body) =>
              resp.copy(body = Process.emitAll(body))
          }
        case r =>
          v1(r)
      }
    }
  }

} 
开发者ID:andimiller,项目名称:http4s-cache,代码行数:62,代码来源:Middleware.scala


示例7: DBHolder

//设置package包名称以及导入依赖的类
package eve

import scala.collection.concurrent.TrieMap
import scalaz.stream.{Process, Sink, channel}
import scalaz.concurrent.Task
import scalaz._

import doobie.imports._

import models._
import shared._

case class DBHolder(xa: Transactor[Task]) {
  private val dbs = TrieMap[Process[Task, FleetState], Process[Task, Unit]]()

  def apply(owner: User, p: Process[Task, FleetState]): Process[Task, Unit] = {
    dbs
      .retain({ case (id, process) =>
        ! process.isHalt
      })
      .getOrElseUpdate(p, {
        p.observeThrough(channel.lift(f => FleetHistory.insert(owner, f).transact(xa))).map(_._2)
      })
  }
} 
开发者ID:reactormonk,项目名称:fleet-buddy,代码行数:26,代码来源:db.scala


示例8: WebSocket

//设置package包名称以及导入依赖的类
package eve

import argonaut._, argonaut.Argonaut._, argonaut.ArgonautShapeless._
import java.lang.NumberFormatException
import org.http4s.{ Response, Uri }
import org.http4s.server.websocket._
import org.http4s.websocket.WebsocketBits._
import scalaz.stream.{Exchange, Process, Sink}
import scalaz.concurrent.Task
import scalaz._

import models._
import oauth._
import shared._
import eveapi._
import eveapi.oauth._
import eveapi.errors.EveApiError
import eveapi.utils.Decoders._

object WebSocket {
  def apply(process: Process[Task, EveApiError \/ FleetState]): Task[Response] = {
    val serverToClient: Process[Task, ServerToClient] = process.pipe(ApiStream.toClient.liftR[EveApiError]).map(_.fold(err => throw err, x => x))
    val websocketProtocol: Process[Task, Text] = serverToClient.map(m => Text(m.asJson.nospaces))
    val fromClient = ApiStream.fromClient.contramap[WebSocketFrame]({
      case Text(t, _) => Parse.decodeEither[ClientToServer](t).fold(err => throw new IllegalArgumentException(s"Invalid json: $t"), x => x)
      case x => throw new IllegalArgumentException(s"Unexpected message: ${x}")
    })
    WS(Exchange(websocketProtocol, fromClient))
  }
} 
开发者ID:reactormonk,项目名称:fleet-buddy,代码行数:31,代码来源:websocket.scala


示例9: ExampleBytesService

//设置package包名称以及导入依赖的类
package com.imageintelligence.http4c.examples

import org.http4s.HttpService
import org.http4s.dsl._
import org.http4s.headers.Authorization
import scodec.bits.ByteVector

import scalaz.stream.Process
import scala.util.Random
import scalaz._
import Scalaz._
import scalaz.concurrent.Task

object ExampleBytesService {

  val service: HttpService = HttpService {
    case req @ _ -> Root / IntVar(n) => {
      println(req.headers.get(Authorization))
      val randomBytes: Process[Task, Byte] = Process.repeatEval(
        Task { (Random.nextInt(256) - 128).toByte }
      )
      Ok(ByteVector.apply(randomBytes.take(n).runLog.run))
    }
  }
} 
开发者ID:ImageIntelligence,项目名称:http4c,代码行数:26,代码来源:ExampleBytesService.scala


示例10: Middleware

//设置package包名称以及导入依赖的类
import java.time.{Instant, ZoneOffset, ZonedDateTime}
import java.time.format.DateTimeFormatter
import java.time.temporal.{ChronoField, ChronoUnit, TemporalField}

import org.http4s._
import org.http4s.server.HttpMiddleware
import org.http4s.util.CaseInsensitiveString

import scala.concurrent.duration._
import scala.util.Try
import scalaz.Kleisli
import scalaz.stream.Process

object Middleware {
  import KleisliMemo._
  import KleisliCache._

  val memoMiddleware = new HttpMiddleware {
    override def apply(v1: Service[Request, Response]): Service[Request, Response] =
      v1.concurrentlyMemoize
  }

  val httpDateFormat =
    DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)

  def getCacheDuration(r: Response): FiniteDuration = {
    {
      for {
        now            <- r.headers.get(CaseInsensitiveString("date"))
        expires        <- r.headers.get(CaseInsensitiveString("expires"))
        nowInstant     <- Try(ZonedDateTime.parse(now.value, httpDateFormat)).toOption.map(_.toInstant)
        expiresInstant <- Try(ZonedDateTime.parse(expires.value, httpDateFormat)).toOption.map(_.toInstant)
      } yield ChronoUnit.SECONDS.between(nowInstant, expiresInstant).seconds
    }.filter(_.length > 0).getOrElse(Duration.Zero)
  }

  def cacheMiddleware(methods: List[Method] = Method.registered.toList) = new HttpMiddleware {
    override def apply(v1: Service[Request, Response]): Service[Request, Response] = {
      val cached = v1.map { r =>
        val body = r.body.runLog.unsafePerformSync
        ((r, body), getCacheDuration(r))
      }.concurrentlyCacheWithExpiringMap
      HttpService {
        case r if methods.contains(r.method) =>
          cached(r).map {
            case (resp, body) =>
              resp.copy(body = Process.emitAll(body))
          }
        case r =>
          v1(r)
      }
    }
  }

} 
开发者ID:xxpizzaxx,项目名称:timerboard-net-backend-esi,代码行数:56,代码来源:Middleware.scala


示例11: Sources

//设置package包名称以及导入依赖的类
package com.joescii.scalaz.stream

import org.http4s.{Method, Request, Status, Uri}
import org.http4s.client.blaze.SimpleHttp1Client

import scalaz.{-\/, \/-}
import scalaz.concurrent.Task
import scalaz.stream.io
import scalaz.stream.Process

object Sources {
  lazy val fromFileSystem:Process[Task, String] = io.linesR("./logs/AWSLogs.log")

  private [this] val c = SimpleHttp1Client()
  private [this] val uri = Uri.uri("https://raw.githubusercontent.com/ozantunca/elb-log-analyzer/master/logs/AWSLogs.log")

  lazy val fromTehWebz:Process[Task, String] = {
    val t = c.fetch(Request(Method.GET, uri)){ res => res.status match {
      case Status.Ok => res
        .bodyAsText
        .runLog
    }}

    Process.await(t)(Process.emitAll)
  }
} 
开发者ID:joescii,项目名称:scalaz-stream-elb-logs,代码行数:27,代码来源:Sources.scala


示例12: Analyzer

//设置package包名称以及导入依赖的类
package com.joescii.scalaz.stream

import scalaz.concurrent.Task
import scalaz.stream.io
import scalaz.stream.Process

object Analyzer {
  def apply(source:Process[Task, String]):Task[Unit] =
    source
      .map(LogEntry.apply)
      .collect { case Some(e) => e }
      .map(t => Time.logDateFormat.format(t.timestamp.getTime))
      .intersperse("\n")
      .to(io.stdOut)
      .run
} 
开发者ID:joescii,项目名称:scalaz-stream-elb-logs,代码行数:17,代码来源:Analyzer.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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