当前位置: 首页>>代码示例>>Scala>>正文


Scala ZoneOffset类代码示例

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


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

示例1: WebhookApi

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.indexer.external.registry

import au.csiro.data61.magda.indexer.search.SearchIndexer
import au.csiro.data61.magda.api.BaseMagdaApi
import au.csiro.data61.magda.model.Registry.WebHookPayload
import akka.event.LoggingAdapter
import akka.http.scaladsl.server.Directives._
import scala.util.Failure
import scala.util.Success
import akka.http.scaladsl.model.StatusCodes.{ Accepted, Conflict, OK, BadRequest }
import akka.actor.ActorSystem
import scala.concurrent.Future
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json._
import au.csiro.data61.magda.model.Registry.{ Protocols => RegistryProtocols }
import au.csiro.data61.magda.indexer.crawler.Crawler
import au.csiro.data61.magda.indexer.crawler.CrawlerApi
import au.csiro.data61.magda.indexer.external.InterfaceConfig
import com.typesafe.config.Config
import au.csiro.data61.magda.indexer.external.registry.RegistryConverters
import akka.stream.scaladsl.Source
import java.time.ZoneOffset

class WebhookApi(indexer: SearchIndexer)(implicit system: ActorSystem, config: Config) extends BaseMagdaApi with RegistryProtocols {
  implicit val ec = system.dispatcher
  override def getLogger = system.log

  val registryConfig = InterfaceConfig.all.get("registry")
  implicit val defaultOffset = ZoneOffset.of(config.getString("time.defaultOffset"))

  val routes =
    magdaRoute {
      post {
        entity(as[WebHookPayload]) { payload =>
          payload.records match {
            // TODO: Handle registry config not found
            case Some(records) =>
              val dataSets = records.map(record => RegistryConverters.registryDataSetConv(registryConfig.get)(record))

              onSuccess(indexer.index(registryConfig.get, Source(dataSets))) { result =>
                complete(Accepted)
              }
            case None =>
              getLogger.error("Recieved webhook payload with no records")
              complete(BadRequest, "Needs records")
          }
        }
      }
    }
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:52,代码来源:WebhookApi.scala

示例2: putStatus

//设置package包名称以及导入依赖的类
package org.wex.cmsfs.common.monitor

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

import com.redis.RedisClient
import play.api.libs.json._

trait MonitorStatus {
  val r = new RedisClient("redis.cmsfs.org", 6379)

