本文整理汇总了Scala中java.time.ZonedDateTime类的典型用法代码示例。如果您正苦于以下问题:Scala ZonedDateTime类的具体用法?Scala ZonedDateTime怎么用?Scala ZonedDateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ZonedDateTime类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: Rfc3339Util
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.time.format.{ DateTimeFormatter, DateTimeParseException }
import java.time.{ LocalDate, ZoneId, ZonedDateTime }
object Rfc3339Util {
private val fullDate = DateTimeFormatter.ofPattern("yyyy-MM-dd")
private val shortDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
private val shortDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
private val fullDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'")
private val dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSZ")
def parseDateTime(datestring: String): ZonedDateTime =
if (datestring.endsWith("Z") || datestring.endsWith("z")) parseFull(datestring)
else parseParts(datestring)
def parseDate(datestring: String): LocalDate =
LocalDate.parse(datestring, fullDate)
def writeDate(date: LocalDate): String = fullDate.format(date)
def writeDateTime(date: ZonedDateTime): String = dateTime.format(date)
private def parseParts(datestring: String): ZonedDateTime = {
//step one, split off the timezone.
val sepChar = if (datestring.indexOf('+') > 0) '+' else '-'
val firstpart = datestring.substring(0, datestring.lastIndexOf(sepChar.toInt))
val secondpart = datestring.substring(datestring.lastIndexOf(sepChar.toInt))
//step two, remove the colon from the timezone offset
val thirdpart = secondpart.substring(0, secondpart.indexOf(':')) + secondpart.substring(secondpart.indexOf(':') + 1)
val dstring = firstpart + thirdpart
try {
ZonedDateTime.parse(dstring, shortDateTime)
} catch {
case pe: DateTimeParseException =>
ZonedDateTime.parse(dstring, dateTime)
}
}
private def parseFull(datestring: String): ZonedDateTime = {
val z = ZoneId.systemDefault()
try {
ZonedDateTime.parse(datestring, shortDTWithTicks.withZone(z))
} catch {
case p: DateTimeParseException => ZonedDateTime.parse(datestring, fullDTWithTicks.withZone(z))
}
}
}
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:52,代码来源:Rfc3339Util.scala
示例2: genericEncoder
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.range.datetime
import java.sql.{PreparedStatement, Types}
import java.time.{LocalDate, ZonedDateTime, LocalDateTime}
import java.util.Date
import io.getquill.source.jdbc.JdbcSource
trait Encoders {
this: JdbcSource[_, _] =>
import Formatters._
private def genericEncoder[T](valueToString: (T => String)): Encoder[T] = {
new Encoder[T] {
override def apply(index: Int, value: T, row: PreparedStatement) = {
val sqlLiteral = valueToString(value)
row.setObject(index + 1, sqlLiteral, Types.OTHER)
row
}
}
}
private def tuple[T](t: (T, T))(valToStr: T => String) = s"[${valToStr(t._1)}, ${valToStr(t._2)}]"
implicit val dateTupleEncoder: Encoder[(Date, Date)] = genericEncoder(tuple(_)(formatDate))
implicit val localDateTimeTupleEncoder: Encoder[(LocalDateTime, LocalDateTime)] =
genericEncoder(tuple(_)(formatLocalDateTime))
implicit val zonedDateTimeTupleEncoder: Encoder[(ZonedDateTime, ZonedDateTime)] =
genericEncoder(tuple(_)(formatZonedDateTime))
implicit val dateTimeTupleEncoder: Encoder[(LocalDate, LocalDate)] =
genericEncoder(t => s"[${formatLocalDate(t._1)}, ${formatLocalDate(t._2)})")
}
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:34,代码来源:Encoders.scala
示例3: MessageParser
//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.collector.parsing
import java.time.ZonedDateTime
import FromCSVtoCaseClass.rowParserFor
import com.darienmt.airplaneadventures.basestation.data.BaseStation._
import scala.util.{ Failure, Success, Try }
object MessageParser {
def apply(l: String): Message = parse(l.split(",").toList) match {
case Success(m) => m
case Failure(ex) => ErrorMessage(l, ex.toString, ZonedDateTime.now())
}
protected val parse: List[String] => Try[Message] = {
case "SEL" :: "" :: rest => rowParserFor[SelectionChangeMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "ID" :: "" :: rest => rowParserFor[IdMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "AIR" :: "" :: rest => rowParserFor[NewAircraftMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10))
case "STA" :: "" :: rest => rowParserFor[StatusChangeMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "CLK" :: "" :: rest => rowParserFor[ClickMessage](rest, List(3, 7, 8, 9, 10))
case "MSG" :: "1" :: rest => rowParserFor[ESIdentificationAncCategoryMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 11))
case "MSG" :: "2" :: rest => rowParserFor[ESSurfacePositionMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 22))
case "MSG" :: "3" :: rest => rowParserFor[ESAirbornePositionMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 16, 19, 20, 21, 22))
case "MSG" :: "4" :: rest => rowParserFor[ESAirborneVelocityMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 17))
case "MSG" :: "5" :: rest => rowParserFor[SurveillanceAltMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 19, 21, 22))
case "MSG" :: "6" :: rest => rowParserFor[SurveillanceIdMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 19, 20, 21, 22))
case "MSG" :: "7" :: rest => rowParserFor[AirToAirMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 12, 22))
case "MSG" :: "8" :: rest => rowParserFor[AllCallReplyMessage](rest, List(3, 4, 5, 6, 7, 8, 9, 10, 22))
case x => Failure(new Exception(s"Unknown message => $x"))
}
}
开发者ID:darienmt,项目名称:airplane-adventures,代码行数:33,代码来源:MessageParser.scala
示例4: Global
//设置package包名称以及导入依赖的类
package shared
import play.api.libs.json._
import models.Building
import java.time.{ ZonedDateTime, ZoneId, DayOfWeek }
//Constants or constnat builders that are not messages
object Global {
final val ZONEID = "Asia/Seoul"
val baseStartTime = 9
val baseEndTime = 17
val classroomList = ("1202" :: "1203" :: "1204" :: "1205" :: "1206" :: "1207" :: "1208" :: Nil) ++
("1210" :: "1211" :: "1301" :: "1302" :: "1303" :: "1304" :: "1305" :: "1306" :: "1307" :: Nil) ++
("1308" :: "1309" :: "1310" :: "1311" :: "1401" :: "1402" :: "1403" :: "1404" :: "1405" :: Nil) ++
("1406" :: "1407" :: "1408" :: "1409" :: "1501" :: "1502" :: "1503" :: "1504" :: "1505" :: Nil) ++
("1506" :: "1507" :: "1508" :: "1509" :: "1601" :: "1602" :: "1603" :: "1604" :: "1605" :: Nil) ++
("1606" :: "1607" :: "1608" :: "1609" :: "2201" :: "2202" :: "2203" :: "2204" :: "2205" :: Nil) ++
("2207" :: "2208" :: "2210" :: "2401" :: "2402" :: "2403" :: "2404" :: "2405" :: "2407" :: Nil) ++
("2408" :: "2409" :: "2501" :: "2502" :: "2503" :: "2504" :: "2506" :: "2507" :: "2508" :: Nil) ++
("2509" :: "3201" :: "3203" :: "3205" :: "3206" :: "3301" :: "3302" :: "3303" :: "3304" :: Nil) ++
("3305" :: "3306" :: "3307" :: "3308" :: "3401" :: "3402" :: "3403" :: "3404" :: "3405" :: Nil) ++
("3406" :: "3407" :: "3408" :: "3409" :: "3501" :: "3502" :: "3503" :: "3504" :: "3505" :: Nil) ++
("3506" :: "3507" :: "3508" :: "3509" :: "C301" :: "C302" :: "C304" :: "C305" :: "C306" :: Nil) ++
("C307" :: "C308" :: "C309" :: "C310" :: "C311" :: "C401" :: "C402" :: "C405" :: "C406" :: Nil) ++
("C407" :: "C408" :: "C409" :: "C410" :: "C411" :: "C412" :: "C413" :: "C501" :: "C509" :: Nil) ++
("C510" :: "C513" :: "C514" :: "C515" :: "C606" :: "C614" :: "C615" :: "C616" :: Nil) ++
("0109" :: "0115" :: "0116" :: "0117" :: "0118" :: "0221" :: "0225" :: "0328" :: "0329" :: "0330" :: "0338" :: Nil)
def keyboardTemplate(buttons: Seq[String]) = Json.obj(
"type" -> "buttons",
"buttons" -> buttons
)
def responseTemplate(message: String, buttons: Seq[String]) = Json.obj(
"message" -> Map(
"text" -> message
),
"keyboard" -> keyboardTemplate(buttons)
)
def nowIsApplicable() = {
val time = ZonedDateTime.now(ZoneId.of(ZONEID))
val dow = time.getDayOfWeek.getValue()
val hour = time.getHour()
dow <= 5 && dow >= 1 && hour >= 9 && hour < 17
}
}
开发者ID:yoo-haemin,项目名称:hufs-classroom,代码行数:51,代码来源:Global.scala
示例5: 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
示例6: Signer
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.auth
import java.security.MessageDigest
import java.time.{ZoneOffset, ZonedDateTime}
import java.time.format.DateTimeFormatter
import akka.actor.ActorSystem
import akka.http.scaladsl.model.{HttpHeader, HttpRequest}
import akka.http.scaladsl.model.headers.RawHeader
import akka.stream.ActorMaterializer
object Signer {
private val dateFormatter = DateTimeFormatter.ofPattern("YYYYMMdd'T'HHmmssX")
private val unsignedPlayload = "UNSIGNED-PAYLOAD"
def signedRequest(request: HttpRequest,
key: SigningKey,
date: ZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC)): HttpRequest = {
//there we don't sha content, because we use the source to passthrough the data
val headersToAdd = Vector(RawHeader("x-amz-date", date.format(dateFormatter)),
RawHeader("x-amz-content-sha256", unsignedPlayload))
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 :+ authHeader)
}
private[this] def authorizationHeader(algorithm: String,
key: SigningKey,
requestDate: ZonedDateTime,
canonicalRequest: CanonicalRequest): HttpHeader = {
RawHeader("Authorization", authorizationString(algorithm, key, requestDate, canonicalRequest))
}
private[this] def authorizationString(algorithm: String,
key: SigningKey,
requestDate: ZonedDateTime,
canonicalRequest: CanonicalRequest): String = {
val sign = key.hexEncodedSignature(stringToSign(algorithm, key, requestDate, canonicalRequest).getBytes())
s"$algorithm Credential=${key.credentialString}, SignedHeaders=${canonicalRequest.signedHeaders}, Signature=$sign"
}
def stringToSign(algorithm: String,
signingKey: SigningKey,
requestDate: ZonedDateTime,
canonicalRequest: CanonicalRequest): String = {
val digest = MessageDigest.getInstance("SHA-256")
val hashedRequest = encodeHex(digest.digest(canonicalRequest.canonicalString.getBytes()))
val date = requestDate.format(dateFormatter)
val scope = signingKey.scope.scopeString
s"$algorithm\n$date\n$scope\n$hashedRequest"
}
def Md5(data: String): String = {
val md5 = java.security.MessageDigest.getInstance("MD5")
val byte = data.getBytes("UTF-8")
new sun.misc.BASE64Encoder().encode(md5.digest(byte))
}
}
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:61,代码来源:Signer.scala
示例7: TodoDas
//设置package包名称以及导入依赖的类
package example.db
import java.time.ZonedDateTime
import akka.NotUsed
import akka.stream.scaladsl.Source
import scala.concurrent.ExecutionContext
class TodoDas(todoDao: TodoDao) {
def findById(id: TodoId): Source[Todo, NotUsed] =
Source.fromPublisher(todoDao.resolveAsStream(id))
def findAll: Source[Todo, NotUsed] =
Source.fromPublisher(todoDao.resolveAllAsStream)
def create(todo: Todo)
(implicit ec: ExecutionContext): Source[Unit, NotUsed] =
Source.fromFuture {
todoDao.create(todo)
}
def update(id: TodoId, text: String, updateAt: ZonedDateTime, version: Long)
(implicit ec: ExecutionContext): Source[Unit, NotUsed] =
Source.fromFuture {
todoDao.update(id, text, updateAt, version)
}
def delete(id: TodoId)
(implicit ec: ExecutionContext): Source[Unit, NotUsed] =
Source.single(id).mapAsync(1) { id =>
todoDao.delete(id)
}
}
开发者ID:j5ik2o,项目名称:akka-ddd-cqrs-es-example,代码行数:37,代码来源:TodoDas.scala
示例8: decoder
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.range.datetime
import java.time.{LocalDate, ZonedDateTime, LocalDateTime}
import java.util.Date
import io.getquill.source.jdbc.JdbcSource
import io.gustavoamigo.quill.pgsql.encoding.GenericDecoder
trait Decoders extends GenericDecoder {
this: JdbcSource[_, _] =>
import Formatters._
private val rangePattern = """([0-9\-\+\. :]+)""".r
private def decoder[T](map: String => T) = decode(s => {
val dates = rangePattern.findAllIn(s).toList
(map(dates.head), map(dates.last))
})
implicit val dateTupleDecoder: Decoder[(Date, Date)] = decoder(parseDate)
implicit val localDateTimeTupleDecoder: Decoder[(LocalDateTime, LocalDateTime)] = decoder(parseLocalDateTime)
implicit val zonedDateTimeTupleDecoder: Decoder[(ZonedDateTime, ZonedDateTime)] = decoder(parseZonedDateTime)
implicit val localDateTupleDecoder: Decoder[(LocalDate, LocalDate)] = decoder(parseLocalDate)
}
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:26,代码来源:Decoders.scala
示例9: PersistingAccountGroupSpec
//设置package包名称以及导入依赖的类
package com.gilesc
package mynab
import java.time.LocalDate
import com.gilesc.mynab.account._
import com.gilesc.mynab.category._
import com.gilesc.mynab.transaction._
import com.gilesc.mynab.user._
import com.gilesc.mynab.persistence.account.AccountGroupRepository.CreateContext
import com.gilesc.mynab.persistence.account._
import AccountGroupService.FindByName
import java.time.ZonedDateTime
class PersistingAccountGroupSpec extends TestCase
with MockAccountCreation {
val id = 1L
val validName = "newaccountgroup"
val invalidName = "r"
val time = ZonedDateTime.now()
"Giving the service an AccountName" should "persist the account group" in {
val userId = UserId(id)
val expected = AccountGroup.create(id, validName)
def mockSave(ctx: CreateContext) = Right(AccountGroupId(id))
AccountGroupService.create(mockSave)(userId, validName) should be(Right(expected))
}
it should "find an account group given a proper account name" in {
def mockFind(an: AccountName): Either[AccountGroupPersistenceError, Option[AccountGroupRow]] =
Right(Option(AccountGroupRow(id, an, time, time, None)))
AccountGroupService.find(mockFind)(FindByName(validName)) should be(
Right(Some(AccountGroup.create(1L, validName))))
}
it should "never call the mock function if an invalid account name is provided" in {
val expected = s"$invalidName is not a valid account name"
def mockFind(an: AccountName): Either[AccountGroupPersistenceError, Option[AccountGroupRow]] =
sys.error("Somehow passed the AccountName restriction")
AccountGroupService.find(mockFind)(FindByName(invalidName)) should be(Left(expected))
}
it should "fail gracefully if the database contains an invalid name" in {
val expected = s"n is not a valid account name"
def mockFind(an: AccountName): Either[AccountGroupPersistenceError, Option[AccountGroupRow]] =
Left(InvalidAccountNameLength("n"))
AccountGroupService.find(mockFind)(FindByName(validName)) should be(Left(expected))
}
}
开发者ID:CraigGiles,项目名称:mynab,代码行数:59,代码来源:PersistingAccountGroupSpec.scala
示例10: jwtClaimsSetGen
//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.jwt.generators.nimbus
import java.time.{Duration, ZonedDateTime}
import java.util.Date
import com.fortysevendeg.scalacheck.datetime.GenDateTime._
import com.fortysevendeg.scalacheck.datetime.instances.jdk8._
import com.fortysevendeg.scalacheck.datetime.jdk8.granularity.minutes
import com.nimbusds.jwt.JWTClaimsSet
import org.scalacheck.Gen
trait JWTClaimsSetGen {
def jwtClaimsSetGen(
customClaims: Seq[(String, Any)] = Seq.empty): Gen[JWTClaimsSet] =
for {
issuer <- Gen.alphaStr suchThat (!_.isEmpty)
subject <- Gen.alphaStr suchThat (!_.isEmpty)
now = ZonedDateTime.now
issuedAt <- Gen.const(now).map(t => Date.from(t.toInstant))
expiration <- genDateTimeWithinRange(now.plusMinutes(5),
Duration
.ofMinutes(25))
.map(t => Date.from(t.toInstant))
builder = new JWTClaimsSet.Builder()
.issuer(issuer)
.subject(subject)
.issueTime(issuedAt)
.expirationTime(expiration)
} yield
customClaims
.foldLeft(builder)((b, claim) => b.claim(claim._1, claim._2))
.build()
}
开发者ID:toolsplus,项目名称:atlassian-jwt,代码行数:36,代码来源:JWTClaimsSetGen.scala
示例11: 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
示例12: Value
//设置package包名称以及导入依赖的类
package all_of_imports
import java.time.ZonedDateTime
//noinspection ScalaStyle
package yaml {
trait IValue {
def `type`: String
}
case class Value(`type`: String) extends IValue
case class DatetimeValue(`type`: String, value: ZonedDateTime) extends IValue
import play.api.libs.json._
import play.api.libs.functional.syntax._
import de.zalando.play.controllers.MissingDefaultReads
object BodyReads extends MissingDefaultReads {
implicit val DatetimeValueReads: Reads[DatetimeValue] = (
(JsPath \ "`type`").read[String] and (JsPath \ "value").read[ZonedDateTime]
)(DatetimeValue.apply _)
implicit val ValueReads: Reads[Value] = (
(JsPath \ "`type`").read[String]
).map(Value.apply )
}
import play.api.libs.json._
import play.api.libs.functional.syntax._
import de.zalando.play.controllers.MissingDefaultWrites
object ResponseWrites extends MissingDefaultWrites {
implicit val DatetimeValueWrites: Writes[DatetimeValue] = new Writes[DatetimeValue] {
def writes(ss: DatetimeValue) =
Json.obj(
"`type`" -> ss.`type`,
"value" -> ss.value
)
}
implicit val ValueWrites: Writes[Value] = new Writes[Value] {
def writes(ss: Value) =
Json.obj(
"`type`" -> ss.`type`
)
}
}
}
// should be defined after the package because of the https://issues.scala-lang.org/browse/SI-9922
//noinspection ScalaStyle
package object yaml {
type PostResponses400 = Null
}
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:60,代码来源:all_of_imports_yaml.scala
示例13: CfExp
//设置package包名称以及导入依赖的类
package com.timeout.scalacloudformation
import java.time.{Duration, ZonedDateTime}
import io.circe.Json
trait CfExp[+T]
object CfExp {
type E[+T] = CfExp[T]
trait IsLit[A]
object IsLit {
implicit val stringLit: IsLit[String] = new IsLit[String] {}
implicit val IntLit: IsLit[Int] = new IsLit[Int] {}
implicit val longLit: IsLit[Long] = new IsLit[Long] {}
implicit val doubleLit: IsLit[Double] = new IsLit[Double] {}
implicit val boolLit: IsLit[Boolean] = new IsLit[Boolean] {}
implicit val dateTimeLit: IsLit[ZonedDateTime] = new IsLit[ZonedDateTime] {}
implicit val jsonLit: IsLit[Json] = new IsLit[Json] {}
implicit val durationLit: IsLit[Duration] = new IsLit[Duration] {}
implicit def propertyLit[T <: ResourceProperty]: IsLit[T] = new IsLit[T] {}
implicit def listLit[A: IsLit]: IsLit[List[A]] = new IsLit[List[A]]{}
}
case class Lit[T: IsLit](value: T) extends E[T]
case class ResourceRef(value: Resource) extends E[String]
case class ParameterRef(value: Parameter) extends E[String]
case class PseudoParameterRef(value: PseudoParameter) extends E[String]
case class FnBase64(exp: E[String]) extends E[String]
case class FnAnd(cond1: E[Boolean], cond2: E[Boolean]) extends E[Boolean]
case class FnEquals[T](left: E[T], right: E[T]) extends E[Boolean]
case class FnIf[T](cond: E[Boolean], ifTrue: E[T], ifFalse: E[T]) extends E[T]
case class FnNot(cond: E[Boolean]) extends E[Boolean]
case class FnOr(conds: E[Boolean]*) extends E[Boolean]
}
开发者ID:typeformation,项目名称:typeformation,代码行数:42,代码来源:CfExp.scala
示例14: 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
示例15: Metadata
//设置package包名称以及导入依赖的类
package delorean
import java.nio.file.{Files, Paths}
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter.ofPattern
import delorean.FileOps.getLinesOfFile
/**
* Class for holding metadata information. Basically a POJO.
*/
case class Metadata(pitstop: String, time: ZonedDateTime, rider: String, parents: Array[String], riderLog: String)
object Metadata {
/**
* Creates a Metadata object by parsing the metadata file of a pitstop
* Typical metadata looks like this
* *****
* Time:Mar 12 2017 10:07 PM India Standard Time
* Rider:dperla
* Parent(s):abc123def456:qwe098rty765
* RiderLog:
* A new Rider in town
* *****
* And using that structure, we parse the file to get the required information
*
* @param pitstopHash : Pitstop for which we need Metadata
* @return
*/
def apply(pitstopHash: String): Metadata = {
val metadataFile: String = {
if (Files.exists(Paths.get(INDICATORS_FOLDER + pitstopHash)))
METADATA_FOLDER + getLinesOfFile(INDICATORS_FOLDER + pitstopHash).head
else
METADATA_FOLDER + pitstopHash
}
val metadataFileContent: Seq[String] = getLinesOfFile(metadataFile)
val time: ZonedDateTime = {
ZonedDateTime.parse(metadataFileContent.head.split(":", 2)(1), ofPattern("MMM dd yyyy hh:mm a zzzz"))
}
val rider: String = metadataFileContent(1).split(":", 2)(1)
// parents hashes will be separated by ':'. So, split will split across all those :'s and tail gives us
// everything other than the first one.
val parents: Array[String] = metadataFileContent(2).split(":").tail
val riderLog: String = metadataFileContent.last
new Metadata(pitstopHash, time, rider, parents, riderLog)
}
}
开发者ID:durgaswaroop,项目名称:delorean,代码行数:49,代码来源:Metadata.scala
示例16: LibratoActorStateSpec
//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.monitor.pipeline.metrics.client.librato
import java.time.{ZoneId, ZonedDateTime}
import org.scalatest.{FlatSpec, Matchers}
class LibratoActorStateSpec extends FlatSpec with Matchers {
val now = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC"))
behavior of "LibratoActorState"
it should "keep track of gauge metrics" in {
val source1 = "source1"
val source2 = "source2"
val metric1 = "metric1"
val metric2 = "metric2"
val state = LibratoActorState()
.addGaugeMetric(source1, metric1, 1, now)
.addGaugeMetric(source2, metric1, 1, now)
.addGaugeMetric(source1, metric2, 1, now)
state.gaugeMetrics should be(
Vector(LibratoMetric(source1, metric1, 1, now),
LibratoMetric(source2, metric1, 1, now),
LibratoMetric(source1, metric2, 1, now)))
}
it should "keep track of counter metrics" in {
val source1 = "source1"
val source2 = "source2"
val metric1 = "metric1"
val metric2 = "metric2"
val state = LibratoActorState()
.addCounterMetric(source1, metric1, 1, now)
.addCounterMetric(source2, metric1, 1, now)
.addCounterMetric(source1, metric2, 1, now)
state.counterMetrics should be(
Vector(LibratoMetric(source1, metric1, 1, now),
LibratoMetric(source2, metric1, 1, now),
LibratoMetric(source1, metric2, 1, now)))
}
it should "start with empty metrics" in {
val state = LibratoActorState()
state.counterMetrics shouldBe empty
state.gaugeMetrics shouldBe empty
}
}
开发者ID:ovotech,项目名称:comms-monitor-service,代码行数:56,代码来源:LibratoActorStateSpec.scala
示例17: instancia
//设置package包名称以及导入依赖的类
package controllers
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import akka.stream.scaladsl.Source
import play.api.libs.json._
import scala.concurrent.duration._
trait ScalaTicker {
object instancia {
var st:SimulacionTrenes = new SimulacionTrenes
st.simular(false)
}
def reiniciarSimulacion(): Unit = {
instancia.st = new SimulacionTrenes;
instancia.st.simular(true)
}
def stringSource: Source[String, _] = {
val tickSource = Source.tick(0 millis, 1000 millis, "TICK")
val s = tickSource.map((tick) => instancia.st.imprimir())
s
}
def jsonSource: Source[JsValue, _] = {
val tickSource = Source.tick(0 millis, 100 millis, "TICK")
val s = tickSource.map((tick) => Json.toJson(ZonedDateTime.now))
s
}
}
开发者ID:juancamilogaviriaacosta,项目名称:proyecto-transmimetro-JuanGaviria-MauricioMontano,代码行数:36,代码来源:ScalaTicker.scala
示例18: SpecSpec
//设置package包名称以及导入依赖的类
package io.defn.crontab
import java.time.{ZoneId, ZonedDateTime}
import org.scalatest._
class SpecSpec extends FunSpec with Matchers {
describe("Spec") {
describe("dateTimes") {
it("should return a stream of upcoming ZonedDateTimes for a spec") {
val start = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC"))
val Right(spec) = Spec.parse("10-15 * * * Sun")
val dateTimes = spec.dateTimes(start).take(10).toList
dateTimes shouldEqual List(
start.withHour(0).withMinute(10),
start.withHour(0).withMinute(11),
start.withHour(0).withMinute(12),
start.withHour(0).withMinute(13),
start.withHour(0).withMinute(14),
start.withHour(0).withMinute(15),
start.withHour(1).withMinute(10),
start.withHour(1).withMinute(11),
start.withHour(1).withMinute(12),
start.withHour(1).withMinute(13)
)
}
}
}
}
开发者ID:Bogdanp,项目名称:crontab,代码行数:32,代码来源:SpecSpec.scala
示例19: QuoteParser
//设置package包名称以及导入依赖的类
package openquant.yahoofinance.impl
import java.time.format.DateTimeFormatter
import java.time.{LocalDate, ZoneId, ZonedDateTime}
import com.github.tototoshi.csv._
import openquant.yahoofinance.Quote
import scala.io.Source
class QuoteParser {
private[this] val df = DateTimeFormatter.ofPattern("yyyy-MM-dd")
private[this] val zoneId = ZoneId.of("America/New_York")
def parse(content: String): Vector[Quote] = {
val csvReader = CSVReader.open(Source.fromString(content))
val quotes: Vector[Quote] = csvReader.toStream.drop(1).map { fields ?
parseCSVLine(fields.toVector)
}.toVector
quotes
}
private def parseCSVLine(field: Vector[String]): Quote = {
require(field.length >= 7)
Quote(
parseDate(field(0)),
BigDecimal(field(1)),
BigDecimal(field(4)),
BigDecimal(field(2)),
BigDecimal(field(3)),
BigDecimal(field(5)),
BigDecimal(field(6))
)
}
private def parseDate(date: String): ZonedDateTime = {
LocalDate.parse(date, df).atStartOfDay().atZone(zoneId)
}
}
object QuoteParser {
def apply() = new QuoteParser
}
开发者ID:openquant,项目名称:YahooFinanceScala,代码行数:45,代码来源:QuoteParser.scala
示例20: YahooFinanceSpec
//设置package包名称以及导入依赖的类
package openquant.yahoofinance
import java.time.ZonedDateTime
import akka.actor.ActorSystem
import akka.testkit.TestKit
import org.specs2.matcher.{FutureMatchers, Matchers}
import org.specs2.mutable._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
class YahooFinanceSpec extends TestKit(ActorSystem()) with SpecificationLike with Matchers with Logging {
"get quotes" in {
val yahooFinance = new YahooFinance()
val res = Await.result(yahooFinance.quotes("MSFT", Some(ZonedDateTime.now().minusDays(5))), Duration.Inf)
res.length must be_>=(3)
res.length must be_<=(5)
}
"get full history" in {
val yahooFinance = new YahooFinance()
val res = Await.result(yahooFinance.quotes("MSFT"), Duration.Inf)
res.length must be_>=(1000)
}
"non-existent symbol" in {
val yahooFinance = new YahooFinance()
Await.result(yahooFinance.quotes("qwertyasdf"), Duration.Inf) must throwA[RuntimeException]
}
"invalid fundamentals" in {
val yahooFinance = new YahooFinance()
val invalids = Await.result(yahooFinance.fundamentals(Vector("qwertyasdf")), Duration.Inf)
invalids must have size (1)
invalids.head.looksValid must beFalse
}
"valid fundamentals" in {
val yahooFinance = new YahooFinance()
val syms =
|
请发表评论