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


Scala OffsetDateTime类代码示例

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


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

示例1: UuidSerializer

//设置package包名称以及导入依赖的类
package org.goingok.data.persistence.db.postgresql

import java.time.OffsetDateTime
import java.util.UUID

import org.json4s.JsonAST.JString
import org.json4s.{CustomSerializer, _}


object UuidSerializer extends CustomSerializer[UUID](format =>
  (
    {
      case JString(s) => UUID.fromString(s)
      case JNull => null
    },
    {
      case x: UUID => JString(x.toString)
    }
  )
)

object OffsetDateTimeSerializer extends CustomSerializer[OffsetDateTime](format => (
  {
    case JString(s) => OffsetDateTime.parse(s)
    case JNull => null
  },
  {
    case o:OffsetDateTime => JString(o.toString)
  }
)
) 
开发者ID:GoingOK,项目名称:goingok-server,代码行数:32,代码来源:CustomSerialisers.scala

示例2: SearchResult

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

import au.csiro.data61.magda.model.misc.{ DataSet, Facet, Region }
import au.csiro.data61.magda.model.Temporal
import au.csiro.data61.magda.model.misc
import au.csiro.data61.magda.search.SearchStrategy
import spray.json.{ DefaultJsonProtocol, JsString, JsValue, JsonFormat }
import au.csiro.data61.magda.api.{ Query, FilterValue, Specified, Unspecified }
import au.csiro.data61.magda.model.misc.{ QueryRegion }
import java.time.OffsetDateTime
import com.typesafe.config.Config

case class SearchResult(
  query: Query,
  hitCount: Long,
  facets: Option[Seq[Facet]] = None,
  dataSets: List[DataSet],
  errorMessage: Option[String] = None,
  strategy: Option[SearchStrategy] = None)

case class RegionSearchResult(
  query: String,
  hitCount: Long,
  regions: List[Region])

trait Protocols extends DefaultJsonProtocol with Temporal.Protocols with misc.Protocols {
  implicit object SearchStrategyFormat extends JsonFormat[SearchStrategy] {
    override def write(strat: SearchStrategy): JsString = JsString.apply(strat.name)

    override def read(json: JsValue): SearchStrategy = SearchStrategy.parse(json.convertTo[String])
  }
  class FilterValueFormat[T](implicit t: JsonFormat[T], implicit val config: Config) extends JsonFormat[FilterValue[T]] {
    override def write(filterValue: FilterValue[T]): JsValue = filterValue match {
      case Specified(inner) => t.write(inner)
      case Unspecified()    => JsString(filterValue.toString)
    }

    override def read(json: JsValue): FilterValue[T] = json match {
      case JsString(string) =>
        if (string.toLowerCase.equals(Unspecified().toString.toLowerCase()))
          Unspecified() else Specified(t.read(json))
      case other => Specified(t.read(other))
    }
  }
  implicit def stringFilterValueFormat(implicit config: Config) = new FilterValueFormat[String]
  implicit def offsetDateFilterValueFormat(implicit config: Config) = new FilterValueFormat[OffsetDateTime]
  implicit def queryRegionFilterValueFormat(implicit config: Config) = new FilterValueFormat[Region]()(apiRegionFormat, config)
  implicit def queryFormat(implicit config: Config) = jsonFormat8(Query.apply)
  implicit def searchResultFormat(implicit config: Config) = jsonFormat6(SearchResult.apply)
  implicit val regionSearchResultFormat = {
    implicit val regionFormat = apiRegionFormat
    jsonFormat3(RegionSearchResult.apply)
  }
}