  def putStatus(id: Int, stage: String)(state: Boolean, result: String) = {
    val stageStatus = CoreMonitorStageStatus(state, result)
    val key = s"${id}_${stage}"

    r.set(key, Json.toJson(stageStatus).toString())
  }
}

case class CoreMonitorStatus(id: Int, category: String, name: String, metric: String,
                             collect: CoreMonitorCollectStatus,
                             analyze: Option[CoreMonitorAnalyzeStatus],
                             Alarm: Option[CoreMonitorAlarmStatus])

object CoreMonitorStatus {
  implicit val format: Format[CoreMonitorStatus] = Json.format
}

case class CoreMonitorStageStatus(state: Boolean, result: String,
                                  timestamp: String = ZonedDateTime.now(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:m:s")))

object CoreMonitorStageStatus {
  implicit val format: Format[CoreMonitorStageStatus] = Json.format
}

case class CoreMonitorCollectStatus(state: Boolean, timestamp: String, result: String)

object CoreMonitorCollectStatus {
  implicit val format: Format[CoreMonitorCollectStatus] = Json.format
}

case class CoreMonitorAnalyzeStatus(state: Boolean, timestamp: String, result: String)

object CoreMonitorAnalyzeStatus {
  implicit val format: Format[CoreMonitorAnalyzeStatus] = Json.format
}

case class CoreMonitorAlarmStatus(state: Boolean, timestamp: String, result: String)

object CoreMonitorAlarmStatus {
  implicit val format: Format[CoreMonitorAlarmStatus] = Json.format
} 
开发者ID:shinhwagk,项目名称:cmsfs,代码行数:53,代码来源:MonitorStatus.scala

示例3: Rfc3339UtilTest

//设置package包名称以及导入依赖的类
package de.zalando.play.controllers

import java.time.{ LocalDateTime, ZoneId, ZoneOffset, ZonedDateTime }

import org.scalatest.{ FunSpec, MustMatchers }


class Rfc3339UtilTest extends FunSpec with MustMatchers {

  val dtz = ZoneId.of("UTC")
  val offset = ZoneOffset.UTC
  //noinspection ScalaStyle
  val date = ZonedDateTime.of(LocalDateTime.ofEpochSecond(1451911387L, 0, offset), dtz)

  describe("Rfc3339UtilTest") {

    it("should parse RFC3339 DateTime") {
      Rfc3339Util.parseDateTime("2007-05-01T15:43:26-00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]"
      Rfc3339Util.parseDateTime("2007-05-01T15:43:26+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]"
      Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452-01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T16:43:26.345200Z[UTC]"
      Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T14:43:26.345200Z[UTC]"
      Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26.345200Z[UTC]"
    }
    it("should parse RFC3339 Date") {
      Rfc3339Util.parseDate("2007-05-01").toString mustBe "2007-05-01"
      Rfc3339Util.parseDate("2008-05-01").toString mustBe "2008-05-01"
      Rfc3339Util.parseDate("2007-08-01").toString mustBe "2007-08-01"
      Rfc3339Util.parseDate("2007-05-08").toString mustBe "2007-05-08"
    }
    it("should write DateTime") {
      Rfc3339Util.writeDateTime(date) mustBe "2016-01-04T12:43:07.0000+0000"
    }
    it("should write Date") {
      Rfc3339Util.writeDate(date.toLocalDate) mustBe "2016-01-04"
    }
  }
} 
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:38,代码来源:Rfc3339UtilTest.scala

示例4: TimeStampFormatter

//设置package包名称以及导入依赖的类
package wvlet.core.scales

import java.time.{Instant, ZoneId, ZoneOffset, ZonedDateTime}
import java.time.format.{DateTimeFormatterBuilder, SignStyle}
import java.util.Locale


object TimeStampFormatter {
  import java.time.temporal.ChronoField._

  val noSpaceTimestampFormat = new DateTimeFormatterBuilder()
                               .parseCaseInsensitive()
                               .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
                               .appendLiteral('-')
                               .appendValue(MONTH_OF_YEAR, 2)
                               .appendLiteral('-')
                               .appendValue(DAY_OF_MONTH, 2)
                               .appendLiteral('T')
                               .appendValue(HOUR_OF_DAY, 2)
                               .appendLiteral(':')
                               .appendValue(MINUTE_OF_HOUR, 2)
                               .appendLiteral(':')
                               .appendValue(SECOND_OF_MINUTE, 2)
                               .appendLiteral('.')
                               .appendValue(MILLI_OF_SECOND, 3)
                               .appendOffset("+HHMM", "Z")
                               .toFormatter(Locale.US)

  val humanReadableTimestampFormatter = new DateTimeFormatterBuilder()
                                        .parseCaseInsensitive()
                                        .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
                                        .appendLiteral('-')
                                        .appendValue(MONTH_OF_YEAR, 2)
                                        .appendLiteral('-')
                                        .appendValue(DAY_OF_MONTH, 2)
                                        .appendLiteral(' ')
                                        .appendValue(HOUR_OF_DAY, 2)
                                        .appendLiteral(':')
                                        .appendValue(MINUTE_OF_HOUR, 2)
                                        .appendLiteral(':')
                                        .appendValue(SECOND_OF_MINUTE, 2)
                                        .appendOffset("+HHMM", "Z")
                                        .toFormatter(Locale.US)

  def formatTimestamp(time:ZonedDateTime): String = {
    humanReadableTimestampFormatter.format(time)
  }

  def formatTimestamp(timeMillis: Long, zone:ZoneOffset=TimeWindow.systemZone): String = {
    val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), zone)
    humanReadableTimestampFormatter.format(timestamp)
  }

  def formatTimestampWithNoSpaace(timeMillis:Long) : String = {
    val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), TimeWindow.systemZone)
    noSpaceTimestampFormat.format(timestamp)
  }

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

示例5: YahooController

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

import java.time.{LocalDate, ZoneOffset}
import utilities.DateImplicits._
import play.api.Logger
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import services.YService

import scala.concurrent.ExecutionContext

class YahooController(yahooService: YService)(implicit ec: ExecutionContext) extends Controller {

  def getQuote(symbol:String) = Action.async {
    Logger.info(s"[YAHOO] -- Loading options for $symbol")
    val result = yahooService.getQuotesFromYahoo(symbol)
    result.map{ r=> Ok(Json.toJson(r)) }
  }

  def getOptionsByExpiration(symbol: String, expiration: String)= Action.async{

    Logger.info(s"[YAHOO] -- Loading CHAIN for $symbol -  $expiration")

    val dt : LocalDate = expiration
    val expiry: Long = dt.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli / 1000
    val result = yahooService.getOptionsByExpiration(symbol, expiry)
    result.map{ r=> Ok(Json.toJson(r)) }
  }
} 
开发者ID:yarshad,项目名称:griffin-api,代码行数:30,代码来源:YahooController.scala

示例6: validate

//设置package包名称以及导入依赖的类
package im.actor.server.activation.common

import java.time.temporal.ChronoUnit._
import java.time.{ LocalDateTime, ZoneOffset }

import akka.http.scaladsl.util.FastFuture
import cats.data.Xor
import im.actor.server.db.ActorPostgresDriver.api._
import im.actor.server.model.AuthCode
import im.actor.server.persist.AuthCodeRepo

import scala.concurrent.{ ExecutionContext, Future }

trait CommonAuthCodes {
  self: ActivationProvider ?

  protected val activationConfig: ActivationConfig
  protected val db: Database
  protected implicit val ec: ExecutionContext

  override def validate(txHash: String, code: String): Future[ValidationResponse] = {
    val action = for {
      optCode ? AuthCodeRepo.findByTransactionHash(txHash)
      result ? optCode map {
        case s if isExpired(s, activationConfig.expiration.toMillis) ?
          for (_ ? AuthCodeRepo.deleteByTransactionHash(txHash)) yield ExpiredCode
        case s if s.code != code ?
          if (s.attempts + 1 >= activationConfig.attempts) {
            for (_ ? AuthCodeRepo.deleteByTransactionHash(txHash)) yield ExpiredCode
          } else {
            for (_ ? AuthCodeRepo.incrementAttempts(txHash, s.attempts)) yield InvalidCode
          }
        case _ ? DBIO.successful(Validated)
      } getOrElse DBIO.successful(InvalidHash)
    } yield result
    db.run(action)
  }

  protected def deleteAuthCode(txHash: String): Future[Unit] = db.run(AuthCodeRepo.deleteByTransactionHash(txHash).map(_ ? ()))

  protected def createAuthCodeIfNeeded(resp: CodeFailure Xor Unit, txHash: String, code: String): Future[Int] = resp match {
    case Xor.Left(_)  ? FastFuture.successful(0)
    case Xor.Right(_) ? db.run(AuthCodeRepo.createOrUpdate(txHash, code))
  }

  protected def isExpired(code: AuthCode, expiration: Long): Boolean =
    code.createdAt.plus(expiration, MILLIS).isBefore(LocalDateTime.now(ZoneOffset.UTC))

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:50,代码来源:CommonAuthCodes.scala

示例7: AuthToken

//设置package包名称以及导入依赖的类
package im.actor.server.model

import java.time.{ LocalDateTime, ZoneOffset }

/**
 * ????Token?
 * by Lining 2016/8/25
 * @param userId
 * @param token
 * @param attempts
 * @param createdAt
 */
@SerialVersionUID(1L)
case class AuthToken(
  userId:    String,
  token:     String,
  attempts:  Int           = 0,
  createdAt: LocalDateTime = LocalDateTime.now(ZoneOffset.UTC)
) 
开发者ID:wex5,项目名称:dangchat-server,代码行数:20,代码来源:AuthToken.scala

示例8: Token

//设置package包名称以及导入依赖的类
package im.actor.server.oauth

import java.time.{ ZoneOffset, LocalDateTime }

case class Token(
  accessToken:  String,
  tokenType:    String,
  expiresIn:    Long,
  refreshToken: Option[String],
  createdAt:    LocalDateTime  = LocalDateTime.now(ZoneOffset.UTC)
)

case class Profile(
  email:      String,
  familyName: Option[String],
  name:       Option[String],
  givenName:  Option[String],
  picture:    Option[String],
  gender:     Option[String],
  locale:     Option[String]
) 
开发者ID:wex5,项目名称:dangchat-server,代码行数:22,代码来源:Models.scala

示例9: LocalDateTimeCompanionSpec

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

import java.time.{LocalDateTime, ZoneOffset}

import org.scalatest.{FlatSpec, MustMatchers}


class LocalDateTimeCompanionSpec extends FlatSpec with MustMatchers {
  behavior of "LocalDateTimeCompanion"

  it should "convert epoch time to LocalDateTime" in {
    val expected = LocalDateTime.ofEpochSecond(1388534400l, 123000000, ZoneOffset.UTC)
    val actual = LocalDateTimeCompanion.unapply("1388534400123")
    actual must contain(expected)
  }
  it should "convert LocalDateTime to epoch" in {
    val expected = 1388534401321l
    val actual = LocalDateTimeCompanion.toEpochMilliseconds(LocalDateTime.ofEpochSecond(1388534401l, 321000000, ZoneOffset.UTC))
    actual mustEqual expected
  }
} 
开发者ID:rmleon,项目名称:sample.scala.apache_flink.1,代码行数:22,代码来源:LocalDateTimeCompanionSpec.scala

示例10: User

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

import java.time.temporal.ChronoUnit
import java.time.{ZoneOffset, ZonedDateTime}
import java.util.{Date, UUID}

import com.datastax.driver.core.utils.UUIDs
import models.Language.Language
import models.Task.yearAsOfJan1


case class User(name: String, password: String, timeuuid: UUID = UUIDs.timeBased())

case class Task(year: Date, lang: Language, timeuuid: UUID, name: String, description: String,
                solutionTemplate: String, referenceSolution: String, suite: String, solutionTrait: String)

object Task {
  val now = 0

  def yearAsOfJan1(ago: Int = now) =
    Date.from(ZonedDateTime.now(ZoneOffset.UTC)
      .truncatedTo(ChronoUnit.DAYS)
      .withDayOfMonth(1).withMonth(1)
      .minusYears(ago).toInstant)
}

case class NewTask(lang: Language, name: String, description: String, solutionTemplate: String,
                   referenceSolution: String, suite: String, solutionTrait: String, year: Date = yearAsOfJan1(),
                   timeuuid: UUID = UUIDs.timeBased())

object Language extends Enumeration {
  type Language = Value

  val scalaLang = Value
} 
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:36,代码来源:Model.scala

示例11: PriceRequest

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

import java.time.{LocalDate, ZoneOffset}

case class PriceRequest(
  tickerSymbol: TickerSymbol,
  businessDate: LocalDate,
  today: LocalDate
)

object PriceRequest {
  def apply(tickerSymbol: TickerSymbol): PriceRequest = {
    val now = LocalDate.now(ZoneOffset.UTC)
    PriceRequest(tickerSymbol, now, now)
  }
}

case class PriceInstant(
  date: LocalDate,
  value: BigDecimal
)

trait PriceComputation extends (DailyValue => BigDecimal)

object Computation {
  object MedianPrice extends PriceComputation {
    override def apply(v1: DailyValue): BigDecimal = (v1.high + v1.low) / 2
  }
} 
开发者ID:alexflav23,项目名称:exercises,代码行数:30,代码来源:PriceInstant.scala

示例12: RefreshTokenStorageImpl

//设置package包名称以及导入依赖的类
package com.acromancer.acromancer.user.application

import java.time.{Instant, ZoneOffset}
import java.util.UUID
import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import com.acromancer.acromancer.user.domain.RememberMeToken
import com.softwaremill.session.{RefreshTokenData, RefreshTokenLookupResult, RefreshTokenStorage}

import scala.concurrent.duration.{Duration, FiniteDuration}
import scala.concurrent.{ExecutionContext, Future}

class RefreshTokenStorageImpl(dao: RememberMeTokenDao, system: ActorSystem)(implicit ec: ExecutionContext)
    extends RefreshTokenStorage[Session] {

  override def lookup(selector: String) = {
    dao.findBySelector(selector).map(_.map(t =>
      RefreshTokenLookupResult(t.tokenHash, t.validTo.toInstant.toEpochMilli, () => Session(t.userId))))
  }

  override def store(data: RefreshTokenData[Session]) =
    dao.add(RememberMeToken(UUID.randomUUID(), data.selector, data.tokenHash, data.forSession.userId,
      Instant.ofEpochMilli(data.expires).atOffset(ZoneOffset.UTC)))

  override def remove(selector: String) =
    dao.remove(selector)

  override def schedule[S](after: Duration)(op: => Future[S]) =
    system.scheduler.scheduleOnce(FiniteDuration(after.toSeconds, TimeUnit.SECONDS), new Runnable {
      override def run() = op
    })
} 
开发者ID:GitsAndGlamour,项目名称:acromancer-game,代码行数:34,代码来源:RefreshTokenStorageImpl.scala

示例13: Signer

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

import java.security.MessageDigest
import java.time.format.DateTimeFormatter
import java.time.{ZoneOffset, ZonedDateTime}

import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.stream.Materializer

import scala.concurrent.{ExecutionContext, Future}


object Signer {
  val dateFormatter = DateTimeFormatter.ofPattern("YYYYMMdd'T'HHmmssX")

  def signedRequest(request: HttpRequest, key: SigningKey, date: ZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC))(implicit mat: Materializer): Future[HttpRequest] = {
    implicit val ec: ExecutionContext = mat.executionContext
    val hashedBody = request.entity.dataBytes.runWith(StreamUtils.digest()).map { case hash =>
      Utils.encodeHex(hash.toArray)
    }

    hashedBody.map { case hb =>
      val headersToAdd = Seq(RawHeader("x-amz-date", date.format(dateFormatter)), RawHeader("x-amz-content-sha256", hb)) ++ sessionHeader(key.credentials)
      val reqWithHeaders = request.withHeaders(request.headers ++ headersToAdd)
      val cr = CanonicalRequest.from(reqWithHeaders)
      val authHeader = authorizationHeader("AWS4-HMAC-SHA256", key, date, cr)
      reqWithHeaders.withHeaders(reqWithHeaders.headers ++ Seq(authHeader))
    }
  }

  def sessionHeader(creds: AWSCredentials): Option[HttpHeader] = {
    creds match {
      case bc: BasicCredentials => None
      case AWSSessionCredentials(_, _, sessionToken) => Some(RawHeader("X-Amz-Security-Token", sessionToken))
    }
  }

  def authorizationHeader(algorithm: String, key: SigningKey, requestDate: ZonedDateTime, canonicalRequest: CanonicalRequest): HttpHeader = {
    RawHeader("Authorization", authorizationString(algorithm, key, requestDate, canonicalRequest))
  }

  def authorizationString(algorithm: String, key: SigningKey, requestDate: ZonedDateTime, canonicalRequest: CanonicalRequest): String = {
    s"$algorithm Credential=${key.credentialString}, SignedHeaders=${canonicalRequest.signedHeaders}, Signature=${key.hexEncodedSignature(stringToSign(algorithm, key, requestDate, canonicalRequest).getBytes())}"
  }

  def stringToSign(algorithm: String, signingKey: SigningKey, requestDate: ZonedDateTime, canonicalRequest: CanonicalRequest): String = {
    val digest = MessageDigest.getInstance("SHA-256")
    val hashedRequest = Utils.encodeHex(digest.digest(canonicalRequest.canonicalString.getBytes()))
    s"$algorithm\n${requestDate.format(dateFormatter)}\n${signingKey.scope.scopeString}\n$hashedRequest"
  }

} 
开发者ID:bluelabsio,项目名称:s3-stream,代码行数:54,代码来源:Signer.scala

示例14: TimeFetchTest

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

import java.time.{LocalDateTime, ZoneOffset}

import akka.actor.{ActorSystem, Terminated}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Millis, Seconds, Span}
import org.scalatest.{Matchers, WordSpec}
import rere.driver.pool.ConnectionPool

import scala.concurrent.ExecutionContext

class TimeFetchTest extends WordSpec with ScalaFutures with Matchers {