object Protocols extends Protocols {
  
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:59,代码来源:Model.scala

示例3: EventMetadata

//设置package包名称以及导入依赖的类
package org.zalando.react.nakadi.client.models

import java.time.OffsetDateTime

case class EventMetadata(
  eid: String,
  event_type: Option[String] = None,
  occurred_at: OffsetDateTime,
  received_at: Option[OffsetDateTime] = None,
  parent_eids: Option[Seq[String]] = None,
  flow_id: Option[String] = None
)

sealed trait Event {
  def metadata: EventMetadata
}

case class BusinessEvent(
  metadata: EventMetadata,
  payload: EventPayload
) extends Event

case class DataChangeEvent(
  data_type: String,
  data_op: DataOpEnum.DataOp,
  data: EventPayload, // Raw payload for event
  metadata: EventMetadata
) extends Event

case class Cursor(
  partition: String,
  offset: String
)

case class EventStreamBatch(
  cursor: Cursor,
  events: Option[Seq[Event]] = None
)

case class EventTypeStatistics(
  expectedWriteRate: Option[Long] = None,
  messageSize: Option[Long] = None,
  readParallelism: Option[Long] = None,
  writeParallelism: Option[Long] = None
)

case class EventType(
  name: String,
  statistics: Option[EventTypeStatistics] = None,
  partitionKeyFields: Seq[String],
  dataKeyFields: Option[Seq[String]] = None,
  owningApplication: String,
  validationStrategies: Option[Seq[String]] = None,
  partitionResolutionStrategy: Option[play.api.libs.json.JsValue] = None,
  schema: Option[play.api.libs.json.JsValue] = None,
  category: EventTypeCategoryEnum.Category,
  enrichmentStrategies: Seq[String]
) 
开发者ID:zalando-nakadi,项目名称:reactive-nakadi,代码行数:59,代码来源:Models.scala

示例4: Payments

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

import java.time.OffsetDateTime
import Money._

import cats._
import cats.data._
import cats.implicits._

object Payments extends Utils {
  case class Account(no: String, name: String, openDate: OffsetDateTime, closeDate: Option[OffsetDateTime] = None)
  case class Payment(account: Account, amount: Money, dateOfPayment: OffsetDateTime)

  def creditsOnly(p: Payment): Money = if (p.amount.isDebit) zeroMoney else p.amount

  // concrete implementation
  def valuationConcrete(payments: List[Payment]) = payments.foldLeft(zeroMoney) { (a, e) =>
    add(a, creditsOnly(e))
  }

  // generic implementation
  def valuation(payments: List[Payment]): Money = {
    implicit val m: Monoid[Money] = Money.MoneyAddMonoid
    mapReduce(payments)(creditsOnly)
  }

  def maxPayment(payments: List[Payment]): Money = {
    implicit val m: Monoid[Money] = Money.MoneyOrderMonoid
    mapReduce(payments)(creditsOnly)
  }
} 
开发者ID:debasishg,项目名称:pigeon,代码行数:32,代码来源:Payments.scala

示例5: CreateTagFunction

//设置package包名称以及导入依赖的类
package com.atomist.rug.function.github

import java.time.OffsetDateTime

import com.atomist.rug.spi.Handlers.Status
import com.atomist.rug.spi._
import com.atomist.rug.spi.annotation.{Parameter, RugFunction, Secret, Tag}
import com.atomist.source.git.GitHubServices
import com.atomist.source.git.domain.{CreateTagRequest, Tagger}
import com.typesafe.scalalogging.LazyLogging

import scala.util.{Failure, Success, Try}


class CreateTagFunction
  extends AnnotatedRugFunction
    with LazyLogging
    with GitHubFunction {

  @RugFunction(name = "create-github-tag", description = "Creates a new tag on a commit",
    tags = Array(new Tag(name = "github"), new Tag(name = "issues")))
  def invoke(@Parameter(name = "tag") tag: String,
             @Parameter(name = "sha") sha: String,
             @Parameter(name = "message") message: String,
             @Parameter(name = "repo") repo: String,
             @Parameter(name = "owner") owner: String,
             @Parameter(name = "apiUrl") apiUrl: String,
             @Secret(name = "user_token", path = "github://user_token?scopes=repo") token: String): FunctionResponse = {

    logger.warn(s"Invoking createTag with tag '$tag', message '$message', sha '$sha', owner '$owner', repo '$repo', apiUrl '$apiUrl' and token '${safeToken(token)}'")

    val ghs = GitHubServices(token, apiUrl)
    Try {
      val ctr = CreateTagRequest(tag, message, sha, "commit", Tagger("Atomist Bot", "[email protected]", OffsetDateTime.now()))
      ghs.createTag(repo, owner, ctr)
    } match {
      case Success(newTag) =>
        Try(ghs.createReference(repo, owner, s"refs/tags/${newTag.tag}", newTag.sha))
        match {
          case Success(response) => FunctionResponse(Status.Success, Option(s"Successfully created annotated tag `$tag` in `$owner/$repo`"), None, JsonBodyOption(response))
          case Failure(e) =>
            val msg = s"Failed to create tag ref `$tag` on `$sha` in '$apiUrl' for `$owner/$repo`"
            logger.error(msg, e)
            FunctionResponse(Status.Failure, Some(msg), None, StringBodyOption(e.getMessage))
        }
      case Failure(e) =>
        val msg = s"Failed to create tag object `$tag` on `$sha` in '$apiUrl' for `$owner/$repo`"
        logger.error(msg, e)
        FunctionResponse(Status.Failure, Some(msg), None, StringBodyOption(e.getMessage))
    }
  }
} 
开发者ID:atomist,项目名称:rug-functions-github,代码行数:53,代码来源:CreateTagFunction.scala

示例6: safeToken

//设置package包名称以及导入依赖的类
package com.atomist.rug.function.github

import java.time.{OffsetDateTime, ZoneId}
import java.util.Date

import com.atomist.rug.runtime.Rug

trait GitHubFunction extends Rug {

  
  def safeToken(token: String): String =
    if (token != null)
      token.charAt(0) + ("*" * (token.length() - 2)) + token.last
    else
      null
}

object GitHubFunction {

  val ApiUrl = "https://api.github.com"

  val Events = Seq(
    "commit_comment",
    "create",
    "delete",
    "deployment",
    "deployment_status",
    "download",
    "follow",
    "fork",
    "fork_apply",
    "gist",
    "gollum",
    "issue_comment",
    "issues",
    "member",
    "page_build",
    "public",
    "pull_request",
    "pull_request_review_comment",
    "push",
    "release",
    "repository",
    "status",
    "team_add",
    "watch",
    "ping")

  def convertDate(date: Date): OffsetDateTime =
    if (date == null) null else OffsetDateTime.ofInstant(date.toInstant, ZoneId.systemDefault())
} 
开发者ID:atomist,项目名称:rug-functions-github,代码行数:52,代码来源:GitHubFunction.scala

示例7: deleteAll

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.store.impl

import java.time.OffsetDateTime

import akka.Done
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
import mesosphere.marathon.core.storage.store.{ IdResolver, PersistenceStore }
import mesosphere.marathon.state.StateMetrics

import scala.concurrent.Future

trait TimedPersistenceStore[K, Category, Serialized] extends StateMetrics {
  self: PersistenceStore[K, Category, Serialized] =>

  override def deleteAll[Id, V](k: Id)(implicit ir: IdResolver[Id, V, Category, K]): Future[Done] =
    timedWrite(self.deleteAll(k))

  override def get[Id, V](id: Id)(implicit
    ir: IdResolver[Id, V, Category, K],
    um: Unmarshaller[Serialized, V]): Future[Option[V]] =
    timedRead(self.get(id))

  override def get[Id, V](
    id: Id,
    version: OffsetDateTime)(implicit
    ir: IdResolver[Id, V, Category, K],
    um: Unmarshaller[Serialized, V]): Future[Option[V]] =
    timedRead(self.get(id, version))

  override def store[Id, V](id: Id, v: V)(implicit
    ir: IdResolver[Id, V, Category, K],
    m: Marshaller[V, Serialized]): Future[Done] =
    timedWrite(self.store(id, v))

  override def store[Id, V](id: Id, v: V,
    version: OffsetDateTime)(implicit
    ir: IdResolver[Id, V, Category, K],
    m: Marshaller[V, Serialized]): Future[Done] =
    timedWrite(self.store(id, v, version))

  override def deleteCurrent[Id, V](k: Id)(implicit ir: IdResolver[Id, V, Category, K]): Future[Done] =
    timedWrite(self.deleteCurrent(k))