  implicit val defaultPatience =
    PatienceConfig(timeout = Span(15, Seconds), interval = Span(100, Millis))

  "driver" should {
    "fetch time" in {
      implicit val ec = ExecutionContext.global
      implicit val system = ActorSystem("rere")
      val credentials = Credentials("admin", "")
      val settings = ConnectionSettings("127.0.0.1", 28015, ConnectionSettings.noSslConnection)

      val poolSize = 1
      val pool = ConnectionPool.create(credentials, settings, "pool", poolSize)
      import rere.driver.runners.all._
      import rere.ql.queries.all._

      val utcOffset = ZoneOffset.UTC
      val now = LocalDateTime.now(utcOffset)

      whenReady(r.now().run(pool).future()) { result =>
        Math.abs(
          result.toLocalDateTime.toInstant(utcOffset).getEpochSecond - now.toInstant(utcOffset).getEpochSecond
        ) should be < 10L

        Math.abs(
          result.toInstant.getEpochSecond - now.toInstant(utcOffset).getEpochSecond
        ) should be < 10L

        whenReady(pool.shutdown()) { shutdownResult =>
          shutdownResult.queriesStarted shouldBe 1L
          shutdownResult.connectionsTurnedOff shouldBe poolSize

          whenReady(system.terminate()) { terminationResult =>
            terminationResult shouldBe an[Terminated]
          }
        }
      }
    }
  }
} 
开发者ID:pbaun,项目名称:rere,代码行数:54,代码来源:TimeFetchTest.scala

示例15: 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


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