  override def deleteVersion[Id, V](
    k: Id,
    version: OffsetDateTime)(implicit ir: IdResolver[Id, V, Category, K]): Future[Done] =
    timedWrite(self.deleteVersion(k, version))
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:50,代码来源:TimedPersistenceStore.scala

示例8: PersistenceStoreVersionedRepository

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.repository.impl

import java.time.OffsetDateTime

import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.scaladsl.Source
import akka.{ Done, NotUsed }
import mesosphere.marathon.core.storage.repository.{ Repository, VersionedRepository }
import mesosphere.marathon.core.storage.store.{ IdResolver, PersistenceStore }

import scala.concurrent.Future


class PersistenceStoreVersionedRepository[Id, V, K, C, S](
  persistenceStore: PersistenceStore[K, C, S],
  extractId: V => Id,
  extractVersion: V => OffsetDateTime)(implicit
  ir: IdResolver[Id, V, C, K],
  marshaller: Marshaller[V, S],
  unmarshaller: Unmarshaller[S, V]) extends PersistenceStoreRepository[Id, V, K, C, S](
  persistenceStore,
  extractId) with VersionedRepository[Id, V] {

  override def versions(id: Id): Source[OffsetDateTime, NotUsed] = persistenceStore.versions(id)

  override def getVersion(id: Id, version: OffsetDateTime): Future[Option[V]] =
    persistenceStore.get(id, version)

  override def storeVersion(v: V): Future[Done] =
    persistenceStore.store(extractId(v), v, extractVersion(v))

  override def deleteCurrent(id: Id): Future[Done] =
    persistenceStore.deleteCurrent(id)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:36,代码来源:PersistenceStoreRepository.scala

示例9: InMemTestClass1Resolver

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.storage.store.impl

import java.time.OffsetDateTime

import com.codahale.metrics.MetricRegistry
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.storage.store.impl.memory.{ InMemoryPersistenceStore, RamId }
import mesosphere.marathon.core.storage.store.{ IdResolver, PersistenceStoreTest, TestClass1 }
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.storage.store.InMemoryStoreSerialization

trait InMemoryTestClass1Serialization {
  implicit object InMemTestClass1Resolver extends IdResolver[String, TestClass1, String, RamId] {
    override def toStorageId(id: String, version: Option[OffsetDateTime]): RamId =
      RamId(category, id, version)
    override val category: String = "test-class"
    override val hasVersions = true

    override def fromStorageId(key: RamId): String = key.id
    override def version(v: TestClass1): OffsetDateTime = v.version
  }
}

class InMemoryPersistenceStoreTest extends AkkaUnitTest with PersistenceStoreTest
    with InMemoryStoreSerialization with InMemoryTestClass1Serialization {

  implicit val metrics = new Metrics(new MetricRegistry)

  behave like basicPersistenceStore("InMemoryPersistenceStore", new InMemoryPersistenceStore())
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:31,代码来源:InMemoryPersistenceStoreTest.scala

示例10: Serializers

//设置package包名称以及导入依赖的类
package com.wunder.pets.web

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID

import com.wunder.pets.pets._
import com.wunder.pets.validations.Validations.ErrorMessages
import play.api.libs.functional.syntax._
import play.api.libs.json._

object Serializers {
  // Order is important here (compiler needs to know about any implicit Reads/Writes before it uses them):

  implicit val uuidWrites = new Writes[UUID] {
    override def writes(o: UUID): JsValue = JsString(o.toString)
  }

  implicit val offsetDateTimeWrites = new Writes[OffsetDateTime] {
    override def writes(o: OffsetDateTime): JsValue = JsString(o.format(DateTimeFormatter.ISO_INSTANT))
  }

  implicit val errorMessagesWrites = new Writes[ErrorMessages] {
    override def writes(o: ErrorMessages): JsValue = Json.obj(
      "errors" -> o.map(JsString(_))
    )
  }

  def newAttributeWriter[T <: PetAttribute]: Writes[T] = {
    new Writes[T] {
      override def writes(o: T): JsValue = JsNumber(o.value)
    }
  }

  implicit val petStrengthWrites = newAttributeWriter[Strength]
  implicit val petSpeedWrites = newAttributeWriter[Speed]
  implicit val petIntelligenceWrites = newAttributeWriter[Intelligence]
  implicit val petIntegrityWrites = newAttributeWriter[Integrity]
  implicit val petNameWrites = new Writes[Name] {
    override def writes(o: Name): JsValue = JsString(o.value)
  }

  implicit val petWrites = new Writes[Pet] {
    override def writes(o: Pet): JsValue = Json.obj(
      "id" -> Json.toJson(o.id),
      "name" -> Json.toJson(o.name),
      "strength" -> Json.toJson(o.strength),
      "speed" -> Json.toJson(o.speed),
      "intelligence" -> Json.toJson(o.intelligence),
      "integrity" -> Json.toJson(o.integrity)
    )
  }

  implicit val createPetFormReads: Reads[CreatePetForm] = (
    (JsPath \ "name").read[String] and
      (JsPath \ "strength").read[Int] and
      (JsPath \ "speed").read[Int] and
      (JsPath \ "intelligence").read[Int] and
      (JsPath \ "integrity").read[Int]
    ) (CreatePetForm.apply _)
} 
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:62,代码来源:Serializers.scala

示例11: JournalEntry

//设置package包名称以及导入依赖的类
package akka.persistence.pg.journal

import java.time.OffsetDateTime

import akka.persistence.pg.{JsonString, PgConfig}

case class JournalEntry(id: Option[Long],
                        rowid: Option[Long],
                        persistenceId: String,
                        sequenceNr: Long,
                        deleted: Boolean,
                        payload: Option[Array[Byte]],
                        manifest: String,
                        uuid: String,
                        writerUuid: String,
                        created: OffsetDateTime,
                        tags: Map[String, String],
                        json: Option[JsonString])




trait JournalTable {
  self: PgConfig =>

  import driver.api._

  case class JournalEntryWithExtraDBIO(entry: JournalEntry,
                                       extraDBIO: Seq[DBIO[_]])

  class JournalTable(tag: Tag) extends Table[JournalEntry](
    tag, pluginConfig.schema, pluginConfig.journalTableName) {

    def id                  = column[Long]("id", O.AutoInc)
    def rowid               = column[Option[Long]]("rowid")
    def persistenceId       = column[String]("persistenceid")
    def sequenceNr          = column[Long]("sequencenr")
    def deleted             = column[Boolean]("deleted", O.Default(false))
    def payload             = column[Option[Array[Byte]]]("payload")
    def manifest            = column[String]("manifest")
    def uuid                = column[String]("uuid")
    def writerUuid          = column[String]("writeruuid")
    def created             = column[OffsetDateTime]("created", O.Default(OffsetDateTime.now()))
    def tags                = column[Map[String, String]]("tags", O.Default(Map.empty))
    def event               = column[Option[JsonString]]("event")

    def idForQuery =
      if (pluginConfig.idForQuery == "rowid") rowid
      else id.?

    def pk = primaryKey(s"${pluginConfig.journalTableName}_pk", (persistenceId, sequenceNr))

    def * = (id.?, rowid, persistenceId, sequenceNr, deleted, payload, manifest, uuid, writerUuid, created, tags, event) <>
      (JournalEntry.tupled, JournalEntry.unapply)

  }

  val journals = TableQuery[JournalTable]

} 
开发者ID:WegenenVerkeer,项目名称:akka-persistence-postgresql,代码行数:61,代码来源:JournalTable.scala

示例12: TestEventEncoder

//设置package包名称以及导入依赖的类
package akka.persistence.pg

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

import akka.persistence.pg.TestActor.{Incremented, Altered}
import akka.persistence.pg.event.JsonEncoder
import scala.util.parsing.json._

class TestEventEncoder extends JsonEncoder {

  val A = classOf[Altered]
  val I = classOf[Incremented]

  override def toJson = {
    case a: Altered => JsonString(s"""{
                                  | "type": "altered",
                                  | "id": "${a.id}",
                                  | "created": "${DateTimeFormatter.ISO_DATE_TIME.format(a.created)}"
                                  |}""".stripMargin)
    case i: Incremented => JsonString(s"""{
                                          | "count": ${i.count},
                                          | "created": "${DateTimeFormatter.ISO_DATE_TIME.format(i.created)}"
                                          |}""".stripMargin)
  }

  private def parseDateTime(jsonMap: Map[String, Any]): OffsetDateTime = {
    OffsetDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(jsonMap("created").asInstanceOf[String]))
  }

  private def altered(jsValue: Map[String, Any]): Altered = {
    Altered(jsValue("id").asInstanceOf[String], parseDateTime(jsValue))
  }

  private def incremented(jsValue: Map[String, Any]): Incremented = {
    Incremented(jsValue("count").asInstanceOf[Double].toInt, parseDateTime(jsValue))
  }

  private def parseJsonString(jsonString: JsonString) = {
    JSON.parseFull(jsonString.value).get.asInstanceOf[Map[String, Any]]
  }

  override def fromJson = {
    case (json, A) => altered(parseJsonString(json))
    case (json, I) => incremented(parseJsonString(json))
  }

} 
开发者ID:WegenenVerkeer,项目名称:akka-persistence-postgresql,代码行数:49,代码来源:TestEventEncoder.scala

示例13: User

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

import java.time.OffsetDateTime
import java.util.UUID
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec

import com.acromancer.acromancer.common.Utils
import com.acromancer.acromancer.user._

case class User(
  id: UserId,
  login: String,
  loginLowerCased: String,
  email: String,
  password: String,
  salt: String,
  createdOn: OffsetDateTime
)

object User {

  def withRandomUUID(
    login: String,
    email: String,
    plainPassword: String,
    salt: String,
    createdOn: OffsetDateTime
  ) = User(UUID.randomUUID(), login, login.toLowerCase, email, encryptPassword(plainPassword, salt), salt, createdOn)

  def encryptPassword(password: String, salt: String): String = {
    // 10k iterations takes about 10ms to encrypt a password on a 2013 MacBook
    val keySpec = new PBEKeySpec(password.toCharArray, salt.getBytes, 10000, 128)
    val secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
    val bytes = secretKeyFactory.generateSecret(keySpec).getEncoded
    Utils.toHex(bytes)
  }

  def passwordsMatch(plainPassword: String, user: User): Boolean = {
    Utils.constantTimeEquals(
      user.password,
      encryptPassword(plainPassword, user.salt)
    )
  }
}

case class BasicUserData(id: UserId, login: String, email: String, createdOn: OffsetDateTime)

object BasicUserData {
  def fromUser(user: User) = new BasicUserData(user.id, user.login, user.email, user.createdOn)
} 
开发者ID:GitsAndGlamour,项目名称:acromancer-game,代码行数:52,代码来源:User.scala

示例14: DateTimeEncoder

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

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID

import akka.http.scaladsl.model.StatusCodes.ClientError
import io.circe._
import io.circe.syntax._

trait CirceEncoders {

  val dateTimeFormat = DateTimeFormatter.ISO_DATE_TIME

  implicit object DateTimeEncoder extends Encoder[OffsetDateTime] {
    override def apply(dt: OffsetDateTime): Json = dateTimeFormat.format(dt).asJson
  }

  implicit object UuidEncoder extends Encoder[UUID] {
    override def apply(u: UUID): Json = u.toString.asJson
  }

  implicit object ClientErrorEncoder extends Encoder[ClientError] {
    override def apply(a: ClientError): Json = a.defaultMessage.asJson
  }
} 
开发者ID:GitsAndGlamour,项目名称:acromancer-game,代码行数:27,代码来源:CirceEncoders.scala

示例15: TaskInput

//设置package包名称以及导入依赖的类
package io.github.maxkorolev.task

import java.time.{ Instant, LocalDateTime, OffsetDateTime, ZoneId }
import java.util.concurrent.Callable

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import io.github.maxkorolev.base.BaseService
import io.github.maxkorolev.task.TaskManager.PushTask

import scala.concurrent.duration._

case class TaskInput(time: Long)

trait TaskService extends BaseService {

  protected val taskRoutes =
    pathPrefix("task") {
      post {
        entity(as[TaskInput]) { in =>
          log.info("/task executed")

          val time = Instant.ofEpochMilli(OffsetDateTime.now().toInstant.toEpochMilli + in.time * 1000L).atZone(ZoneId.systemDefault()).toLocalDateTime

          val millis = time.atZone(ZoneId.systemDefault()).toInstant.toEpochMilli
          val task = new Task {
            val time = millis
            val timeout = 10.seconds
            override def call(): Any = {
              Thread.sleep(3000)
            }
          }
          taskManager ! PushTask(task)

          complete(StatusCodes.OK)
        }
      }
    }
} 
开发者ID:maxkorolev,项目名称:pix,代码行数:40,代码来源:TaskService.scala


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