java.time.ZonedDateTime Scala Examples

The following examples show how to use java.time.ZonedDateTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: FundamentalsParser.scala    From YahooFinanceScala   with MIT License 6 votes vote down vote up
package openquant.yahoofinance.impl

import java.time.format.DateTimeFormatter
import java.time.{LocalDate, ZoneId, ZonedDateTime}

import com.github.tototoshi.csv._
import openquant.yahoofinance.Fundamentals

import scala.io.Source


object FundamentalsParser extends Function1[String, Vector[Fundamentals]] {
  def apply(content: String): Vector[Fundamentals] = {
    val csvReader = CSVReader.open(Source.fromString(content))
    val fundamentals: Vector[Fundamentals] = csvReader.toStream.map { fields ⇒
      parseCSVLine(fields.toVector)
    }.toVector
    fundamentals
  }

  private def parseCSVLine(field: Vector[String]): Fundamentals = {
    require(field.length >= 2, "number of fields")
    val name = field(1)
    if (name == "N/A")
      Fundamentals(
        looksValid = false,
        symbol = field(0),
        name = name
      )
    else
      Fundamentals(
        looksValid = true,
        symbol = field(0),
        name = name
      )
  }
} 
Example 2
Source File: UserAccountRepositoryBySlickImplSpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.slick

import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.example.model._
import com.github.j5ik2o.dddbase.example.repository.{ IdGenerator, SpecSupport, UserAccountRepository }
import com.github.j5ik2o.dddbase.example.repository.util.{ FlywayWithMySQLSpecSupport, Slick3SpecSupport }
import monix.execution.Scheduler.Implicits.global
import org.scalatest.{ FreeSpecLike, Matchers }

class UserAccountRepositoryBySlickImplSpec
    extends FreeSpecLike
    with FlywayWithMySQLSpecSupport
    with Slick3SpecSupport
    with Matchers
    with SpecSupport {

  override val tables: Seq[String] = Seq("user_account")

  val userAccount = UserAccount(
    id = UserAccountId(IdGenerator.generateIdValue),
    status = Status.Active,
    emailAddress = EmailAddress("[email protected]"),
    password = HashedPassword("aaa"),
    firstName = "Junichi",
    lastName = "Kato",
    createdAt = ZonedDateTime.now,
    updatedAt = None
  )

  val userAccounts = for (idx <- 1L to 10L)
    yield
      UserAccount(
        id = UserAccountId(IdGenerator.generateIdValue),
        status = Status.Active,
        emailAddress = EmailAddress(s"user${idx}@gmail.com"),
        password = HashedPassword("aaa"),
        firstName = "Junichi",
        lastName = "Kato",
        createdAt = ZonedDateTime.now,
        updatedAt = None
      )

  "UserAccountRepositoryBySlickImpl" - {
    "store" in {
      val repository = new UserAccountRepositoryBySlickImpl(dbConfig.profile, dbConfig.db)
      val result = (for {
        _ <- repository.store(userAccount)
        r <- repository.resolveById(userAccount.id)
      } yield r).runToFuture.futureValue

      result shouldBe userAccount
    }
    "storeMulti" in {
      val repository = new UserAccountRepositoryBySlickImpl(dbConfig.profile, dbConfig.db)
      val result = (for {
        _ <- repository.storeMulti(userAccounts)
        r <- repository.resolveMulti(userAccounts.map(_.id))
      } yield r).runToFuture.futureValue

      sameAs(result, userAccounts) shouldBe true
    }
  }
} 
Example 3
Source File: Merge.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.data
package derived

import java.time.{Instant, LocalDate, LocalDateTime, ZonedDateTime}

import cats.kernel.Semigroup
import magnolia.{CaseClass, Magnolia, SealedTrait}
import simulacrum.typeclass
import derevo.Derivation

@typeclass trait Merge[A] {
  def merge(a: A, b: A): A
}

trait MergeInstances1 {
  type Typeclass[A] = Merge[A]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] =
    (a, b) => caseClass.construct(p => p.typeclass.merge(p.dereference(a), p.dereference(b)))

  def dispatch[T](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] =
    (a, b) => sealedTrait.dispatch(a) { h => if (h.cast.isDefinedAt(b)) h.typeclass.merge(h.cast(a), h.cast(b)) else a }

  implicit def instance[A]: Merge[A] = macro Magnolia.gen[A]
}

object Merge extends Derivation[Merge] with MergeInstances1 {
  implicit def optionInstance[A](implicit m: Merge[A]): Merge[Option[A]] =
    (ao, bo) => ao.fold(bo)(a => bo.fold(ao)(b => Some(m.merge(a, b))))

  implicit def primitiveInstance[A: Primitive]: Merge[A] = (a: A, _: A) => a

  sealed class Primitive[A]
  final implicit object primitiveByte          extends Primitive[Byte]
  final implicit object primitiveShort         extends Primitive[Short]
  final implicit object primitiveInt           extends Primitive[Int]
  final implicit object primitiveLong          extends Primitive[Long]
  final implicit object primitiveChar          extends Primitive[Char]
  final implicit object primitiveFloat         extends Primitive[Float]
  final implicit object primitiveDouble        extends Primitive[Double]
  final implicit object primitiveUnit          extends Primitive[Unit]
  final implicit object primitiveBigDecimal    extends Primitive[BigDecimal]
  final implicit object primitiveBigInt        extends Primitive[BigInt]
  final implicit object primitiveLocalDateTime extends Primitive[LocalDateTime]
  final implicit object primitiveZonedDateTime extends Primitive[ZonedDateTime]
  final implicit object primitiveLocalDate     extends Primitive[LocalDate]
  final implicit object primitiveInstant       extends Primitive[Instant]
  final implicit object primitiveString        extends Primitive[String]
}

object Merged {
  trait OpaqueTag extends Any
  type Base = Any { type MergedOpaque }

  type Mer[A] <: Base with OpaqueTag

  def apply[A](value: A): Mer[A] = value.asInstanceOf[Mer[A]]

  implicit final class MergedOps[A](private val mer: Mer[A]) extends AnyVal {
    def value: A = mer.asInstanceOf[A]
  }

  implicit def mergedSemigroup[A: Merge]: Semigroup[Merged[A]] =
    (x, y) => apply(Merge[A].merge(x.value, y.value))
} 
Example 4
Source File: zoneddatetime.scala    From cats-time   with MIT License 5 votes vote down vote up
package io.chrisdavenport.cats.time.instances

import cats._
import cats.implicits._
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME

trait zoneddatetime {

  final def showZonedDateTime(formatter: DateTimeFormatter): Show[ZonedDateTime] =
    Show[String].contramap(_.format(formatter))

  implicit final val zoneddatetimeInstances = 
    new Hash[ZonedDateTime] with Order[ZonedDateTime] with Show[ZonedDateTime]{
      override def hash(x: ZonedDateTime): Int = x.hashCode
      override def compare(x: ZonedDateTime, y: ZonedDateTime): Int = x.compareTo(y)
      override def show(x: ZonedDateTime): String = x.format(ISO_ZONED_DATE_TIME)
    }
}

object zoneddatetime extends zoneddatetime 
Example 5
Source File: CustomScalars.scala    From graphql-gateway   with Apache License 2.0 5 votes vote down vote up
package sangria.gateway.schema

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

import sangria.schema._
import sangria.ast
import sangria.validation.ValueCoercionViolation

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

object CustomScalars {
  implicit val DateTimeType = ScalarType[ZonedDateTime]("DateTime",
    description = Some("DateTime is a scalar value that represents an ISO8601 formatted date and time."),
    coerceOutput = (date, _) ⇒ DateTimeFormatter.ISO_INSTANT.format(date),
    coerceUserInput = {
      case s: String ⇒ parseDateTime(s) match {
        case Success(date) ⇒ Right(date)
        case Failure(_) ⇒ Left(DateCoercionViolation)
      }
      case _ ⇒ Left(DateCoercionViolation)
    },
    coerceInput = {
      case ast.StringValue(s, _, _, _, _) ⇒ parseDateTime(s) match {
        case Success(date) ⇒ Right(date)
        case Failure(_) ⇒ Left(DateCoercionViolation)
      }
      case _ ⇒ Left(DateCoercionViolation)
    })

  def parseDateTime(s: String) = Try(DateTimeFormatter.ISO_ZONED_DATE_TIME.parse(s).asInstanceOf[ZonedDateTime])

  case object DateCoercionViolation extends ValueCoercionViolation("Date value expected")
} 
Example 6
Source File: Encoders.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill.context.async

import java.time.{ LocalDate, LocalDateTime, LocalTime, OffsetDateTime, ZoneId, ZonedDateTime }
import java.util.Date

import org.joda.time.{ DateTime => JodaDateTime, DateTimeZone => JodaDateTimeZone, LocalTime => JodaLocalTime, LocalDate => JodaLocalDate, LocalDateTime => JodaLocalDateTime }

trait Encoders {
  this: AsyncContext[_, _, _] =>

  type Encoder[T] = AsyncEncoder[T]

  type EncoderSqlType = SqlTypes.SqlTypes

  case class AsyncEncoder[T](sqlType: DecoderSqlType)(implicit encoder: BaseEncoder[T])
    extends BaseEncoder[T] {
    override def apply(index: Index, value: T, row: PrepareRow) =
      encoder.apply(index, value, row)
  }

  def encoder[T](sqlType: DecoderSqlType): Encoder[T] =
    encoder(identity[T], sqlType)

  def encoder[T](f: T => Any, sqlType: DecoderSqlType): Encoder[T] =
    AsyncEncoder[T](sqlType)(new BaseEncoder[T] {
      def apply(index: Index, value: T, row: PrepareRow) =
        row :+ f(value)
    })

  implicit def mappedEncoder[I, O](implicit mapped: MappedEncoding[I, O], e: Encoder[O]): Encoder[I] =
    AsyncEncoder(e.sqlType)(new BaseEncoder[I] {
      def apply(index: Index, value: I, row: PrepareRow) =
        e(index, mapped.f(value), row)
    })

  implicit def optionEncoder[T](implicit d: Encoder[T]): Encoder[Option[T]] =
    AsyncEncoder(d.sqlType)(new BaseEncoder[Option[T]] {
      def apply(index: Index, value: Option[T], row: PrepareRow) = {
        value match {
          case None    => nullEncoder(index, null, row)
          case Some(v) => d(index, v, row)
        }
      }
    })

  private[this] val nullEncoder: Encoder[Null] = encoder[Null](SqlTypes.NULL)

  implicit val stringEncoder: Encoder[String] = encoder[String](SqlTypes.VARCHAR)
  implicit val bigDecimalEncoder: Encoder[BigDecimal] = encoder[BigDecimal](SqlTypes.REAL)
  implicit val booleanEncoder: Encoder[Boolean] = encoder[Boolean](SqlTypes.BOOLEAN)
  implicit val byteEncoder: Encoder[Byte] = encoder[Byte](SqlTypes.TINYINT)
  implicit val shortEncoder: Encoder[Short] = encoder[Short](SqlTypes.SMALLINT)
  implicit val intEncoder: Encoder[Int] = encoder[Int](SqlTypes.INTEGER)
  implicit val longEncoder: Encoder[Long] = encoder[Long](SqlTypes.BIGINT)
  implicit val floatEncoder: Encoder[Float] = encoder[Float](SqlTypes.FLOAT)
  implicit val doubleEncoder: Encoder[Double] = encoder[Double](SqlTypes.DOUBLE)
  implicit val byteArrayEncoder: Encoder[Array[Byte]] = encoder[Array[Byte]](SqlTypes.VARBINARY)
  implicit val jodaDateTimeEncoder: Encoder[JodaDateTime] = encoder[JodaDateTime](SqlTypes.TIMESTAMP)
  implicit val jodaLocalDateEncoder: Encoder[JodaLocalDate] = encoder[JodaLocalDate](SqlTypes.DATE)
  implicit val jodaLocalDateTimeEncoder: Encoder[JodaLocalDateTime] = encoder[JodaLocalDateTime](SqlTypes.TIMESTAMP)
  implicit val dateEncoder: Encoder[Date] = encoder[Date]((d: Date) => new JodaLocalDateTime(d), SqlTypes.TIMESTAMP)

  implicit val encodeZonedDateTime: MappedEncoding[ZonedDateTime, JodaDateTime] =
    MappedEncoding(zdt => new JodaDateTime(zdt.toInstant.toEpochMilli, JodaDateTimeZone.forID(zdt.getZone.getId)))

  implicit val encodeOffsetDateTime: MappedEncoding[OffsetDateTime, JodaDateTime] =
    MappedEncoding(odt => new JodaDateTime(odt.toInstant.toEpochMilli, JodaDateTimeZone.forID(odt.getOffset.getId)))

  implicit val encodeLocalDate: MappedEncoding[LocalDate, JodaLocalDate] =
    MappedEncoding(ld => new JodaLocalDate(ld.getYear, ld.getMonthValue, ld.getDayOfMonth))

  implicit val encodeLocalTime: MappedEncoding[LocalTime, JodaLocalTime] =
    MappedEncoding(lt => new JodaLocalTime(lt.getHour, lt.getMinute, lt.getSecond))

  implicit val encodeLocalDateTime: MappedEncoding[LocalDateTime, JodaLocalDateTime] =
    MappedEncoding(ldt => new JodaLocalDateTime(ldt.atZone(ZoneId.systemDefault()).toInstant.toEpochMilli))

  implicit val localDateEncoder: Encoder[LocalDate] = mappedEncoder(encodeLocalDate, jodaLocalDateEncoder)
} 
Example 7
Source File: Encodings.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill.context.cassandra.encoding

import java.time.{ Instant, LocalDate, ZonedDateTime, ZoneId }
import java.util.Date

import com.datastax.driver.core.{ LocalDate => CasLocalDate }
import io.getquill.context.cassandra.CassandraContext

trait Encodings extends CassandraMapperConversions with CassandraTypes {
  this: CassandraContext[_] =>

  protected val zoneId = ZoneId.systemDefault

  implicit val encodeJava8LocalDate: MappedEncoding[LocalDate, CasLocalDate] = MappedEncoding(ld =>
    CasLocalDate.fromYearMonthDay(ld.getYear, ld.getMonthValue, ld.getDayOfMonth))
  implicit val decodeJava8LocalDate: MappedEncoding[CasLocalDate, LocalDate] = MappedEncoding(ld =>
    LocalDate.of(ld.getYear, ld.getMonth, ld.getDay))

  implicit val encodeJava8Instant: MappedEncoding[Instant, Date] = MappedEncoding(Date.from)
  implicit val decodeJava8Instant: MappedEncoding[Date, Instant] = MappedEncoding(_.toInstant)

  implicit val encodeJava8ZonedDateTime: MappedEncoding[ZonedDateTime, Date] = MappedEncoding(zdt =>
    Date.from(zdt.toInstant))
  implicit val decodeJava8ZonedDateTime: MappedEncoding[Date, ZonedDateTime] = MappedEncoding(d =>
    ZonedDateTime.ofInstant(d.toInstant, zoneId))
} 
Example 8
Source File: Encoders.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill.context.jasync

import java.time.{ LocalDate, LocalDateTime, LocalTime, OffsetDateTime, ZoneId, ZonedDateTime }
import java.util.Date

import org.joda.time.{ DateTime => JodaDateTime, DateTimeZone => JodaDateTimeZone, LocalTime => JodaLocalTime, LocalDate => JodaLocalDate, LocalDateTime => JodaLocalDateTime }

trait Encoders {
  this: JAsyncContext[_, _, _] =>

  type Encoder[T] = AsyncEncoder[T]

  type EncoderSqlType = SqlTypes.SqlTypes

  case class AsyncEncoder[T](sqlType: DecoderSqlType)(implicit encoder: BaseEncoder[T])
    extends BaseEncoder[T] {
    override def apply(index: Index, value: T, row: PrepareRow) =
      encoder.apply(index, value, row)
  }

  def encoder[T](sqlType: DecoderSqlType): Encoder[T] =
    encoder(identity[T], sqlType)

  def encoder[T](f: T => Any, sqlType: DecoderSqlType): Encoder[T] =
    AsyncEncoder[T](sqlType)(new BaseEncoder[T] {
      def apply(index: Index, value: T, row: PrepareRow) =
        row :+ f(value)
    })

  implicit def mappedEncoder[I, O](implicit mapped: MappedEncoding[I, O], e: Encoder[O]): Encoder[I] =
    AsyncEncoder(e.sqlType)(new BaseEncoder[I] {
      def apply(index: Index, value: I, row: PrepareRow) =
        e(index, mapped.f(value), row)
    })

  implicit def optionEncoder[T](implicit d: Encoder[T]): Encoder[Option[T]] =
    AsyncEncoder(d.sqlType)(new BaseEncoder[Option[T]] {
      def apply(index: Index, value: Option[T], row: PrepareRow) = {
        value match {
          case None    => nullEncoder(index, null, row)
          case Some(v) => d(index, v, row)
        }
      }
    })

  private[this] val nullEncoder: Encoder[Null] = encoder[Null](SqlTypes.NULL)

  implicit val stringEncoder: Encoder[String] = encoder[String](SqlTypes.VARCHAR)
  implicit val bigDecimalEncoder: Encoder[BigDecimal] = encoder[BigDecimal]((bd: BigDecimal) => bd.bigDecimal, SqlTypes.REAL)
  implicit val booleanEncoder: Encoder[Boolean] = encoder[Boolean](SqlTypes.BOOLEAN)
  implicit val byteEncoder: Encoder[Byte] = encoder[Byte](SqlTypes.TINYINT)
  implicit val shortEncoder: Encoder[Short] = encoder[Short](SqlTypes.SMALLINT)
  implicit val intEncoder: Encoder[Int] = encoder[Int](SqlTypes.INTEGER)
  implicit val longEncoder: Encoder[Long] = encoder[Long](SqlTypes.BIGINT)
  implicit val floatEncoder: Encoder[Float] = encoder[Float](SqlTypes.FLOAT)
  implicit val doubleEncoder: Encoder[Double] = encoder[Double](SqlTypes.DOUBLE)
  implicit val byteArrayEncoder: Encoder[Array[Byte]] = encoder[Array[Byte]](SqlTypes.VARBINARY)
  implicit val jodaDateTimeEncoder: Encoder[JodaDateTime] = encoder[JodaDateTime](SqlTypes.TIMESTAMP)
  implicit val jodaLocalDateEncoder: Encoder[JodaLocalDate] = encoder[JodaLocalDate](SqlTypes.DATE)
  implicit val jodaLocalDateTimeEncoder: Encoder[JodaLocalDateTime] = encoder[JodaLocalDateTime](SqlTypes.TIMESTAMP)
  implicit val dateEncoder: Encoder[Date] = encoder[Date]((d: Date) => new JodaLocalDateTime(d), SqlTypes.TIMESTAMP)

  implicit val encodeZonedDateTime: MappedEncoding[ZonedDateTime, JodaDateTime] =
    MappedEncoding(zdt => new JodaDateTime(zdt.toInstant.toEpochMilli, JodaDateTimeZone.forID(zdt.getZone.getId)))

  implicit val encodeOffsetDateTime: MappedEncoding[OffsetDateTime, JodaDateTime] =
    MappedEncoding(odt => new JodaDateTime(odt.toInstant.toEpochMilli, JodaDateTimeZone.forID(odt.getOffset.getId)))

  implicit val encodeLocalDate: MappedEncoding[LocalDate, JodaLocalDate] =
    MappedEncoding(ld => new JodaLocalDate(ld.getYear, ld.getMonthValue, ld.getDayOfMonth))

  implicit val encodeLocalTime: MappedEncoding[LocalTime, JodaLocalTime] =
    MappedEncoding(lt => new JodaLocalTime(lt.getHour, lt.getMinute, lt.getSecond))

  implicit val encodeLocalDateTime: MappedEncoding[LocalDateTime, JodaLocalDateTime] =
    MappedEncoding(ldt => new JodaLocalDateTime(ldt.atZone(ZoneId.systemDefault()).toInstant.toEpochMilli))

  implicit val localDateEncoder: Encoder[LocalDate] = mappedEncoder(encodeLocalDate, jodaLocalDateEncoder)
} 
Example 9
Source File: SlickDaoSupport.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.slick

import java.time.{ Instant, ZoneId, ZonedDateTime }

trait SlickDaoSupport {

  val profile: slick.jdbc.JdbcProfile

  import profile.api._

  implicit val zonedDateTimeColumnType =
    MappedColumnType.base[ZonedDateTime, java.sql.Timestamp](
      { zdt =>
        new java.sql.Timestamp(zdt.toInstant.toEpochMilli)
      }, { ts =>
        val instant = Instant.ofEpochMilli(ts.getTime)
        ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
      }
    )

  trait Record

  trait SoftDeletableRecord extends Record {
    val status: String
  }

  abstract class TableBase[T](_tableTag: Tag, _tableName: String, _schemaName: Option[String] = None)
      extends Table[T](_tableTag, _schemaName, _tableName)

  trait SoftDeletableTableSupport[T] { this: TableBase[T] =>
    def status: Rep[String]
  }
} 
Example 10
Source File: UserAccountRepositoryByFreeSpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.free

import java.time.ZonedDateTime

import cats.free.Free
import com.github.j5ik2o.dddbase.example.model._
import com.github.j5ik2o.dddbase.example.repository.{ IdGenerator, SpecSupport, UserAccountRepository }
import com.github.j5ik2o.dddbase.example.repository.util.{ FlywayWithMySQLSpecSupport, SkinnySpecSupport }
import monix.execution.Scheduler.Implicits.global
import org.scalatest.{ FreeSpecLike, Matchers }
import scalikejdbc.AutoSession

class UserAccountRepositoryByFreeSpec
    extends FreeSpecLike
    with FlywayWithMySQLSpecSupport
    with SkinnySpecSupport
    with Matchers
    with SpecSupport {

  override val tables: Seq[String] = Seq("user_account")

  val userAccount = UserAccount(
    id = UserAccountId(IdGenerator.generateIdValue),
    status = Status.Active,
    emailAddress = EmailAddress("[email protected]"),
    password = HashedPassword("aaa"),
    firstName = "Junichi",
    lastName = "Kato",
    createdAt = ZonedDateTime.now,
    updatedAt = None
  )

  val userAccounts = for (idx <- 1L to 10L)
    yield
      UserAccount(
        id = UserAccountId(IdGenerator.generateIdValue),
        status = Status.Active,
        emailAddress = EmailAddress(s"user${idx}@gmail.com"),
        password = HashedPassword("aaa"),
        firstName = "Junichi",
        lastName = "Kato",
        createdAt = ZonedDateTime.now,
        updatedAt = None
      )

  "UserAccountRepositoryByFree" - {
    "store" in {
      val program: Free[UserRepositoryDSL, UserAccount] = for {
        _      <- UserAccountRepositoryByFree.store(userAccount)
        result <- UserAccountRepositoryByFree.resolveById(userAccount.id)
      } yield result
      val skinny     = UserAccountRepository.bySkinny
      val evalResult = UserAccountRepositoryByFree.evaluate(skinny)(program)
      val result     = evalResult.run(AutoSession).runToFuture.futureValue
      result shouldBe userAccount
    }
  }
} 
Example 11
Source File: UserMessageRepositoryBySkinnyImplSpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.skinny
import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.example.model.{ Status, UserMessage, UserMessageId }
import com.github.j5ik2o.dddbase.example.repository.{ IdGenerator, SpecSupport }
import com.github.j5ik2o.dddbase.example.repository.util.{ FlywayWithMySQLSpecSupport, SkinnySpecSupport }
import monix.execution.Scheduler.Implicits.global
import org.scalatest.{ FreeSpecLike, Matchers }
import scalikejdbc.AutoSession

class UserMessageRepositoryBySkinnyImplSpec
    extends FreeSpecLike
    with FlywayWithMySQLSpecSupport
    with SkinnySpecSupport
    with Matchers
    with SpecSupport {
  override val tables: Seq[String] = Seq("user_message")

  val userMessage = UserMessage(
    id = UserMessageId(IdGenerator.generateIdValue, IdGenerator.generateIdValue),
    status = Status.Active,
    message = "ABC",
    createdAt = ZonedDateTime.now(),
    updatedAt = None
  )

  val userMessages = for (idx <- 1L to 10L)
    yield
      UserMessage(
        id = UserMessageId(IdGenerator.generateIdValue, IdGenerator.generateIdValue),
        status = Status.Active,
        message = s"ABC${idx}",
        createdAt = ZonedDateTime.now(),
        updatedAt = None
      )
  val repository = new UserMessageRepositoryBySkinnyImpl

  "UserMessageRepositoryBySkinnyImpl" - {
    "store" in {
      val result = (for {
        _ <- repository.store(userMessage)
        r <- repository.resolveById(userMessage.id)
      } yield r).run(AutoSession).runToFuture.futureValue

      result shouldBe userMessage
    }
    "storeMulti" in {
      val result = (for {
        _ <- repository.storeMulti(userMessages)
        r <- repository.resolveMulti(userMessages.map(_.id))
      } yield r).run(AutoSession).runToFuture.futureValue

      sameAs(result, userMessages) shouldBe true
    }
  }
} 
Example 12
Source File: UserAccountRepositoryBySkinnyImplSpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.skinny

import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.example.model._
import com.github.j5ik2o.dddbase.example.repository.{ IdGenerator, SpecSupport }
import com.github.j5ik2o.dddbase.example.repository.util.{ FlywayWithMySQLSpecSupport, SkinnySpecSupport }
import monix.execution.Scheduler.Implicits.global
import org.scalatest.{ FreeSpecLike, Matchers }
import scalikejdbc.AutoSession

class UserAccountRepositoryBySkinnyImplSpec
    extends FreeSpecLike
    with FlywayWithMySQLSpecSupport
    with SkinnySpecSupport
    with Matchers
    with SpecSupport {

  val repository                   = new UserAccountRepositoryBySkinnyImpl
  override val tables: Seq[String] = Seq("user_account")

  val userAccount = UserAccount(
    id = UserAccountId(IdGenerator.generateIdValue),
    status = Status.Active,
    emailAddress = EmailAddress("[email protected]"),
    password = HashedPassword("aaa"),
    firstName = "Junichi",
    lastName = "Kato",
    createdAt = ZonedDateTime.now,
    updatedAt = None
  )

  val userAccounts = for (idx <- 1L to 10L)
    yield
      UserAccount(
        id = UserAccountId(IdGenerator.generateIdValue),
        status = Status.Active,
        emailAddress = EmailAddress(s"user${idx}@gmail.com"),
        password = HashedPassword("aaa"),
        firstName = "Junichi",
        lastName = "Kato",
        createdAt = ZonedDateTime.now,
        updatedAt = None
      )

  "UserAccountRepositoryBySkinny" - {
    "store" in {
      val result = (for {
        _ <- repository.store(userAccount)
        r <- repository.resolveById(userAccount.id)
      } yield r).run(AutoSession).runToFuture.futureValue

      result shouldBe userAccount
    }
    "storeMulti" in {
      val result = (for {
        _ <- repository.storeMulti(userAccounts)
        r <- repository.resolveMulti(userAccounts.map(_.id))
      } yield r).run(AutoSession).runToFuture.futureValue

      sameAs(result, userAccounts) shouldBe true
    }

  }

} 
Example 13
Source File: AirframeSpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.airframe

import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.example.model._
import com.github.j5ik2o.dddbase.example.repository.util.{ FlywayWithMySQLSpecSupport, SkinnySpecSupport }
import com.github.j5ik2o.dddbase.example.repository.{ BySkinny, IdGenerator, UserAccountRepository }
import monix.execution.Scheduler.Implicits.global
import org.scalatest.{ FreeSpecLike, Matchers }
import scalikejdbc.AutoSession
import wvlet.airframe._

class AirframeSpec extends FreeSpecLike with FlywayWithMySQLSpecSupport with SkinnySpecSupport with Matchers {

  override val tables: Seq[String] = Seq("user_account")

  val design = newDesign.bind[UserAccountRepository[BySkinny]].toInstance(UserAccountRepository.bySkinny)

  val userAccount = UserAccount(
    id = UserAccountId(IdGenerator.generateIdValue),
    status = Status.Active,
    emailAddress = EmailAddress("[email protected]"),
    password = HashedPassword("aaa"),
    firstName = "Junichi",
    lastName = "Kato",
    createdAt = ZonedDateTime.now,
    updatedAt = None
  )

  "Airframe" - {
    "store and resolveById" in {
      design.withSession { session =>
        val repository = session.build[UserAccountRepository[BySkinny]]
        val result = (for {
          _ <- repository.store(userAccount)
          r <- repository.resolveById(userAccount.id)
        } yield r).run(AutoSession).runToFuture.futureValue
        result shouldBe userAccount
      }
    }
  }

} 
Example 14
Source File: Implicits.scala    From scala-cass   with MIT License 5 votes vote down vote up
package com.weather.scalacass.jdk8

import com.weather.scalacass.{ CassFormatDecoder, CassFormatEncoder }
import com.weather.scalacass.CassFormatDecoderVersionSpecific.codecCassFormatDecoder
import CassFormatEncoder.sameTypeCassFormatEncoder
import java.time.{ Instant, LocalDate, LocalTime, ZonedDateTime }

import com.datastax.driver.core.{ Cluster, DataType }
import com.google.common.reflect.TypeToken

object Implicits {
  implicit val timeEncoder: CassFormatEncoder[LocalTime] = sameTypeCassFormatEncoder(DataType.time)
  implicit val timeDecoder: CassFormatDecoder[LocalTime] = codecCassFormatDecoder(TypeToken.of(classOf[LocalTime]))

  implicit val dateEncoder: CassFormatEncoder[LocalDate] = sameTypeCassFormatEncoder(DataType.date)
  implicit val dateDecoder: CassFormatDecoder[LocalDate] = codecCassFormatDecoder(TypeToken.of(classOf[LocalDate]))

  implicit val instantEncoder: CassFormatEncoder[Instant] = sameTypeCassFormatEncoder(DataType.timestamp)
  implicit val instantDecoder: CassFormatDecoder[Instant] = codecCassFormatDecoder(TypeToken.of(classOf[Instant]))

  implicit def zonedDateTimeEncoder(implicit cluster: Cluster): CassFormatEncoder[ZonedDateTime] =
    sameTypeCassFormatEncoder(cluster.getMetadata.newTupleType(DataType.timestamp, DataType.varchar))
  implicit val zonedDateTimeDecoder: CassFormatDecoder[ZonedDateTime] = codecCassFormatDecoder(TypeToken.of(classOf[ZonedDateTime]))
} 
Example 15
Source File: UserMessageRepositoryBySlickImplSpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.slick

import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.example.model.{ Status, UserMessage, UserMessageId }
import com.github.j5ik2o.dddbase.example.repository.{ IdGenerator, SpecSupport }
import com.github.j5ik2o.dddbase.example.repository.util.{ FlywayWithMySQLSpecSupport, Slick3SpecSupport }
import monix.execution.Scheduler.Implicits.global
import org.scalatest.{ FreeSpecLike, Matchers }

class UserMessageRepositoryBySlickImplSpec
    extends FreeSpecLike
    with FlywayWithMySQLSpecSupport
    with Slick3SpecSupport
    with Matchers
    with SpecSupport {

  override val tables: Seq[String] = Seq("user_message")

  val userMessage = UserMessage(
    id = UserMessageId(IdGenerator.generateIdValue, IdGenerator.generateIdValue),
    status = Status.Active,
    message = "ABC",
    createdAt = ZonedDateTime.now(),
    updatedAt = None
  )

  val userMessages = for (idx <- 1L to 10L)
    yield
      UserMessage(
        id = UserMessageId(IdGenerator.generateIdValue, IdGenerator.generateIdValue),
        status = Status.Active,
        message = s"ABC${idx}",
        createdAt = ZonedDateTime.now(),
        updatedAt = None
      )

  "UserMessageRepositoryBySlickImpl" - {
    "store" in {
      val repository = new UserMessageRepositoryBySlickImpl(dbConfig.profile, dbConfig.db)
      val result = (for {
        _ <- repository.store(userMessage)
        r <- repository.resolveById(userMessage.id)
      } yield r).runToFuture.futureValue

      result shouldBe userMessage
    }
    "storeMulti" in {
      val repository = new UserMessageRepositoryBySlickImpl(dbConfig.profile, dbConfig.db)
      val result = (for {
        _ <- repository.storeMulti(userMessages)
        r <- repository.resolveMulti(userMessages.map(_.id))
      } yield r).runToFuture.futureValue

      sameAs(result, userMessages) shouldBe true
    }
  }
} 
Example 16
Source File: UserAccountRepositoryOnMemorySpec.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.repository.memory

import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.AggregateNotFoundException
import com.github.j5ik2o.dddbase.example.model._
import com.github.j5ik2o.dddbase.example.repository.{ IdGenerator, SpecSupport, UserAccountRepository }
import com.github.j5ik2o.dddbase.example.repository.util.ScalaFuturesSupportSpec
import monix.eval.Task
import monix.execution.Scheduler.Implicits.global
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ FreeSpec, Matchers }

import scala.concurrent.duration._
import scala.concurrent.{ Await, Future }

class UserAccountRepositoryOnMemorySpec
    extends FreeSpec
    with ScalaFutures
    with ScalaFuturesSupportSpec
    with Matchers
    with SpecSupport {

  val userAccount = UserAccount(
    id = UserAccountId(IdGenerator.generateIdValue),
    status = Status.Active,
    emailAddress = EmailAddress("[email protected]"),
    password = HashedPassword("aaa"),
    firstName = "Junichi",
    lastName = "Kato",
    createdAt = ZonedDateTime.now,
    updatedAt = None
  )

  val userAccounts = for (idx <- 1L to 10L)
    yield
      UserAccount(
        id = UserAccountId(IdGenerator.generateIdValue),
        status = Status.Active,
        emailAddress = EmailAddress(s"user${idx}@gmail.com"),
        password = HashedPassword("aaa"),
        firstName = "Junichi",
        lastName = "Kato",
        createdAt = ZonedDateTime.now,
        updatedAt = None
      )

  "UserAccountRepositoryOnMemory" - {
    "store" in {
      val repository = UserAccountRepository.onMemory()
      val result: UserAccount = (for {
        _ <- repository.store(userAccount)
        r <- repository.resolveById(userAccount.id)
      } yield r).runToFuture.futureValue

      result shouldBe userAccount
    }
    "storeMulti" in {
      val repository = UserAccountRepository.onMemory()
      val result: Seq[UserAccount] = (for {
        _ <- repository.storeMulti(userAccounts)

        r <- repository.resolveMulti(userAccounts.map(_.id))
      } yield r).runToFuture.futureValue

      sameAs(result, userAccounts) shouldBe true
    }
    "store then expired" in {
      val repository = UserAccountRepository.onMemory(expireAfterWrite = Some(1 seconds))
      val resultFuture: Future[UserAccount] = (for {
        _ <- repository.store(userAccount)
        _ <- Task.pure(Thread.sleep(1000))
        r <- repository.resolveById(userAccount.id)
      } yield r).runToFuture

      an[AggregateNotFoundException] should be thrownBy {
        Await.result(resultFuture, Duration.Inf)
      }
    }
  }

} 
Example 17
Source File: UserAccount.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.model

import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.{ Aggregate, AggregateLongId }

import scala.reflect._

case class UserAccountId(value: Long) extends AggregateLongId

case class EmailAddress(value: String)

case class HashedPassword(value: String)

case class UserAccount(
    id: UserAccountId,
    status: Status,
    emailAddress: EmailAddress,
    password: HashedPassword,
    firstName: String,
    lastName: String,
    createdAt: ZonedDateTime,
    updatedAt: Option[ZonedDateTime]
) extends Aggregate {
  override type AggregateType = UserAccount
  override type IdType        = UserAccountId
  override protected val tag: ClassTag[UserAccount] = classTag[UserAccount]
} 
Example 18
Source File: UserMessage.scala    From scala-ddd-base   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.dddbase.example.model
import java.time.ZonedDateTime

import com.github.j5ik2o.dddbase.{ Aggregate, AggregateId }

import scala.reflect.{ classTag, ClassTag }

case class UserMessageId(userId: Long, messageId: Long) extends AggregateId {
  override type IdType = (Long, Long)
  override val value = (userId, messageId)
}

case class UserMessage(
    id: UserMessageId,
    status: Status,
    message: String,
    createdAt: ZonedDateTime,
    updatedAt: Option[ZonedDateTime]
) extends Aggregate {
  override type IdType        = UserMessageId
  override type AggregateType = UserMessage
  override protected val tag: ClassTag[UserMessage] = classTag[UserMessage]
} 
Example 19
Source File: TimePrinter.scala    From get-programming-with-scala   with MIT License 5 votes vote down vote up
package org.example.time

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

class TimePrinter(formatter: DateTimeFormatter) {

  def now(country: String): String = {
    val timezone = countryToTimezone(country)
    val dateTime = currentDateTime(timezone)
    dateTimeToString(dateTime)
  }

  private def countryToTimezone(country: String): String =
    country.toLowerCase match {
      case "italy" => "Europe/Rome"
      case "uk" => "Europe/London"
      case "germany" => "Europe/Berlin"
      case "japan" => "Asia/Tokyo"
      case _ =>
        val msg = s"Unknown timezone for country $country"
        throw new IllegalStateException(msg)
    }

  private def currentDateTime(timezone: String): ZonedDateTime = {
    val zoneId = ZoneId.of(timezone)
    ZonedDateTime.now(zoneId)
  }

  private def dateTimeToString(dateTime: ZonedDateTime): String =
    formatter.format(dateTime)
} 
Example 20
Source File: TimePrinter.scala    From get-programming-with-scala   with MIT License 5 votes vote down vote up
package org.example.time

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

class TimePrinter(formatter: DateTimeFormatter) {

  def now(timezone: String): String = {
    val dateTime = currentDateTime(timezone)
    dateTimeToString(dateTime)
  }

  private def currentDateTime(timezone: String): ZonedDateTime = {
    val zoneId = ZoneId.of(timezone)
    ZonedDateTime.now(zoneId)
  }

  private def dateTimeToString(dateTime: ZonedDateTime): String =
    formatter.format(dateTime)
} 
Example 21
Source File: GenericStatus.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.operator

import java.time.ZonedDateTime

import play.api.libs.json.{Format, Json}

case class GenericStatus(
    conditions: Option[List[Condition]]
)

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

case class Condition(
    `type`: String,
    status: String,
    reason: Option[String] = None,
    message: Option[String] = None,
    severity: Option[String] = None,
    lastUpdateTime: Option[ZonedDateTime] = None,
    lastTransitionTime: Option[ZonedDateTime] = None
)

object Condition {
  private implicit val timeFormat: Format[ZonedDateTime] =
    Format(skuber.json.format.timeReads, skuber.json.format.timewWrites)
  implicit val format: Format[Condition] = Json.format
} 
Example 22
Source File: Validated.scala    From cloudstate   with Apache License 2.0 5 votes vote down vote up
package io.cloudstate.operator

import java.time.ZonedDateTime

import io.cloudstate.operator.OperatorConstants.FalseStatus

import scala.concurrent.{ExecutionContext, Future}


sealed trait Validated[+T] {
  import io.cloudstate.operator.Validated._

  def flatMap[R](f: T => Validated[R])(implicit ec: ExecutionContext): Validated[R] = this match {
    case Valid(t) => f(t)
    case invalid @ Invalid(_) => invalid
    case FutureBased(future) => FutureBased(future.map(_.flatMap(f)))
  }

  def map[R](f: T => R)(implicit ec: ExecutionContext): Validated[R] = this match {
    case Valid(t) => Valid(f(t))
    case invalid @ Invalid(_) => invalid
    case FutureBased(future) => FutureBased(future.map(_.map(f)))
  }

  def toFutureEither(implicit ec: ExecutionContext): Future[Either[List[Condition], T]] =
    fold(Left(_), Right(_))

  def fold[R](invalid: List[Condition] => R, success: T => R)(implicit ec: ExecutionContext): Future[R] = this match {
    case Valid(t) => Future.successful(success(t))
    case Invalid(errors) => Future.successful(invalid(errors))
    case FutureBased(future) => future.flatMap(_.fold(invalid, success))
  }

  def zip[R](other: Validated[R])(implicit ec: ExecutionContext): Validated[(T, R)] = (this, other) match {
    case (Invalid(e1), Invalid(e2)) => Invalid(e1 ++ e2)
    case (invalid @ Invalid(_), _) => invalid
    case (_, invalid @ Invalid(_)) => invalid
    case (FutureBased(future), v) => FutureBased(future.map(_.zip(v)))
    case (v, FutureBased(future)) => FutureBased(future.map(v.zip(_)))
    case (Valid(v1), Valid(v2)) => Valid((v1, v2))
  }

  def filter(predicate: T => Boolean)(implicit ec: ExecutionContext): Validated[T] = this match {
    case v @ Valid(t) if predicate(t) => v
    case Valid(_) =>
      invalid(
        Condition(
          `type` = "Filtered",
          status = OperatorConstants.FalseStatus,
          reason = Some("PredicateFailed"),
          message = Some("A generic predicate failed"),
          lastTransitionTime = Some(ZonedDateTime.now())
        )
      )
    case invalid @ Invalid(_) => invalid
    case FutureBased(future) => FutureBased(future.map(_.filter(predicate)))
  }

  def withFilter(predicate: T => Boolean)(implicit ec: ExecutionContext): Validated[T] = filter(predicate)

}

object Validated {
  def apply[T](t: T): Validated[T] = Valid(t)
  def future[T](future: Future[T])(implicit ec: ExecutionContext): Validated[T] = FutureBased(future.map(Valid(_)))
  def invalid(errors: List[Condition]): Validated[Nothing] = Invalid(errors)
  def invalid(error: Condition): Validated[Nothing] = Invalid(List(error))

  def error(`type`: String, reason: String, message: String) =
    Validated.invalid(
      Condition(`type` = `type`,
                status = FalseStatus,
                severity = Some("Error"),
                lastTransitionTime = Some(ZonedDateTime.now()),
                reason = Some(reason),
                message = Some(message))
    )

  implicit def futureT2Validated[T](future: Future[T])(implicit ec: ExecutionContext): Validated[T] =
    Validated.future(future)
  implicit def futureValidated2Validated[T](future: Future[Validated[T]])(implicit ec: ExecutionContext): Validated[T] =
    FutureBased(future)

  implicit class ValidatedConverters[T](t: T) {
    def valid: Validated[T] = Valid(t)
  }

  private case class FutureBased[+T](future: Future[Validated[T]]) extends Validated[T]
  private case class Valid[+T](t: T) extends Validated[T]
  private case class Invalid(errors: List[Condition]) extends Validated[Nothing]
} 
Example 23
Source File: ISO8601DateTime.scala    From toketi-iothubreact   with MIT License 5 votes vote down vote up
// Copyright (c) Microsoft. All rights reserved.

package F_SendMessageToDevice

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

import scala.util.matching.Regex


case class ISO8601DateTime(text: String) {

  private lazy val pattern1: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{1,3})Z""".r
  private lazy val pattern2: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})Z""".r
  private lazy val pattern3: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})""".r
  private lazy val format  : DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
  private lazy val zone    : ZoneId            = ZoneId.of("UTC")

  private lazy val zonedDateTime: ZonedDateTime = {
    text match {
      case pattern1(y, m, d, h, i, s, n) ⇒
        val ni = n.toInt
        val nanos = if (ni > 99) ni * 1000000 else if (ni > 9) ni * 10000000 else ni * 100000000
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, h.toInt, i.toInt, s.toInt, nanos, zone)

      case pattern2(y, m, d, h, i, s) ⇒
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, h.toInt, i.toInt, s.toInt, 0, zone)

      case pattern3(y, m, d) ⇒
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, 0, 0, 0, 0, zone)

      case null ⇒ null
      case _    ⇒ throw new Exception(s"wrong date time format: $text")
    }
  }

  override def toString: String = if (zonedDateTime == null) "" else zonedDateTime.format(format)
} 
Example 24
Source File: ISO8601DateTime.scala    From toketi-iothubreact   with MIT License 5 votes vote down vote up
// Copyright (c) Microsoft. All rights reserved.

package B_PrintTemperature

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

import scala.util.matching.Regex


case class ISO8601DateTime(text: String) {

  private lazy val pattern1: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{1,3})Z""".r
  private lazy val pattern2: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})Z""".r
  private lazy val pattern3: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})""".r
  private lazy val format  : DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
  private lazy val zone    : ZoneId            = ZoneId.of("UTC")

  private lazy val zonedDateTime: ZonedDateTime = {
    text match {
      case pattern1(y, m, d, h, i, s, n) ⇒
        val ni = n.toInt
        val nanos = if (ni > 99) ni * 1000000 else if (ni > 9) ni * 10000000 else ni * 100000000
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, h.toInt, i.toInt, s.toInt, nanos, zone)

      case pattern2(y, m, d, h, i, s) ⇒
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, h.toInt, i.toInt, s.toInt, 0, zone)

      case pattern3(y, m, d) ⇒
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, 0, 0, 0, 0, zone)

      case null ⇒ null
      case _    ⇒ throw new Exception(s"wrong date time format: $text")
    }
  }

  override def toString: String = if (zonedDateTime == null) "" else zonedDateTime.format(format)
} 
Example 25
Source File: full_petstore_api_yaml.extractor.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package full.petstore.api.yaml

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.SwaggerSecurityExtractors._
import de.zalando.play.controllers.ArrayWrapper
import java.time.ZonedDateTime

object SecurityExtractorsExecutionContext {
    // this ExecutionContext might be overridden if default configuration is not suitable for some reason
    implicit val ec = de.zalando.play.controllers.Contexts.tokenChecking
}

trait SecurityExtractors {
    def api_key_Extractor[User >: Any](): RequestHeader => Future[Option[User]] =
        header => headerApiKey("api_key")(header) { (apiKey: String) =>
            ???
    }
    def petstore_auth_Extractor[User >: Any](scopes: String*): RequestHeader => Future[Option[User]] =
        header => oAuth(scopes)("http://petstore.swagger.wordnik.com/oauth/dialog")(header) { (token: play.api.libs.json.JsValue) =>
            ???
    }
    implicit val unauthorizedContentWriter = ???
    def unauthorizedContent(req: RequestHeader) = Results.Unauthorized(???)
} 
Example 26
Source File: SQLQuerySpec.scala    From scruid   with Apache License 2.0 5 votes vote down vote up
package ing.wbaa.druid

import java.time.{ LocalDateTime, ZonedDateTime }

import akka.stream.scaladsl.Sink
import ing.wbaa.druid.SQL._
import ing.wbaa.druid.client.CirceDecoders
import io.circe.generic.auto._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.matchers.should.Matchers
import org.scalatest.time.{ Millis, Seconds, Span }
import org.scalatest.wordspec.AnyWordSpec

class SQLQuerySpec extends AnyWordSpec with Matchers with ScalaFutures with CirceDecoders {
  implicit override val patienceConfig =
    PatienceConfig(timeout = Span(20, Seconds), interval = Span(5, Millis))
  private val totalNumberOfEntries  = 39244
  private val usOnlyNumberOfEntries = 528

  implicit val config = DruidConfig()
  implicit val mat    = config.client.actorMaterializer

  case class Result(hourTime: ZonedDateTime, count: Int)

  "SQL query" should {

    val sqlQuery: SQLQuery = dsql"""
      |SELECT FLOOR(__time to HOUR) AS hourTime, count(*) AS "count"
      |FROM wikipedia
      |WHERE "__time" BETWEEN TIMESTAMP '2015-09-12 00:00:00' AND TIMESTAMP '2015-09-13 00:00:00'
      |GROUP BY 1
      |""".stripMargin

    "successfully be interpreted by Druid" in {
      val resultsF = sqlQuery.execute()
      whenReady(resultsF) { response =>
        response.list[Result].map(_.count).sum shouldBe totalNumberOfEntries
      }
    }

    "support streaming" in {
      val resultsF = sqlQuery.streamAs[Result]().runWith(Sink.seq)

      whenReady(resultsF) { results =>
        results.map(_.count).sum shouldBe totalNumberOfEntries
      }
    }
  }

  "SQL parameterized query" should {

    val fromDateTime   = LocalDateTime.of(2015, 9, 12, 0, 0, 0, 0)
    val untilDateTime  = fromDateTime.plusDays(1)
    val countryIsoCode = "US"

    val sqlQuery: SQLQuery =
      dsql"""
      |SELECT FLOOR(__time to HOUR) AS hourTime, count(*) AS "count"
      |FROM wikipedia
      |WHERE "__time" BETWEEN ${fromDateTime} AND ${untilDateTime} AND countryIsoCode = ${countryIsoCode}
      |GROUP BY 1
      |""".stripMargin

    "be expressed as a parameterized query with three parameters" in {
      sqlQuery.query.count(_ == '?') shouldBe 3
      sqlQuery.parameters.size shouldBe 3

      sqlQuery.parameters(0) shouldBe SQLQueryParameter(SQLQueryParameterType.Timestamp,
                                                        "2015-09-12 00:00:00")
      sqlQuery.parameters(1) shouldBe SQLQueryParameter(SQLQueryParameterType.Timestamp,
                                                        "2015-09-13 00:00:00")
      sqlQuery.parameters(2) shouldBe SQLQueryParameter(SQLQueryParameterType.Varchar, "US")
    }

    "successfully be interpreted by Druid" in {
      val resultsF = sqlQuery.execute()
      whenReady(resultsF) { response =>
        response.list[Result].map(_.count).sum shouldBe usOnlyNumberOfEntries
      }
    }

    "support streaming" in {
      val resultsF = sqlQuery.streamAs[Result]().runWith(Sink.seq)

      whenReady(resultsF) { results =>
        results.map(_.count).sum shouldBe usOnlyNumberOfEntries
      }

    }

  }
} 
Example 27
Source File: KmsSmokeTest.scala    From aws4s   with MIT License 5 votes vote down vote up
package org.aws4s.kms

import java.time.ZonedDateTime
import org.aws4s.core.SmokeTest

class KmsSmokeTest extends SmokeTest {

  "Essential functionality" should "be alright" in {

    val kms  = Kms(httpClient, region, credentials)
    val data = "secretdata"

    val all = for {
      keyId      <- kms.createKey(Some(KeyDescription(s"KMS smoke-test key ${ZonedDateTime.now}"))) map (_.keyMetadata.keyId)
      ciphertext <- kms.encrypt(keyId, Plaintext(Blob(data.getBytes))) map (_.cipherText)
      plaintext  <- kms.decrypt(ciphertext) map (_.plainText)
      _          <- kms.scheduleKeyDeletion(keyId, Some(PendingWindowInDays(7)))
    } yield new String(plaintext.raw.value)

    all.unsafeToFuture() map (_ shouldBe data)
  }
} 
Example 28
Source File: License.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
import java.io.File
import java.io.PrintStream
import java.time.ZonedDateTime
import java.time.ZoneOffset
import scala.io.Source
import sbt._


  """.stripMargin.trim

  def findFiles(dir: File): Seq[File] = {
    (dir ** "*.scala").get ++ (dir ** "*.java").get
  }

  def checkLicenseHeaders(log: Logger, srcDir: File): Unit = {
    val badFiles = findFiles(srcDir).filterNot(checkLicenseHeader)
    if (badFiles.nonEmpty) {
      badFiles.foreach { f => log.error(s"bad license header: $f") }
      sys.error(s"${badFiles.size} files with incorrect header, run formatLicenseHeaders to fix")
    } else {
      log.info("all files have correct license header")
    }
  }

  def checkLicenseHeader(file: File): Boolean = {
    val lines = Source.fromFile(file, "UTF-8").getLines().toList
    checkLicenseHeader(lines)
  }

  def checkLicenseHeader(lines: List[String]): Boolean = {
    val header = lines.takeWhile(!_.startsWith("package ")).mkString(lineSeparator)
    header == apache2
  }

  def formatLicenseHeaders(log: Logger, srcDir: File): Unit = {
    findFiles(srcDir).foreach { f => formatLicenseHeader(log, f) }
  }

  def formatLicenseHeader(log: Logger, file: File): Unit = {
    val lines = Source.fromFile(file, "UTF-8").getLines().toList
    if (!checkLicenseHeader(lines)) {
      log.info(s"fixing license header: $file")
      writeLines(file, apache2 :: removeExistingHeader(lines))
    }
  }

  def removeExistingHeader(lines: List[String]): List[String] = {
    val res = lines.dropWhile(!_.startsWith("package "))
    if (res.isEmpty) lines else res
  }

  def writeLines(file: File, lines: List[String]): Unit = {
    val out = new PrintStream(file)
    try lines.foreach(out.println) finally out.close()
  }
} 
Example 29
Source File: CustomDerivations.scala    From zio-config   with Apache License 2.0 5 votes vote down vote up
package zio.config.examples.magnolia

import java.time.{ LocalDate, ZonedDateTime }
import scala.util.Try
import zio.config._
import zio.config.magnolia.DeriveConfigDescriptor._

import zio.config.typesafe._

object CustomDerivations extends App {
  case class AppConfig(jobName: String, details: Option[Detail], s3Path: S3Path)

  case class Detail(containerId: String, executionTime: Either[ZonedDateTime, LocalDate])

  case class S3Path(s: String)

  object S3Path {
    // For some reason you decided to check if the string inside s3Path is empty or not while writing back as well
    // If this implicit doesn't exist, zio-config-magnolia falls back to its default behaviour
    // and finds out an instance for S3Path as it is a simple case class.
    implicit val descriptorOfS3Path: Descriptor[S3Path] =
      Descriptor[String]
        .xmapEither(
          s => validateS3Path(s).toRight(s"Invalid s3 path: ${s}"),
          value => validateS3Path(value.s).map(_.s).toRight("Cannot write. Invalid S3 path.")
        )

    private def validateS3Path(s3Path: String): Option[S3Path] =
      if (s3Path.startsWith("s3://")) Some(S3Path(s3Path)) else None
  }

  // Good to keep implicit derivations within companion objects.
  // Preferable to give descriptions to enrich error reporting of zio-config.
  object Detail

  val config =
    """
    jobName : "spark"
    s3Path  : "s3://path"
    details : {
      containerId : abcdefg
      executionTime: "2020-06-20T17:15:23.601712+10:00[Australia/Sydney]"
    }
    """

  // Custom derivation for zoned date time. Since zonedDateTime is external,
  // we couldn't have a companion object to place this implicit, and hence placed
  // globally for the automatic derivation to work.
  implicit val descriptorOfZonedDateTime: Descriptor[ZonedDateTime] =
    Descriptor[String]
      .xmapEitherELeftPartial(
        x => Try(ZonedDateTime.parse(x)).toEither
      )(_.toString)(_.getMessage) ?? "time in zoned date time"

  val appConfigDesc =
    descriptor[AppConfig]

  val source = TypesafeConfigSource.fromHoconString(config) match {
    case Right(a) => a
    case Left(_)  => throw new Exception("bad hocon string")
  }

  val s = read(appConfigDesc from source)

  assert(
    s == Right(
      AppConfig(
        "spark",
        Some(Detail("abcdefg", Left(ZonedDateTime.parse("2020-06-20T17:15:23.601712+10:00[Australia/Sydney]")))),
        S3Path("s3://path")
      )
    )
  )
} 
Example 30
Source File: TimeHelper.scala    From ez-framework   with Apache License 2.0 5 votes vote down vote up
package com.ecfront.ez.framework.core.helper

import java.text.SimpleDateFormat
import java.time.ZonedDateTime
import java.util.{Calendar, Date, TimeZone}


object TimeHelper {

  val msf = new SimpleDateFormat("yyyyMMddHHmmssSSS")
  val sf = new SimpleDateFormat("yyyyMMddHHmmss")
  val mf = new SimpleDateFormat("yyyyMMddHHmm")
  val hf = new SimpleDateFormat("yyyyMMddHH")
  val df = new SimpleDateFormat("yyyyMMdd")
  val Mf = new SimpleDateFormat("yyyyMM")
  val yf = new SimpleDateFormat("yyyy")

  val yyyy_MM_dd_HH_mm_ss_SSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
  val yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  val yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd")

  def dateOffset(offsetValue: Int, offsetUnit: Int, currentTime: Long): Long = {
    val format = currentTime.toString.length match {
      case 8 => df
      case 10 => hf
      case 12 => mf
      case 14 => sf
      case 17 => msf
    }
    val calendar = Calendar.getInstance()
    calendar.setTime(format.parse(currentTime + ""))
    calendar.add(offsetUnit, offsetValue)
    format.format(calendar.getTime).toLong
  }

  def dateOffset(offsetValue: Int, offsetUnit: Int, currentDate: Date): Date = {
    val calendar = Calendar.getInstance()
    calendar.setTime(currentDate)
    calendar.add(offsetUnit, offsetValue)
    calendar.getTime
  }

  def utc2Local(utcTime: String, localTimePatten: String = "yyyy-MM-dd'T'HH:mm:ss"): String = {
    val utcDate = Date.from(ZonedDateTime.parse(utcTime).toInstant)
    val localF = new SimpleDateFormat(localTimePatten)
    localF.setTimeZone(TimeZone.getDefault)
    localF.format(utcDate.getTime)
  }

} 
Example 31
Source File: i041_no_json_deserialiser_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package i041_no_json_deserialiser


    import java.time.ZonedDateTime
    import scala.math.BigDecimal
    import scala.math.BigInt

    import de.zalando.play.controllers.PlayPathBindables


//noinspection ScalaStyle
package yaml {


    case class Money(id: UserId, userId: UserId, amount: MoneyAmount, createDate: MoneyCreateDate) 
    case class User(id: UserId, name: UserName, money: UserMoney) 
    case class UserMoney(id: UserId, userId: UserId, amount: MoneyAmount, createDate: MoneyCreateDate) 
    case class Error(code: Int, message: String) 


    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    import de.zalando.play.controllers.MissingDefaultReads
    object BodyReads extends MissingDefaultReads {
        implicit val MoneyReads: Reads[Money] = (
            (JsPath \ "id").readNullable[Long] and (JsPath \ "userId").readNullable[Long] and (JsPath \ "amount").readNullable[BigDecimal] and (JsPath \ "createDate").readNullable[ZonedDateTime]
        )(Money.apply _)
        implicit val UserMoneyReads: Reads[UserMoney] = (
            (JsPath \ "id").readNullable[Long] and (JsPath \ "userId").readNullable[Long] and (JsPath \ "amount").readNullable[BigDecimal] and (JsPath \ "createDate").readNullable[ZonedDateTime]
        )(UserMoney.apply _)
        implicit val UserReads: Reads[User] = (
            (JsPath \ "id").readNullable[Long] and (JsPath \ "name").readNullable[String] and (JsPath \ "money").read[UserMoney]
        )(User.apply _)
    }

    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    import de.zalando.play.controllers.MissingDefaultWrites
    object ResponseWrites extends MissingDefaultWrites {
    implicit val MoneyWrites: Writes[Money] = new Writes[Money] {
        def writes(ss: Money) =
          Json.obj(
            "id" -> ss.id, 
            "userId" -> ss.userId, 
            "amount" -> ss.amount, 
            "createDate" -> ss.createDate
          )
        }
    implicit val UserMoneyWrites: Writes[UserMoney] = new Writes[UserMoney] {
        def writes(ss: UserMoney) =
          Json.obj(
            "id" -> ss.id, 
            "userId" -> ss.userId, 
            "amount" -> ss.amount, 
            "createDate" -> ss.createDate
          )
        }
    implicit val UserWrites: Writes[User] = new Writes[User] {
        def writes(ss: User) =
          Json.obj(
            "id" -> ss.id, 
            "name" -> ss.name, 
            "money" -> ss.money
          )
        }
    }
}

// should be defined after the package because of the https://issues.scala-lang.org/browse/SI-9922

//noinspection ScalaStyle
package object yaml {

    type MoneyCreateDate = Option[ZonedDateTime]
    type UserId = Option[Long]
    type MoneyAmount = Option[BigDecimal]
    type UserName = Option[String]
    type UserGetResponses200 = Seq[User]


import play.api.mvc.{QueryStringBindable, PathBindable}

    implicit val bindable_BigIntPath = PlayPathBindables.pathBindableBigInt

} 
Example 32
Source File: all_of_imports_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
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



} 
Example 33
Source File: i041_no_json_deserialiser_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package i041_no_json_deserialiser.yaml

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._
import java.time.ZonedDateTime
import scala.math.BigDecimal
import scala.math.BigInt

object Generators extends JsValueGenerators {
    

    
    def createMoneyCreateDateGenerator = _generate(MoneyCreateDateGenerator)
    def createUserIdGenerator = _generate(UserIdGenerator)
    def createMoneyAmountGenerator = _generate(MoneyAmountGenerator)
    def createBigIntGenerator = _generate(BigIntGenerator)
    def createUserNameGenerator = _generate(UserNameGenerator)
    def createStringGenerator = _generate(StringGenerator)
    def createUserGetResponses200Generator = _generate(UserGetResponses200Generator)
    

    
    def MoneyCreateDateGenerator = Gen.option(arbitrary[ZonedDateTime])
    def UserIdGenerator = Gen.option(arbitrary[Long])
    def MoneyAmountGenerator = Gen.option(arbitrary[BigDecimal])
    def BigIntGenerator = arbitrary[BigInt]
    def UserNameGenerator = Gen.option(arbitrary[String])
    def StringGenerator = arbitrary[String]
    def UserGetResponses200Generator: Gen[List[User]] = Gen.containerOf[List,User](UserGenerator)
    

    def createMoneyGenerator = _generate(MoneyGenerator)
    def createUserGenerator = _generate(UserGenerator)
    def createUserMoneyGenerator = _generate(UserMoneyGenerator)
    def createErrorGenerator = _generate(ErrorGenerator)


    def MoneyGenerator = for {
        id <- UserIdGenerator
        userId <- UserIdGenerator
        amount <- MoneyAmountGenerator
        createDate <- MoneyCreateDateGenerator
    } yield Money(id, userId, amount, createDate)
    def UserGenerator = for {
        id <- UserIdGenerator
        name <- UserNameGenerator
        money <- UserMoneyGenerator
    } yield User(id, name, money)
    def UserMoneyGenerator = for {
        id <- UserIdGenerator
        userId <- UserIdGenerator
        amount <- MoneyAmountGenerator
        createDate <- MoneyCreateDateGenerator
    } yield UserMoney(id, userId, amount, createDate)
    def ErrorGenerator = for {
        code <- arbitrary[Int]
        message <- arbitrary[String]
    } yield Error(code, message)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    
    
    implicit lazy val arbDateTime: Arbitrary[ZonedDateTime] = Arbitrary(for {
        d <- arbitrary[java.util.Date]
    } yield ZonedDateTime.ofInstant(d.toInstant, java.time.ZoneId.systemDefault()))
    
    
    

} 
Example 34
Source File: split_petstore_api_yaml.extractor.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package split.petstore.api.yaml

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.SwaggerSecurityExtractors._
import de.zalando.play.controllers.ArrayWrapper
import java.time.ZonedDateTime

object SecurityExtractorsExecutionContext {
    // this ExecutionContext might be overridden if default configuration is not suitable for some reason
    implicit val ec = de.zalando.play.controllers.Contexts.tokenChecking
}

trait SecurityExtractors {
    def api_key_Extractor[User >: Any](): RequestHeader => Future[Option[User]] =
        header => headerApiKey("api_key")(header) { (apiKey: String) =>
            ???
    }
    def petstore_auth_Extractor[User >: Any](scopes: String*): RequestHeader => Future[Option[User]] =
        header => oAuth(scopes)("http://petstore.swagger.wordnik.com/oauth/dialog")(header) { (token: play.api.libs.json.JsValue) =>
            ???
    }
    implicit val unauthorizedContentWriter = ???
    def unauthorizedContent(req: RequestHeader) = Results.Unauthorized(???)
} 
Example 35
Source File: full_petstore_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package full.petstore.api.yaml

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.{FutureAuthenticatedBuilder,PlayBodyParsing}
import de.zalando.play.controllers.ArrayWrapper
import java.time.ZonedDateTime


trait FullPetstoreApiYamlSecurity extends SecurityExtractors {
    import SecurityExtractorsExecutionContext.ec
    
    class findPetsByTagsSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class updatePetSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class addPetSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class getPetByIdSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(api_key_Extractor(), petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class updatePetWithFormSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class deletePetSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class findPetsByStatusSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
} 
Example 36
Source File: split_petstore_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package split.petstore.api.yaml

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.{FutureAuthenticatedBuilder,PlayBodyParsing}
import de.zalando.play.controllers.ArrayWrapper
import java.time.ZonedDateTime


trait SplitPetstoreApiYamlSecurity extends SecurityExtractors {
    import SecurityExtractorsExecutionContext.ec
    
    class findPetsByTagsSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class updatePetSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class addPetSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class getPetByIdSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(api_key_Extractor(), petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class updatePetWithFormSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class deletePetSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
    class findPetsByStatusSecureAction(scopes: String*)
 extends FutureAuthenticatedBuilder(
        req => {
            val secureChecks: Seq[RequestHeader => Future[Option[_]]] = Seq(petstore_auth_Extractor("write_pets", "read_pets"))
            val individualChecks: Future[Seq[Option[_]]] = Future.sequence(secureChecks.map(_.apply(req)))
                individualChecks.map { checks =>
                    checks.find(_.isEmpty).getOrElse(Option(checks.map(_.get)))
                }
        }, unauthorizedContent)
    
} 
Example 37
Source File: ScheduleSpec.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package model

import java.time.{Clock, Instant, ZoneId, ZonedDateTime}

import com.wix.accord.Validator
import com.wix.accord.dsl._

import scala.concurrent.duration._

case class ScheduleSpec(
    id: String,
    cron: CronSpec,
    timeZone: ZoneId = ScheduleSpec.DefaultTimeZone,
    startingDeadline: Duration = ScheduleSpec.DefaultStartingDeadline,
    concurrencyPolicy: ConcurrencyPolicy = ScheduleSpec.DefaultConcurrencyPolicy,
    enabled: Boolean = ScheduleSpec.DefaultEnabled
) {
  def clock: Clock = ScheduleSpec.DefaultClock

  def nextExecution(after: Instant): Instant = {
    val localAfter = ZonedDateTime.ofInstant(after, timeZone)
    val localNext = cron.nextExecution(localAfter)
    localNext.toInstant
  }

  def nextExecution(): Instant = nextExecution(clock.instant())
}

object ScheduleSpec {
  val DefaultTimeZone = ZoneId.of("UTC")
  val DefaultStartingDeadline = 15.minutes
  val DefaultConcurrencyPolicy = ConcurrencyPolicy.Allow
  val DefaultEnabled = true
  val DefaultClock = Clock.systemUTC()

  implicit lazy val validScheduleSpec: Validator[ScheduleSpec] = validator[ScheduleSpec] { spec =>
    spec.startingDeadline >= 1.minute
  }
} 
Example 38
Source File: all_of_imports_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package all_of_imports.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import java.time.ZonedDateTime
// ----- constraints and wrapper validations -----
class ValueTypeConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Value⌿type"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class ValueTypeValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Value⌿type"
    override val validators = Seq(new ValueTypeConstraints(instance))
}
class DatetimeValueValueConstraints(override val instance: ZonedDateTime) extends ValidationBase[ZonedDateTime] {
    override val reference = "⌿definitions⌿DatetimeValue⌿value"
    override def constraints: Seq[Constraint[ZonedDateTime]] =
        Seq()
}
class DatetimeValueValueValidator(instance: ZonedDateTime) extends RecursiveValidator {
    override val reference = "⌿definitions⌿DatetimeValue⌿value"
    override val validators = Seq(new DatetimeValueValueConstraints(instance))
}
// ----- complex type validators -----

// ----- option delegating validators -----
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
class DatetimeValueValidator(instance: DatetimeValue) extends RecursiveValidator {
    override val reference = "⌿definitions⌿DatetimeValue"
    override val validators = Seq(
        new ValueTypeValidator(instance.`type`), 
        new DatetimeValueValueValidator(instance.value)
    )
}
// ----- call validations -----
class PostValidator(body: DatetimeValue) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿post"
    override val validators = Seq(
        new DatetimeValueValidator(body)
    
    )
} 
Example 39
Source File: string_formats_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package string_formats.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.Base64String
import Base64String._
import java.time.ZonedDateTime
import java.util.UUID
import java.time.LocalDate
import de.zalando.play.controllers.BinaryString
import BinaryString._
// ----- constraints and wrapper validations -----
class GetBase64OptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿get⌿base64⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetBase64OptValidator(instance: Base64String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿base64⌿Opt"
    override val validators = Seq(new GetBase64OptConstraints(instance))
}
class GetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/⌿get⌿petId"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetPetIdValidator(instance: BinaryString) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿petId"
    override val validators = Seq(new GetPetIdConstraints(instance))
}
class GetDate_timeOptConstraints(override val instance: ZonedDateTime) extends ValidationBase[ZonedDateTime] {
    override val reference = "⌿paths⌿/⌿get⌿date_time⌿Opt"
    override def constraints: Seq[Constraint[ZonedDateTime]] =
        Seq()
}
class GetDate_timeOptValidator(instance: ZonedDateTime) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date_time⌿Opt"
    override val validators = Seq(new GetDate_timeOptConstraints(instance))
}
class GetUuidOptConstraints(override val instance: UUID) extends ValidationBase[UUID] {
    override val reference = "⌿paths⌿/⌿get⌿uuid⌿Opt"
    override def constraints: Seq[Constraint[UUID]] =
        Seq()
}
class GetUuidOptValidator(instance: UUID) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿uuid⌿Opt"
    override val validators = Seq(new GetUuidOptConstraints(instance))
}
class GetDateOptConstraints(override val instance: LocalDate) extends ValidationBase[LocalDate] {
    override val reference = "⌿paths⌿/⌿get⌿date⌿Opt"
    override def constraints: Seq[Constraint[LocalDate]] =
        Seq()
}
class GetDateOptValidator(instance: LocalDate) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date⌿Opt"
    override val validators = Seq(new GetDateOptConstraints(instance))
}
// ----- complex type validators -----

// ----- option delegating validators -----
class GetBase64Validator(instance: GetBase64) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿base64"
    override val validators = instance.toSeq.map { new GetBase64OptValidator(_) }
}
class GetDate_timeValidator(instance: GetDate_time) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date_time"
    override val validators = instance.toSeq.map { new GetDate_timeOptValidator(_) }
}
class GetUuidValidator(instance: GetUuid) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿uuid"
    override val validators = instance.toSeq.map { new GetUuidOptValidator(_) }
}
class GetDateValidator(instance: GetDate) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿date"
    override val validators = instance.toSeq.map { new GetDateOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class GetValidator(date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid, petId: BinaryString) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new GetDate_timeValidator(date_time), 
    
        new GetDateValidator(date), 
    
        new GetBase64Validator(base64), 
    
        new GetUuidValidator(uuid), 
    
        new GetPetIdValidator(petId)
    
    )
} 
Example 40
Source File: Rfc3339UtilTest.scala    From api-first-hand   with MIT License 5 votes vote down vote up
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"
    }
  }
} 
Example 41
Source File: Rfc3339Util.scala    From api-first-hand   with MIT License 5 votes vote down vote up
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))
    }
  }

} 
Example 42
Source File: CronGenerator.scala    From lemon-schedule   with GNU General Public License v2.0 5 votes vote down vote up
package com.gabry.job.utils

import java.time.temporal.ChronoField
import java.time.{Instant, ZoneId, ZonedDateTime}
import java.util.Locale

import com.cronutils.descriptor.CronDescriptor
import com.cronutils.model.CronType
import com.cronutils.model.definition.CronDefinitionBuilder
import com.cronutils.model.time.ExecutionTime
import com.cronutils.parser.CronParser


  def isValid(cronExpression:String):Boolean = {
    try{
      parser.parse(cronExpression)
      true
    }catch{
      case ex:Exception =>
        false
    }
  }

} 
Example 43
Source File: ParameterMappers.scala    From neotypes   with MIT License 5 votes vote down vote up
package neotypes
package implicits.mappers

import java.time.{Duration, LocalDate, LocalDateTime, LocalTime, Period, OffsetDateTime, OffsetTime, ZonedDateTime}
import java.util.UUID

import mappers.ParameterMapper

import org.neo4j.driver.v1.Value
import org.neo4j.driver.v1.types.{IsoDuration, Point}

import scala.collection.Iterable
import scala.jdk.CollectionConverters._

trait ParameterMappers {
  implicit final val BooleanParameterMapper: ParameterMapper[Boolean] =
    ParameterMapper.fromCast(Boolean.box)

  implicit final val ByteArrayParameterMapper: ParameterMapper[Array[Byte]] =
    ParameterMapper.identity

  implicit final val DoubleParameterMapper: ParameterMapper[Double] =
    ParameterMapper.fromCast(Double.box)

  implicit final val DurationParameterMapper: ParameterMapper[Duration] =
    ParameterMapper.identity

  implicit final val FloatParameterMapper: ParameterMapper[Float] =
    ParameterMapper.fromCast(Float.box)

  implicit final val IntParameterMapper: ParameterMapper[Int] =
    ParameterMapper.fromCast(Int.box)

  implicit final val IsoDurationParameterMapper: ParameterMapper[IsoDuration] =
    ParameterMapper.identity

  implicit final val LocalDateParameterMapper: ParameterMapper[LocalDate] =
    ParameterMapper.identity

  implicit final val LocalDateTimeParameterMapper: ParameterMapper[LocalDateTime] =
    ParameterMapper.identity

  implicit final val LocalTimeParameterMapper: ParameterMapper[LocalTime] =
    ParameterMapper.identity

  implicit final val LongParameterMapper: ParameterMapper[Long] =
    ParameterMapper.fromCast(Long.box)

  implicit final val OffsetDateTimeParameterMapper: ParameterMapper[OffsetDateTime] =
    ParameterMapper.identity

  implicit final val OffsetTimeParameterMapper: ParameterMapper[OffsetTime] =
    ParameterMapper.identity

  implicit final val PeriodParameterMapper: ParameterMapper[Period] =
    ParameterMapper.identity

  implicit final val PointParameterMapper: ParameterMapper[Point] =
    ParameterMapper.identity

  implicit final val StringParameterMapper: ParameterMapper[String] =
    ParameterMapper.identity

  implicit final val UUIDParameterMapper: ParameterMapper[UUID] =
    ParameterMapper[String].contramap(_.toString)

  implicit final val ValueParameterMapper: ParameterMapper[Value] =
    ParameterMapper.identity

  implicit final val ZonedDateTimeParameterMapper: ParameterMapper[ZonedDateTime] =
    ParameterMapper.identity

  private final def iterableParameterMapper[T](mapper: ParameterMapper[T]): ParameterMapper[Iterable[T]] =
    ParameterMapper.fromCast { col =>
      col.iterator.map(v => mapper.toQueryParam(v).underlying).asJava
    }

  implicit final def collectionParameterMapper[T, C[_]](implicit mapper: ParameterMapper[T], ev: C[T] <:< Iterable[T]): ParameterMapper[C[T]] =
    iterableParameterMapper(mapper).contramap(ev)

  private final def iterableMapParameterMapper[V](mapper: ParameterMapper[V]): ParameterMapper[Iterable[(String, V)]] =
    ParameterMapper.fromCast { col =>
      col.iterator.map {
        case (key, v) => key -> mapper.toQueryParam(v).underlying
      }.toMap.asJava
    }

  implicit final def mapParameterMapper[V, M[_, _]](implicit mapper: ParameterMapper[V], ev: M[String, V] <:< Iterable[(String, V)]): ParameterMapper[M[String, V]] =
    iterableMapParameterMapper(mapper).contramap(ev)

  implicit final def optionAnyRefParameterMapper[T](implicit mapper: ParameterMapper[T]): ParameterMapper[Option[T]] =
    ParameterMapper.fromCast { optional =>
      optional.map(v => mapper.toQueryParam(v).underlying).orNull
    }
} 
Example 44
Source File: PodLogSpec.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber

import java.time.ZonedDateTime

import akka.stream.scaladsl.TcpIdleTimeoutException
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, Matchers}
import org.scalatest.concurrent.Eventually
import skuber.Pod.LogQueryParams
import skuber.json.format._

import scala.concurrent.Await
import scala.concurrent.duration._

class PodLogSpec extends K8SFixture with Eventually with Matchers with BeforeAndAfterAll {
  val podName: String = java.util.UUID.randomUUID().toString

  behavior of "PodLog"

  val idleTimeout = 3.seconds
  override val config = ConfigFactory.parseString(s"skuber.pod-log.idle-timeout=${idleTimeout.toSeconds}s").withFallback(ConfigFactory.load())

  override def beforeAll(): Unit = {
    super.beforeAll()

    val k8s = k8sInit(config)
    Await.result(k8s.create(getNginxPod(podName, "1.7.9")), 3.second)
    // Let the pod running
    Thread.sleep(3000)
    k8s.close
  }

  override def afterAll(): Unit = {
    val k8s = k8sInit(config)
    Await.result(k8s.delete[Pod](podName), 3.second)
    Thread.sleep(3000)
    k8s.close

    super.afterAll()
  }

  it should "get log of a pod" in { k8s =>
    k8s.getPodLogSource(podName, LogQueryParams(follow = Some(false))).flatMap { source =>
      source.map(_.utf8String).runReduce(_ + _).map { s =>
        assert(s == "foo\n")
      }
    }
  }

  it should "tail log of a pod and timeout after a while" in { k8s =>
    var log = ""
    var start = ZonedDateTime.now()
    k8s.getPodLogSource(podName, LogQueryParams(follow = Some(true))).flatMap { source =>
      source.map(_.utf8String).runForeach(log += _)
    }.failed.map { case e: TcpIdleTimeoutException =>
      val msgPattern = s"TCP idle-timeout encountered on connection to [^,]+, no bytes passed in the last ${idleTimeout}"
      assert(e.getMessage.matches(msgPattern), s"""["${e.getMessage}"] does not match ["${msgPattern}"]""")
      assert(log == "foo\n")
      assert(ZonedDateTime.now().isAfter(start.withSecond(idleTimeout.toSeconds.toInt)))
    }
  }

  def getNginxContainer(version: String): Container = Container(
    name = "ubuntu", image = "nginx:" + version,
    command = List("sh"),
    args = List("-c", s"""echo "foo"; trap exit TERM; sleep infinity & wait""")
  )

  def getNginxPod(name: String, version: String): Pod = {
    val container = getNginxContainer(version)
    val podSpec = Pod.Spec(containers = List((container)))
    Pod.named(podName).copy(spec = Some(podSpec))
  }
} 
Example 45
Source File: ComponentSupport.scala    From akka-ddd-cqrs-es-example   with MIT License 5 votes vote down vote up
package com.github.j5ik2o.bank.adaptor.dao

import java.time.{ Instant, ZoneId, ZonedDateTime }

trait ComponentSupport {

  val profile: slick.jdbc.JdbcProfile

  import profile.api._

  implicit val zonedDateTimeColumnType = MappedColumnType.base[ZonedDateTime, java.sql.Timestamp](
    { zdt =>
      new java.sql.Timestamp(zdt.toInstant.toEpochMilli)
    }, { ts =>
      val instant = Instant.ofEpochMilli(ts.getTime)
      ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
    }
  )

  trait DaoSupport[Id, Entity]

  trait Record {
    val id: Long
  }

  trait SoftDeletableRecord extends Record {
    val status: String
  }

  abstract class TableBase[T](_tableTag: Tag, _tableName: String, _schemaName: Option[String] = None)
      extends Table[T](_tableTag, _schemaName, _tableName) {
    def id: Rep[Long] = column[Long]("id", O.PrimaryKey, O.AutoInc)
  }

  trait SoftDeletableTableSupport[T] { this: TableBase[T] =>
    def status: Rep[String]
  }

} 
Example 46
Source File: Executor.scala    From neo4j-spark-connector   with Apache License 2.0 5 votes vote down vote up
package org.neo4j.spark

import java.time.{LocalDate, LocalDateTime, OffsetTime, ZoneOffset, ZonedDateTime}
import java.util
import java.sql.Timestamp

import org.apache.spark.SparkContext
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
import org.apache.spark.sql.catalyst.util.DateTimeUtils
import org.apache.spark.sql.types.StructType
import org.neo4j.spark.dataframe.CypherTypes
import org.neo4j.spark.utils.{Neo4jSessionAwareIterator, Neo4jUtils}

import scala.collection.JavaConverters._


object Executor {

  def convert(value: AnyRef): Any = value match {
    case it: util.Collection[_] => it.toArray()
    case m: java.util.Map[_,_] => m.asScala
    case _ => Neo4jUtils.convert(value)
  }

  def toJava(parameters: Map[String, Any]): java.util.Map[String, Object] = {
    parameters.mapValues(toJava).asJava
  }

  private def toJava(x: Any): AnyRef = x match {
    case y: Seq[_] => y.asJava
    case _ => x.asInstanceOf[AnyRef]
  }

  val EMPTY = Array.empty[Any]

  val EMPTY_RESULT = new CypherResult(new StructType(), Iterator.empty)

  class CypherResult(val schema: StructType, val rows: Iterator[Array[Any]]) {
    def sparkRows: Iterator[Row] = rows.map(row => new GenericRowWithSchema(row, schema))

    def fields = schema.fieldNames
  }

  def execute(sc: SparkContext, query: String, parameters: Map[String, AnyRef]): CypherResult = {
    execute(Neo4jConfig(sc.getConf), query, parameters)
  }

  private def rows(result: Iterator[_]) = {
    var i = 0
    while (result.hasNext) i = i + 1
    i
  }

  def execute(config: Neo4jConfig, query: String, parameters: Map[String, Any], write: Boolean = false): CypherResult = {
    val result = new Neo4jSessionAwareIterator(config, query, toJava(parameters), write)
    if (!result.hasNext) {
      return EMPTY_RESULT
    }
    val peek = result.peek()
    val keyCount = peek.size()
    if (keyCount == 0) {
      return new CypherResult(new StructType(), Array.fill[Array[Any]](rows(result))(EMPTY).toIterator)
    }
    val keys = peek.keys().asScala
    val fields = keys.map(k => (k, peek.get(k).`type`())).map(keyType => CypherTypes.field(keyType))
    val schema = StructType(fields)
    val it = result.map(record => {
      val row = new Array[Any](keyCount)
      var i = 0
      while (i < keyCount) {
        val value = convert(record.get(i).asObject())
        row.update(i, value)
        i = i + 1
      }
      row
    })
    new CypherResult(schema, it)
  }
} 
Example 47
Source File: ArrayOfZonedDateTimesReading.scala    From jsoniter-scala   with MIT License 5 votes vote down vote up
package com.github.plokhotnyuk.jsoniter_scala.benchmark

import java.nio.charset.StandardCharsets.UTF_8
import java.time.ZonedDateTime

import com.avsystem.commons.serialization.json._
import com.github.plokhotnyuk.jsoniter_scala.benchmark.AVSystemCodecs._
import com.github.plokhotnyuk.jsoniter_scala.benchmark.BorerJsonEncodersDecoders._
//import com.github.plokhotnyuk.jsoniter_scala.benchmark.DslPlatformJson._
import com.github.plokhotnyuk.jsoniter_scala.benchmark.JacksonSerDesers._
import com.github.plokhotnyuk.jsoniter_scala.benchmark.JsoniterScalaCodecs._
import com.github.plokhotnyuk.jsoniter_scala.benchmark.SprayFormats._
import com.github.plokhotnyuk.jsoniter_scala.benchmark.UPickleReaderWriters._
import com.github.plokhotnyuk.jsoniter_scala.core._
import com.rallyhealth.weejson.v1.jackson.FromJson
import com.rallyhealth.weepickle.v1.WeePickle.ToScala
import io.circe.parser._
import org.openjdk.jmh.annotations.Benchmark
import play.api.libs.json.Json
import spray.json._

class ArrayOfZonedDateTimesReading extends ArrayOfZonedDateTimesBenchmark {
  @Benchmark
  def avSystemGenCodec(): Array[ZonedDateTime] = JsonStringInput.read[Array[ZonedDateTime]](new String(jsonBytes, UTF_8))

  @Benchmark
  def borer(): Array[ZonedDateTime] = io.bullet.borer.Json.decode(jsonBytes).to[Array[ZonedDateTime]].value

  @Benchmark
  def circe(): Array[ZonedDateTime] = decode[Array[ZonedDateTime]](new String(jsonBytes, UTF_8)).fold(throw _, identity)

  @Benchmark
  def jacksonScala(): Array[ZonedDateTime] = jacksonMapper.readValue[Array[ZonedDateTime]](jsonBytes)

  @Benchmark
  def jsoniterScala(): Array[ZonedDateTime] = readFromArray[Array[ZonedDateTime]](jsonBytes)

  @Benchmark
  def playJson(): Array[ZonedDateTime] = Json.parse(jsonBytes).as[Array[ZonedDateTime]]

  @Benchmark
  def sprayJson(): Array[ZonedDateTime] = JsonParser(jsonBytes).convertTo[Array[ZonedDateTime]]

  @Benchmark
  def uPickle(): Array[ZonedDateTime] = read[Array[ZonedDateTime]](jsonBytes)

  @Benchmark
  def weePickle(): Array[ZonedDateTime] = FromJson(jsonBytes).transform(ToScala[Array[ZonedDateTime]])
} 
Example 48
Source File: EffectiveURIKey.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws.ahc.cache

import java.net.URI
import java.time.Instant
import java.time.ZonedDateTime

import com.typesafe.play.cachecontrol.HeaderName
import play.shaded.ahc.org.asynchttpclient._

case class EffectiveURIKey(method: String, uri: URI) {
  override def toString: String = method + " " + uri.toString
}

object EffectiveURIKey {
  def apply(request: Request): EffectiveURIKey = {
    require(request != null)
    EffectiveURIKey(request.getMethod, request.getUri.toJavaNetURI)
  }
}


  def isExpired: Boolean = expiresAt.exists(_.toInstant.isBefore(Instant.now()))
} 
Example 49
Source File: package.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion

import scala.language.implicitConversions

import java.time.ZonedDateTime

import com.krux.hyperion.common.S3Uri
import com.krux.hyperion.expression.Duration

package object adt {

  // somehow the following does not work in all situations:
  // implicit def seqNative2SeqHType[B <: HType, A <% B](x: Seq[A]): Seq[B] = x.map(xx => xx: B)

  // since the generic one does not work we have to write all supported ones explicitly
  implicit def seqString2SeqHString(x: Seq[String]): Seq[HString] = x.map(xx => xx: HString)
  implicit def seqInt2SeqHInt(x: Seq[Int]): Seq[HInt] = x.map(xx => xx: HInt)
  implicit def seqDouble2SeqHDouble(x: Seq[Double]): Seq[HDouble] = x.map(xx => xx: HDouble)
  implicit def seqBoolean2SeqHBoolean(x: Seq[Boolean]): Seq[HBoolean] = x.map(xx => xx: HBoolean)
  implicit def seqDateTime2SeqHDateTime(x: Seq[ZonedDateTime]): Seq[HDateTime] = x.map(xx => xx: HDateTime)
  implicit def seqDuration2SeqHDuration(x: Seq[Duration]): Seq[HDuration] = x.map(xx => xx: HDuration)
  implicit def seqS3Uri2SeqHS3Uri(x: Seq[S3Uri]): Seq[HS3Uri] = x.map(xx => xx: HS3Uri)
  implicit def seqLong2SeqHLong(x: Seq[Long]): Seq[HLong] = x.map(xx => xx: HLong)

} 
Example 50
Source File: ScanObjectsModel.scala    From project-matt   with MIT License 5 votes vote down vote up
package org.datafy.aws.app.matt.models

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

import org.datafy.aws.app.matt.extras.{ElasticWrapper, RedisWrapper, S3KeySummary}
import org.slf4j.LoggerFactory
import io.circe._
import io.circe.generic.semiauto._
import io.circe.generic.auto._
import io.circe.syntax._

case class RiskStats(piiColumn: String, value: Int)

case class ObjectScanStats (
  s3Key: String,
  objectSummaryStats: List[RiskStats],
  classifier: String = "",
  scannedDate: Long =  System.currentTimeMillis()
)

case class FullScanStats (
  s3Bucket: String,
  lastScannedKey: String,
  summaryStats: List[RiskStats],
  objectScanStats: List[ObjectScanStats],
  classifier: String = "",
  scannedDate: Long =  System.currentTimeMillis(),
  totalObjectsSize: Option[Int] = None
)

object ScanObjectsModel {

  val logger = LoggerFactory.getLogger("ScanObjectsModel")

  def saveScannedResults(scanStats: FullScanStats) = {
    logger.info("attempting some saving here")

    val response = ElasticWrapper.saveDocument(scanStats)
    logger.info("Payload saved: some saving here")
    response
  }

  def getLastScannedFromRedis(key: String) = {
    val lastScannedKey = RedisWrapper.getData(key)
    lastScannedKey
  }

  def saveLastScannedToRedis(key: String, s3ObjectSummary: List[S3KeySummary]) = {
    RedisWrapper.setData(key, s3ObjectSummary.last.key)
    logger.info(s"Cached last scanned key: ${s3ObjectSummary.last.key} to Redis Server")
    s3ObjectSummary.last.key
  }

} 
Example 51
Source File: JavaTimeCodecTest.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec
import java.time.{Instant, ZonedDateTime}

import wvlet.airframe.codec.PrimitiveCodec.StringCodec
import wvlet.airframe.metrics.TimeParser
import wvlet.airframe.msgpack.spi.MessagePack
import wvlet.airframe.surface.Surface


class JavaTimeCodecTest extends CodecSpec {

  test("support ZonedDateTime") {
    roundtrip(Surface.of[ZonedDateTime], ZonedDateTime.now())
    roundtrip(Surface.of[ZonedDateTime], ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]"))

    val codec = MessageCodec.of[ZonedDateTime]
    val p     = MessagePack.newBufferPacker
    p.packString("non-date string")
    val v = codec.unpackMsgPack(p.toByteArray)
    v shouldBe empty
  }

  test("support java.util.Date") {
    val now = java.util.Date.from(Instant.now())
    roundtrip(Surface.of[java.util.Date], now)
  }

  test("parse various time strings in InstantCodec") {
    val timeStr = "2018-05-26 21:10:29-0800"
    val z       = TimeParser.parseAtLocalTimeZone(timeStr).get
    val i1      = z.toInstant

    val msgpack = StringCodec.toMsgPack(timeStr)
    val i2      = JavaInstantTimeCodec.fromMsgPack(msgpack)

    i1 shouldBe i2
  }
} 
Example 52
Source File: JavaTimeCodec.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec
import java.time.{Instant, ZonedDateTime}
import java.util.Date

import wvlet.airframe.msgpack.io.ByteArrayBuffer
import wvlet.airframe.msgpack.spi._
import wvlet.airframe.surface.Surface
import wvlet.log.LogSupport

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


object JavaTimeCodec {
  val javaTimeCodecs = Map(
    Surface.of[ZonedDateTime] -> ZonedDateTimeCodec,
    Surface.of[Date]          -> JavaUtilDateCodec
  )

  object ZonedDateTimeCodec extends MessageCodec[ZonedDateTime] {
    override def pack(p: Packer, v: ZonedDateTime): Unit = {
      // Use java standard ZonedDateTime string repr such as "2007-12-03T10:15:30+01:00[Europe/Paris]"
      p.packString(v.toString)
    }

    override def unpack(u: Unpacker, v: MessageContext): Unit = {
      val zonedDateTimeStr = u.unpackString
      Try(ZonedDateTime.parse(zonedDateTimeStr)) match {
        case Success(zd) =>
          v.setObject(zd)
        case Failure(e) =>
          v.setIncompatibleFormatException(
            this,
            s"${zonedDateTimeStr} cannot be read as ZonedDateTime: ${e.getMessage}"
          )
      }
    }
  }

} 
Example 53
Source File: LogTimestampFormatter.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.log

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


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

  val systemZone = ZoneId.systemDefault().normalized()
  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)
    .appendLiteral('.')
    .appendValue(MILLI_OF_SECOND, 3)
    .appendOffset("+HHMM", "Z")
    .toFormatter(Locale.US)

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

  def formatTimestampWithNoSpaace(timeMillis: Long): String = {
    val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), systemZone)
    noSpaceTimestampFormat.format(timestamp)
  }
} 
Example 54
Source File: TimeParserTest.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.metrics

import java.time.ZonedDateTime

import wvlet.airspec.AirSpec


class TimeParserTest extends AirSpec {
  private def parse(str: String, expected: String): Unit = {
    val z   = TimeParser.parse(str, UTC)
    val ans = ZonedDateTime.parse(expected)

    if (z.isEmpty) {
      warn(s"failed to parse ${str}")
    }
    z shouldBe defined

    TimeStampFormatter.formatTimestamp(z.get) shouldBe TimeStampFormatter.formatTimestamp(ans)
  }

  def `parse date time`: Unit = {
    // Time with time zone
    parse("2017-01-01 23:01:23-0700", "2017-01-01T23:01:23-07:00")
    parse("2017-01-01 23:01:23-07:00", "2017-01-01T23:01:23-07:00")
    parse("2017-01-01 00:00:00 UTC", "2017-01-01T00:00:00Z")
    parse("2017-01-01 01:23:45Z", "2017-01-01T01:23:45Z")
    parse("2017-01-01 01:23:45+0900", "2017-01-01T01:23:45+09:00")

    // PDT
    parse("2017-01-01 00:00:00 America/Los_Angeles", "2017-01-01T00:00:00-08:00")

    // PST
    parse("2017-05-01 00:00:00 America/Los_Angeles", "2017-05-01T00:00:00-07:00")

    // Date only strings
    // UTC
    parse("2017-01-01", "2017-01-01T00:00:00Z")
    parse("2016-12-01", "2016-12-01T00:00:00Z")

    // Datetime without time zone
    parse("2016-12-01 08:00:01", "2016-12-01T08:00:01Z")
    parse("2016-12-01 08:00:01", "2016-12-01T08:00:01Z")
  }
} 
Example 55
Source File: TimeStampFormatter.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.metrics

import java.time.format.{DateTimeFormatterBuilder, SignStyle}
import java.time.{Instant, ZoneOffset, ZonedDateTime}
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 = systemTimeZone): String = {
    val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), zone)
    humanReadableTimestampFormatter.format(timestamp)
  }

  def formatTimestampWithNoSpace(timeMillis: Long): String = {
    val timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), systemTimeZone)
    noSpaceTimestampFormat.format(timestamp)
  }
} 
Example 56
Source File: BqResultSetTest.scala    From scalikejdbc-bigquery   with Apache License 2.0 5 votes vote down vote up
package scalikejdbc.bigquery

import java.time.{LocalDate, LocalTime, ZoneId, ZonedDateTime}

import com.google.cloud.bigquery._
import org.scalatest.flatspec.AnyFlatSpec

class BqResultSetTest extends AnyFlatSpec {

  it should "be able to instantiate from null Schema" in {
    val tableResult = MockUtil.tableResultFromSeq(Nil, null)
    new BqResultSet(tableResult)
  }

  it should "correctly traversable" in {

    val row1 = Seq(BqParameter.String("first")).map(MockUtil.fieldValueFromParameter(_))
    val row2 = Seq(BqParameter.String("second")).map(MockUtil.fieldValueFromParameter(_))
    val row3 = Seq(BqParameter.String("third")).map(MockUtil.fieldValueFromParameter(_))

    val schema = Schema.of(Field.of("name", LegacySQLTypeName.STRING));
    val queryResult = MockUtil.tableResultFromSeq(Seq(row1, row2, row3), schema)

    val resultSet = new BqResultSet(queryResult)

    assert(resultSet.next())
    assert(resultSet.next())
    assert(resultSet.next())
    assert(!resultSet.next())
  }

  it should "correctly get value" in {

    val row = Seq(
      BqParameter.Int64(42L),
      BqParameter.Float64(3.14159),
      BqParameter.Bool(true),
      BqParameter.String("hello"),
      BqParameter.Bytes(Array[Byte](104, 101, 108, 108, 111)),
      BqParameter.Date(LocalDate.of(2017, 3, 22)),
//      BqParameter.DateTime
      BqParameter.Time(LocalTime.of(19, 58, 0, 0)),
      BqParameter.Timestamp(ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")))
    ).map(MockUtil.fieldValueFromParameter(_))

    val fields = Seq(
      Field.of("int64_column", LegacySQLTypeName.INTEGER),
      Field.of("float64_column", LegacySQLTypeName.FLOAT),
      Field.of("bool_column", LegacySQLTypeName.BOOLEAN),
      Field.of("string_column", LegacySQLTypeName.STRING),
      Field.of("bytes_column", LegacySQLTypeName.BYTES),
      Field.of("date_column", LegacySQLTypeName.STRING),
      Field.of("time_column", LegacySQLTypeName.STRING),
      Field.of("timestamp_column", LegacySQLTypeName.TIMESTAMP)
    )

    val schema = Schema.of(fields: _*)

    val queryResult = MockUtil.tableResultFromSeq(Seq(row), schema)

    val resultSet = new BqResultSet(queryResult)

    assert(resultSet.next())

    // int64
    assert(resultSet.getInt(0) == 42)
    assert(resultSet.getInt("int64_column") == 42)

    // float64
    assert(resultSet.getDouble(1) == 3.14159)
    assert(resultSet.getDouble("float64_column") == 3.14159)

    // bool
    assert(resultSet.getBoolean(2) == true)
    assert(resultSet.getBoolean("bool_column") == true)

    // string
    assert(resultSet.getString(3) == "hello")
    assert(resultSet.getString("string_column") == "hello")

    // bytes
    assert(resultSet.getBytes(4).sameElements(Array[Byte](104, 101, 108, 108, 111)))
    assert(resultSet.getBytes("bytes_column").sameElements(Array[Byte](104, 101, 108, 108, 111)))

    // date
    assert(resultSet.getDate(5).toLocalDate == LocalDate.of(2017, 3, 22))
    assert(resultSet.getDate("date_column").toLocalDate == LocalDate.of(2017, 3, 22))

    // time
    assert(resultSet.getTime(6).toLocalTime == LocalTime.of(19, 58, 0, 0))
    assert(resultSet.getTime("time_column").toLocalTime == LocalTime.of(19, 58, 0, 0))

    // timestamp
    assert(resultSet.getTimestamp(7).toInstant == ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")).toInstant)
    assert(resultSet.getTimestamp("timestamp_column").toInstant == ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")).toInstant)
  }
} 
Example 57
Source File: Post.scala    From scalikejdbc-bigquery   with Apache License 2.0 5 votes vote down vote up
package scalikejdbc.bigquery

import java.time.ZonedDateTime

import scalikejdbc._

case class PostId(value: Int) extends AnyVal

case class Post(
  id: PostId,
  body: String,
  postedAt: ZonedDateTime
)

case class PostWithTags(
  post: Post,
  tags: Seq[Tag]
)

object Post extends SQLSyntaxSupport[Post] {
  override val columns = Seq("id", "body", "posted_at")

  implicit val postIdBinders: Binders[PostId] = Binders.int.xmap(PostId.apply, _.value)

  val p = this.syntax("p")

  def apply(rs: WrappedResultSet): Post = apply(rs, p.resultName)
  def apply(rs: WrappedResultSet, rn: ResultName[Post]): Post = new Post(
    id = rs.get[PostId](rn.id),
    body = rs.get[String](rn.body),
    postedAt = rs.get[ZonedDateTime](rn.postedAt))
} 
Example 58
Source File: Generators.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres

import java.nio.charset.StandardCharsets
import java.time.{ZonedDateTime, _}
import java.time.temporal.JulianFields
import java.util.UUID

import org.scalacheck.{Arbitrary, Gen}
import Arbitrary.arbitrary
import com.twitter.finagle.postgres.values.Interval

object Generators {
  //need a more sensible BigDecimal generator, because ScalaCheck goes crazy with it and we can't even stringify them
  //this will be sufficient to test the decoder
  implicit val arbBD: Arbitrary[BigDecimal] = Arbitrary(for {
    precision <- Gen.choose(1, 32)
    scale <- Gen.choose(-precision, precision)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)))

  implicit val arbDate = Arbitrary[LocalDate](for {
    julian <- Gen.choose(1721060, 5373484)  //Postgres date parser doesn't like dates outside year range 0000-9999
  } yield LocalDate.now().`with`(JulianFields.JULIAN_DAY, julian))

  implicit val arbTime: Arbitrary[LocalTime] = Arbitrary[LocalTime](for {
    usec <- Gen.choose(0L, 24L * 60 * 60 * 1000000 - 1)
  } yield LocalTime.ofNanoOfDay(usec * 1000))

  implicit val arbInstant = Arbitrary[Instant](for {
    milli <- Gen.posNum[Long]
  } yield Instant.ofEpochMilli(milli))

  implicit val arbTimestamp = Arbitrary[LocalDateTime](for {
    milli <- Gen.posNum[Long]
  } yield LocalDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault()))

  implicit val arbTimestampTz = Arbitrary[ZonedDateTime](for {
    milli <- Gen.posNum[Long]
  } yield ZonedDateTime.ofInstant(Instant.ofEpochMilli(milli), ZoneId.systemDefault()))

  implicit val arbZoneOffset = Arbitrary(Gen.choose(-12, 12).map(ZoneOffset.ofHours))

  implicit val arbInterval = Arbitrary(for {
    months <- Gen.choose(-120, 120)
    years <- Gen.choose(-10, 10)
    days <- Gen.choose(-50, 50)
    hours <- Gen.choose(-50, 50)
    minutes <- Gen.choose(0, 59)
    seconds <- Gen.choose(0, 59)
  } yield Interval(
    Duration.ofSeconds(seconds).plusMinutes(minutes).plusHours(hours),
    Period.ofMonths(months).plusYears(years).plusDays(days)
  ))

  implicit val arbTimeTz = Arbitrary[OffsetTime](for {
    time <- arbitrary[LocalTime]
    offs <- arbitrary[ZoneOffset]
  } yield time.atOffset(offs))

  implicit val arbUUID = Arbitrary[UUID](Gen.uuid)

  // arbitrary string that only contains valid UTF-8 characters
  val utf8 = StandardCharsets.UTF_8.newEncoder()
  implicit val arbUTF8String = Arbitrary(arbitrary[String].filter {
    str => utf8.canEncode(str) && !str.contains('\u0000')
  })

  // TODO: can empty maps be supported?
  implicit val arbHStore: Arbitrary[Map[String, Option[String]]] = Arbitrary(
    Gen.mapOf(for {
      k <- Gen.identifier
      v <- Gen.oneOf(Gen.alphaStr.map(Some(_)), Gen.const(None))
    } yield (k, v)).suchThat(_.nonEmpty)
  )

  // postgres has slightly different precision rules, but that doesn't mean the decoder isn't working
  implicit val arbFloat = Arbitrary[Float](for {
    precision <- Gen.choose(1, 6)
    scale <- Gen.choose(-10, 10)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)).toFloat)

  implicit val arbDouble = Arbitrary[Double](for {
    precision <- Gen.choose(1, 15)
    scale <- Gen.choose(-20, 20)
    digits <- Gen.listOfN[Char](precision, Gen.numChar)
  } yield BigDecimal(BigDecimal(digits.mkString).bigDecimal.movePointLeft(scale)).toDouble)
} 
Example 59
Source File: AccessTokenSpec.scala    From tsec   with MIT License 5 votes vote down vote up
package tsec.oauth2.provider

import java.time.Instant
import java.time.{ZoneOffset, ZonedDateTime}

import cats.effect.IO

import scala.concurrent.duration._
import org.scalatest.Matchers._
import org.scalatest._

class AccessTokenSpec extends flatspec.AnyFlatSpec {

  it should "say a token is active that is not yet expired" in {
    val token = AccessToken("token", None, None, lifeTime = Some(15 seconds), createdAt = Instant.now())
    token.isExpired[IO].unsafeRunSync() shouldBe false
  }

  it should "expire tokens that have a lifespan that has passed" in {
    val token = AccessToken(
      "token",
      None,
      None,
      lifeTime = Some(1798 seconds),
      createdAt = ZonedDateTime.now(ZoneOffset.UTC).minusSeconds(1800).toInstant
    )
    token.isExpired[IO].unsafeRunSync() shouldBe true
  }

  it should "not expire tokens that have no lifespan" in {
    val token = AccessToken(
      "token",
      None,
      None,
      lifeTime = None,
      createdAt = ZonedDateTime.now(ZoneOffset.UTC).minusSeconds(1800).toInstant
    )
    token.isExpired[IO].unsafeRunSync() shouldBe false
  }
} 
Example 60
Source File: Reads.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion.cli

import com.krux.hyperion.Schedule
import com.krux.hyperion.expression.Duration
import java.time.{DayOfWeek, ZonedDateTime, ZoneOffset}
import scopt.Read._

object Reads {

  private lazy val daysOfWeek = Map(
    "monday" -> DayOfWeek.MONDAY,
    "tuesday" -> DayOfWeek.TUESDAY,
    "wednesday" -> DayOfWeek.WEDNESDAY,
    "thursday" -> DayOfWeek.THURSDAY,
    "friday" -> DayOfWeek.FRIDAY,
    "saturday" -> DayOfWeek.SATURDAY,
    "sunday" -> DayOfWeek.SUNDAY
  )

  private lazy val daysOfMonth = (1 to 31).flatMap { dom =>
    Seq(dom.toString -> dom, dom % 10 match {
      case 1 => s"${dom}st" -> dom
      case 2 => s"${dom}nd" -> dom
      case 3 => s"${dom}rd" -> dom
      case _ => s"${dom}th" -> dom
    })
  }.toMap

  implicit val durationRead: scopt.Read[Duration] = reads { x => Duration(x) }

  implicit val dateTimeRead: scopt.Read[ZonedDateTime] = reads { x =>
    val dt = x.toLowerCase match {
      case "now" | "today" => ZonedDateTime.now
      case "yesterday" => ZonedDateTime.now.minusDays(1)
      case "tomorrow" => ZonedDateTime.now.plusDays(1)
      case dow if daysOfWeek.keySet contains dow => ZonedDateTime.now.`with`(daysOfWeek(dow))
      case dom if daysOfMonth.keySet contains dom => ZonedDateTime.now.withDayOfMonth(daysOfMonth(dom))
      case d => ZonedDateTime.parse(d)
    }

    dt.withZoneSameInstant(ZoneOffset.UTC)
  }

  implicit val scheduleRead: scopt.Read[Schedule] = reads { x =>
    Schedule.cron.startDateTime(dateTimeRead.reads(x))
  }

} 
Example 61
Source File: Candle.scala    From scalanda   with MIT License 5 votes vote down vote up
package com.msilb.scalanda.restapi.model

import java.time.ZonedDateTime

import com.msilb.scalanda.common.util.DateUtils._
import spray.json.DefaultJsonProtocol

sealed trait Candle {
  def time: ZonedDateTime

  def volume: Int

  def complete: Boolean
}

object Candle {

  case class MidPointBasedCandle(time: ZonedDateTime,
                                 openMid: Double,
                                 highMid: Double,
                                 lowMid: Double,
                                 closeMid: Double,
                                 volume: Int,
                                 complete: Boolean) extends Candle

  case class BidAskBasedCandle(time: ZonedDateTime,
                               openBid: Double,
                               highBid: Double,
                               lowBid: Double,
                               closeBid: Double,
                               openAsk: Double,
                               highAsk: Double,
                               lowAsk: Double,
                               closeAsk: Double,
                               volume: Int,
                               complete: Boolean) extends Candle

  object CandleJsonProtocol extends DefaultJsonProtocol {
    implicit val midPointBasedCandleFormat = jsonFormat7(MidPointBasedCandle)
    implicit val bidAskBasedCandleFormat = jsonFormat11(BidAskBasedCandle)
  }

} 
Example 62
Source File: Parameters.scala    From flint   with Apache License 2.0 5 votes vote down vote up
package com.twosigma.flint.timeseries.io.read

import java.time.{ Instant, ZonedDateTime, ZoneOffset }
import javax.annotation.Nullable

import scala.collection.mutable

import com.twosigma.flint.annotation.PythonApi

private[read] class Parameters private (
  val extraOptions: mutable.Map[String, String],
  var range: BeginEndRange = BeginEndRange(None, None, None, None)
) extends Serializable {

  def this(defaultOptions: Map[String, String]) =
    this(mutable.HashMap[String, String](defaultOptions.toSeq: _*))

  def option(key: String, valueOpt: Option[String]): Unit = valueOpt match {
    case Some(v) => extraOptions += key -> v
    case None => extraOptions -= key
  }

  
  @PythonApi
  private[read] def extraOptionsAsJavaMap: java.util.Map[String, String] = {
    import scala.collection.JavaConverters._
    extraOptions.asJava
  }

}

private[read] case class BeginEndRange(
  rawBeginNanosOpt: Option[Long] = None,
  rawEndNanosOpt: Option[Long] = None,
  expandBeginNanosOpt: Option[Long] = None,
  expandEndNanosOpt: Option[Long] = None
) {

  def beginNanos: Long = beginNanosOpt.getOrElse(
    throw new IllegalArgumentException("'begin' range must be set")
  )

  def endNanos: Long = endNanosOpt.getOrElse(
    throw new IllegalArgumentException("'end' range must be set")
  )

  def beginNanosOpt: Option[Long] = {
    rawBeginNanosOpt.map(_ - expandBeginNanosOpt.getOrElse(0L))
  }

  def endNanosOpt: Option[Long] = {
    rawEndNanosOpt.map(_ + expandEndNanosOpt.getOrElse(0L))
  }

  @PythonApi
  private[read] def beginNanosOrNull: java.lang.Long = beginNanosOpt.map(Long.box).orNull

  @PythonApi
  private[read] def endNanosOrNull: java.lang.Long = endNanosOpt.map(Long.box).orNull
} 
Example 63
package sample.stream

import java.time.{Instant, ZoneId, ZonedDateTime}

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.scaladsl._
import akka.stream.{DelayOverflowStrategy, ThrottleMode}

import scala.concurrent.duration._
import scala.util.Failure

case class SourceEvent(id: Integer)

case class DomainEvent(id: Integer, timeDate: ZonedDateTime)



object SlowConsumerDropsElementsOnFastProducer extends App {
  implicit val system = ActorSystem("SlowConsumerDropsElementsOnFastProducer")
  implicit val ec = system.dispatcher

  val fastSource: Source[SourceEvent, NotUsed] =
    Source(1 to 500)
      .throttle(10, 1.second, 1, ThrottleMode.shaping)
      .map { i =>
        println(s"Producing event: $i")
        SourceEvent(i)
      }

  val droppyStream: Flow[SourceEvent, SourceEvent, NotUsed] =
  //Conflate is "rate aware", it combines/aggregates elements from upstream while downstream backpressures
  //The reducer function here takes the freshest element. This in a simple dropping operation.
    Flow[SourceEvent]
      .conflate((lastEvent, newEvent) => newEvent)

  val enrichWithTimestamp: Flow[SourceEvent, DomainEvent, NotUsed] =
    Flow[SourceEvent]
      .map { e =>
        val instant = Instant.ofEpochMilli(System.currentTimeMillis())
        val zonedDateTimeUTC: ZonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"))
        DomainEvent(e.id, zonedDateTimeUTC)
      }

  val terminationHook: Flow[DomainEvent, DomainEvent, Unit] = Flow[DomainEvent]
    .watchTermination() { (_, done) =>
      done.onComplete {
        case Failure(err) => println(s"Flow failed: $err")
        case _ => system.terminate(); println(s"Flow terminated")
      }
    }

  val slowSink: Sink[DomainEvent, NotUsed] =
    Flow[DomainEvent]
      //.buffer(100, OverflowStrategy.backpressure)
      .delay(10.seconds, DelayOverflowStrategy.backpressure)
      .to(Sink.foreach(e => println(s"Reached Sink: $e")))

  fastSource
    .via(droppyStream)
    .via(enrichWithTimestamp)
    .via(terminationHook)
    .runWith(slowSink)
} 
Example 64
Source File: JVMZonedDateTimeTests.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

import java.time.temporal.ChronoUnit
import java.time.{Duration, ZonedDateTime}

import cats.instances.option._
import cats.kernel.laws.discipline.OrderTests
import com.fortysevendeg.scalacheck.datetime.jdk8.ArbitraryJdk8
import dtc.{Offset, Zoned}
import dtc.laws.{DateTimeTests, ProviderTests, ZonedDateTimeTestData, ZonedDateTimeTests}
import dtc.syntax.timeZone._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Cogen, Gen}
import dtc.instances.providers.realZonedDateTimeProvider

abstract class JVMZonedDateTimeTests(instance: Zoned[ZonedDateTime]) extends DTCSuiteJVM {

  implicit val zonedInstance: Zoned[ZonedDateTime] = instance

  implicit val arbT: Arbitrary[ZonedDateTime] = ArbitraryJdk8.arbZonedDateTimeJdk8
  implicit val cogenT: Cogen[ZonedDateTime] = Cogen(_.toEpochSecond)

  val overflowSafePairGen: Gen[(ZonedDateTime, Duration)] = for {
    dt <- arbitrary[ZonedDateTime]
    dur <- arbitrary[Duration]
  } yield (dt, dur)

  def genDateFromPeriod(period: SameZoneOffsetPeriod): Gen[ZonedDateTime] =
    genDateTimeFromSameOffsetPeriod(period).map(tpl => ZonedDateTime.of(tpl._1, tpl._2, tpl._3.zoneId))

  val overflowSafePairGenWithinSameOffset: Gen[(ZonedDateTime, Duration)] = for {
    period <- arbitrary[SameZoneOffsetPeriod]
    dateTime <- genDateFromPeriod(period)
    duration <- genDateFromPeriod(period)
      .map(other => dateTime.until(other, ChronoUnit.NANOS))
      .map(Duration.ofNanos)
  } yield (dateTime, duration)

  val genZonedTestDataSuite: Gen[ZonedDateTimeTestData[ZonedDateTime]] =
    overflowSafePairGen.map {
      case (date, duration) =>
        val target = date.plus(duration)
        ZonedDateTimeTestData(date, duration,
          Offset(date.plus(duration).getOffset.getTotalSeconds), target.toLocalTime, target.toLocalDate)
    }

  checkAll("java.time.ZonedDateTime", DateTimeTests[ZonedDateTime](overflowSafePairGen).dateTime)
  checkAll("java.time.ZonedDateTime", ZonedDateTimeTests[ZonedDateTime](
    overflowSafePairGenWithinSameOffset,
    genZonedTestDataSuite,
    genYear,
    genTimeZone
  ).zonedDateTime)
  checkAll("java.time.ZonedDateTime", OrderTests[ZonedDateTime].order)
  checkAll("java.time.ZonedDateTime", OrderTests[ZonedDateTime].partialOrder)
  checkAll("java.time.ZonedDateTime", OrderTests[ZonedDateTime].eqv)

  checkAll("java.time.ZonedDateTime", ProviderTests[ZonedDateTime](genTimeZone).provider)
}

class ZonedDateTimeWithStrictEqualityTests
  extends JVMZonedDateTimeTests(dtc.instances.zonedDateTime.zonedDateTimeWithStrictEquality)

class ZonedDateTimeWithCrossZoneEqualityTests
  extends JVMZonedDateTimeTests(dtc.instances.zonedDateTime.zonedDateTimeWithCrossZoneEquality) 
Example 65
Source File: ZonedDateTimeEqualityTest.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.tests

import java.time.{Instant, ZoneId, ZonedDateTime}

import org.scalatest.matchers.should.Matchers
import org.scalatest.funsuite.AnyFunSuiteLike

class ZonedDateTimeEqualityTest extends AnyFunSuiteLike with Matchers {

  private val instant = 1431231233567L
  private val x = ZonedDateTime.ofInstant(Instant.ofEpochMilli(instant), ZoneId.of("Canada/Pacific"))
  private val y = ZonedDateTime.ofInstant(Instant.ofEpochMilli(instant), ZoneId.of("America/Vancouver"))

  test("strict equality") {
    dtc.instances.zonedDateTime.zonedDateTimeWithStrictEquality.eqv(x, y) shouldBe false
  }

  test("cross-zone equality") {
    dtc.instances.zonedDateTime.zonedDateTimeWithCrossZoneEquality.eqv(x, y) shouldBe true
  }
} 
Example 66
Source File: DTVersions.scala    From Converter   with GNU General Public License v3.0 5 votes vote down vote up
package org.scalablytyped.converter.internal
package importer

import java.net.URI
import java.time.{Instant, ZonedDateTime}

import ammonite.ops.%%
import org.scalablytyped.converter.internal.ts.{CalculateLibraryVersion, PackageJsonDeps}

import scala.util.matching.Regex
import scala.util.{Success, Try}

class DTVersions(lastChangedIndex: DTLastChangedIndex) extends CalculateLibraryVersion {
  val GitAtGithubDotCom: Regex = s"[email protected]:(.*)".r

  def uri(uriString: String): URI =
    uriString match {
      case GitAtGithubDotCom(path) => new URI(s"https://github.com/$path")
      case other                   => new URI(other)
    }

  override def apply(
      sourceFolder:   InFolder,
      isStdLib:       Boolean,
      packageJsonOpt: Option[PackageJsonDeps],
      comments:       Comments,
  ): LibraryVersion = {

    implicit val wd = sourceFolder.path

    val libraryVersion = packageJsonOpt.flatMap(_.version) orElse DefinitelyTypedVersion.from(comments)

    val inGit: Option[InGit] =
      Try(uri((%% git ('remote, "get-url", 'origin)).out.string.trim)) match {
        case Success(constants.ConverterRepo) =>
          None
        case Success(uri) =>
          val lastModified = ZonedDateTime.ofInstant(
            Instant.ofEpochSecond(lastChangedIndex(sourceFolder.path.toIO)),
            constants.TimeZone,
          )
          Some(InGit(uri, uri === constants.DefinitelyTypedRepo, lastModified))
        case _ => None
      }

    LibraryVersion(isStdLib, libraryVersion, inGit)
  }

  
  private object DefinitelyTypedVersion {
    private val Version = "^\\/\\/ Type definitions for .+ ([a-zA-Z\\d][a-zA-Z\\d.\\-]*)$".r

    def from(comments: Comments): Option[String] = {
      val lines = comments.rawCs.flatMap(_.split("\n"))
      lines.collectFirst {
        case Version(v) if v.exists(_.isDigit) => v
      }
    }
  }
} 
Example 67
Source File: WaitForTaskDsl.scala    From algoliasearch-client-scala   with MIT License 5 votes vote down vote up
package algolia.dsl

import java.time.ZonedDateTime
import java.util.concurrent.{Executors, ThreadFactory, TimeUnit}

import algolia.definitions.{WaitForTaskDefinition, WaitForTimeoutException}
import algolia.responses.{AlgoliaTask, TaskStatus}
import algolia.{AlgoliaClient, Executable}
import io.netty.util.{HashedWheelTimer, Timeout, TimerTask}

import scala.concurrent.{ExecutionContext, Future, Promise}

trait WaitForTaskDsl {

  case object waitFor {
    def task(task: AlgoliaTask): WaitForTaskDefinition =
      WaitForTaskDefinition(task.idToWaitFor)

    def task(taskID: Long): WaitForTaskDefinition =
      WaitForTaskDefinition(taskID)
  }

  implicit object WaitForTaskDefinitionExecutable
      extends Executable[WaitForTaskDefinition, TaskStatus] {

    // Run every 100 ms, use a wheel with 512 buckets
    private lazy val timer = {
      val threadFactory = new ThreadFactory {
        override def newThread(r: Runnable): Thread = {
          val t = Executors.defaultThreadFactory().newThread(r)
          t.setDaemon(true)
          t.setName("algolia-waitfor-thread-" + ZonedDateTime.now())
          t
        }
      }
      new HashedWheelTimer(threadFactory, 100, TimeUnit.MILLISECONDS, 512)
    }

    
    override def apply(client: AlgoliaClient, query: WaitForTaskDefinition)(
        implicit executor: ExecutionContext
    ): Future[TaskStatus] = {

      def request(d: Long, totalDelay: Long): Future[TaskStatus] =
        delay[TaskStatus](d) {
          client.request[TaskStatus](query.build())
        }.flatMap { res =>
          if (res.status == "published") {
            Future.successful(res)
          } else if (totalDelay > query.maxDelay) {
            Future.failed(
              WaitForTimeoutException(
                s"Waiting for task `${query.taskId}` on index `${query.index.get}` timeout after ${d}ms"
              )
            )
          } else {
            request(d * 2, totalDelay + d)
          }
        }

      request(query.baseDelay, 0L)
    }

    private def delay[T](delay: Long)(block: => Future[T]): Future[T] = {
      val promise = Promise[T]()
      val task = new TimerTask {
        override def run(timeout: Timeout): Unit = promise.completeWith(block)
      }
      timer.newTimeout(task, delay, TimeUnit.MILLISECONDS)
      promise.future
    }
  }

} 
Example 68
Source File: Status.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package it.almawave.kb.http.endpoints

import java.time.LocalTime
import io.swagger.annotations.Api
import javax.ws.rs.Path
import javax.ws.rs.GET
import javax.ws.rs.Produces
import io.swagger.annotations.ApiOperation
import javax.ws.rs.core.MediaType
import org.slf4j.LoggerFactory
import javax.ws.rs.core.Context
import javax.ws.rs.core.UriInfo
import javax.ws.rs.core.Request
import it.almawave.linkeddata.kb.utils.JSONHelper
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.time.ZoneId

@Api(tags = Array("catalog"))
@Path("/status")
class Status {

  private val logger = LoggerFactory.getLogger(this.getClass)

  @Context
  var uriInfo: UriInfo = null

  @GET
  @Produces(Array(MediaType.APPLICATION_JSON))
  @ApiOperation(nickname = "status", value = "endpoint status")
  def status() = {

    val base_uri = uriInfo.getBaseUri
    val msg = s"the service is running at ${base_uri}"
    logger.info(msg)

    val _now = now()
    StatusMsg(_now._1, _now._2, msg)

  }

  def now() = {

    val zdt = ZonedDateTime.now(ZoneId.of("+1"))
    val dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ")

    (zdt.format(dtf), zdt)

  }

}

case class StatusMsg(
  now:      String,
  dateTime: ZonedDateTime,
  msg:      String
) 
Example 69
Source File: YahooFinanceSpec.scala    From YahooFinanceScala   with MIT License 5 votes vote down vote up
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 = Vector("MSFT", "IBM")
    val valids = Await.result(yahooFinance.fundamentals(syms), Duration.Inf)
    valids must have size(2)
    valids.foreach { x ⇒
      x.looksValid must beTrue
      x.name must not beEmpty
    }
    valids.map { _.symbol } must contain(exactly(syms:_*))
    ok
  }
} 
Example 70
Source File: QuoteParser.scala    From YahooFinanceScala   with MIT License 5 votes vote down vote up
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
} 
Example 71
Source File: GenerateLogFile.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.stream

import java.nio.file.{ Path, Paths }
import java.nio.file.StandardOpenOption
import java.nio.file.StandardOpenOption._
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

import scala.concurrent.Future

import akka.actor.ActorSystem
import akka.stream.{ ActorMaterializer, IOResult }
import akka.stream.scaladsl._
import akka.util.ByteString

object GenerateLogFile extends App {
  val filePath = args(0)
  val numberOfLines = args(1).toInt
  val rnd = new java.util.Random()
  val sink = FileIO.toPath(FileArg.shellExpanded(filePath), Set(CREATE, WRITE, APPEND))
  def line(i: Int) = {
    val host = "my-host"
    val service = "my-service"
    val time = ZonedDateTime.now.format(DateTimeFormatter.ISO_INSTANT)
    val state = if( i % 10 == 0) "warning" 
      else if(i % 101 == 0) "error" 
      else if(i % 1002 == 0) "critical"
      else "ok"
    val description = "Some description of what has happened."
    val tag = "tag"
    val metric = rnd.nextDouble() * 100
    s"$host | $service | $state | $time | $description | $tag | $metric \n"
  }

  val graph = Source.fromIterator{() => 
    Iterator.tabulate(numberOfLines)(line)
  }.map(l=> ByteString(l)).toMat(sink)(Keep.right)

  implicit val system = ActorSystem() 
  implicit val ec = system.dispatcher
  implicit val materializer = ActorMaterializer()

  graph.run().foreach { result =>
    println(s"Wrote ${result.count} bytes to '$filePath'.")
    system.terminate()
  }  
} 
Example 72
Source File: SimpleTimeServiceBackendSpec.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.platform.apiserver

import java.time.{Instant, ZoneOffset, ZonedDateTime}

import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{Matchers, WordSpec}

class SimpleTimeServiceBackendSpec extends WordSpec with Matchers with ScalaFutures {
  "a simple time service backend" should {
    "return the time it started with" in {
      val timeService = TimeServiceBackend.simple(instantAt(month = 1))
      timeService.getCurrentTime should be(instantAt(month = 1))
    }

    "update the time to a new time" in {
      val timeService = TimeServiceBackend.simple(instantAt(month = 1))
      timeService.setCurrentTime(instantAt(month = 1), instantAt(month = 2))
      timeService.getCurrentTime should be(instantAt(month = 2))
    }

    "not allow the time to be updated without a correct expected time" in {
      val timeService = TimeServiceBackend.simple(instantAt(month = 1))
      whenReady(timeService.setCurrentTime(instantAt(month = 1), instantAt(month = 2))) {
        _ should be(true)
      }
      whenReady(timeService.setCurrentTime(instantAt(month = 1), instantAt(month = 3))) {
        _ should be(false)
      }
      timeService.getCurrentTime should be(instantAt(month = 2))
    }
  }

  // always construct new instants to avoid sharing references, which would allow us to cheat when
  // comparing them inside the SimpleTimeServiceBackend
  private def instantAt(month: Int): Instant =
    ZonedDateTime.of(2020, month, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant
} 
Example 73
Source File: DateTimeIndexUtilsSuite.scala    From spark-timeseries   with Apache License 2.0 5 votes vote down vote up
package com.cloudera.sparkts

import java.time.{ZonedDateTime, ZoneId}

import com.cloudera.sparkts.DateTimeIndex._
import org.scalatest.{FunSuite, ShouldMatchers}

class DateTimeIndexUtilsSuite extends FunSuite with ShouldMatchers {
  val UTC = ZoneId.of("Z")

  test("non-overlapping sorted") {
    val index1: DateTimeIndex = uniform(dt("2015-04-10"), 5, new DayFrequency(2), UTC)
    val index2: DateTimeIndex = uniform(dt("2015-05-10"), 5, new DayFrequency(2), UTC)
    val index3: DateTimeIndex = irregular(Array(
      dt("2015-06-10"),
      dt("2015-06-13"),
      dt("2015-06-15"),
      dt("2015-06-20"),
      dt("2015-06-25")
    ), UTC)

    DateTimeIndexUtils.union(Array(index1, index2, index3), UTC) should be (
      hybrid(Array(index1, index2, index3)))
  }

  test("non-overlapping non-sorted") {
    val index1: DateTimeIndex = uniform(dt("2015-04-10"), 5, new DayFrequency(2), UTC)
    val index2: DateTimeIndex = uniform(dt("2015-05-10"), 5, new DayFrequency(2), UTC)
    val index3: DateTimeIndex = irregular(Array(
      dt("2015-06-10"),
      dt("2015-06-13"),
      dt("2015-06-15"),
      dt("2015-06-20"),
      dt("2015-06-25")
    ), UTC)

    DateTimeIndexUtils.union(Array(index3, index1, index2), UTC) should be (
      hybrid(Array(index1, index2, index3)))
  }

  test("overlapping uniform and irregular") {
    val index1: DateTimeIndex = uniform(dt("2015-04-10"), 5, new DayFrequency(2), UTC)
    val index2: DateTimeIndex = uniform(dt("2015-05-10"), 5, new DayFrequency(2), UTC)
    val index3: DateTimeIndex = irregular(Array(
      dt("2015-04-09"),
      dt("2015-04-11"),
      dt("2015-05-01"),
      dt("2015-05-10"),
      dt("2015-06-25")
    ), UTC)

    DateTimeIndexUtils.union(Array(index3, index1, index2), UTC) should be (
      hybrid(Array(
        irregular(Array(
          dt("2015-04-09"),
          dt("2015-04-10"),
          dt("2015-04-11")), UTC),
        uniform(dt("2015-04-12"), 4, new DayFrequency(2), UTC),
        irregular(Array(dt("2015-05-01"),
          dt("2015-05-10")), UTC),
        uniform(dt("2015-05-12"), 4, new DayFrequency(2), UTC),
        irregular(Array(dt("2015-06-25")), UTC)
      )))
  }

  def dt(dt: String, zone: ZoneId = UTC): ZonedDateTime = {
    val splits = dt.split("-").map(_.toInt)
    ZonedDateTime.of(splits(0), splits(1), splits(2), 0, 0, 0, 0, zone)
  }
} 
Example 74
Source File: Simple_JSON_Example.scala    From fintrospect   with Apache License 2.0 5 votes vote down vote up
package cookbook.core


// fintrospect-core
object Simple_JSON_Example extends App {

  import java.time.ZonedDateTime

  import argo.jdom.JsonNode
  import com.twitter.finagle.http.Method.Post
  import com.twitter.finagle.http.path.Root
  import com.twitter.finagle.http.{Request, Response}
  import com.twitter.finagle.{Http, Service}
  import com.twitter.util.Await.ready
  import io.fintrospect.formats.Argo.JsonFormat._
  import io.fintrospect.formats.Argo.ResponseBuilder._
  import io.fintrospect.parameters.Body
  import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute}

  val json: Body[JsonNode] = Body.json()

  val echo: Service[Request, Response] = Service.mk[Request, Response] { req =>
    val requestJson: JsonNode = json <-- req
    val responseJson: JsonNode = obj(
      "posted" -> requestJson,
      "time" -> string(ZonedDateTime.now().toString)
    )
    Ok(responseJson)
  }

  val route: ServerRoute[Request, Response] = RouteSpec().body(json).at(Post) bindTo echo

  val module: Module = RouteModule(Root).withRoute(route)

  ready(Http.serve(":9999", module.toService))
}

//curl -v -XPOST http://localhost:9999/ --data '{"name":"David"}' 
Example 75
Source File: PubSubMessage.scala    From akka-cloudpubsub   with Apache License 2.0 5 votes vote down vote up
package com.qubit.pubsub.client

import java.time.{Instant, ZoneOffset, ZonedDateTime}

import com.google.protobuf.{ByteString, Timestamp}
import com.google.pubsub.v1.{
  PubsubMessage => PubSubMessageProto,
  ReceivedMessage => ReceivedPubSubMessageProto
}

import scala.collection.JavaConversions._

final case class PubSubMessage(
    payload: Array[Byte],
    msgId: Option[String] = None,
    publishTs: Option[ZonedDateTime] = None,
    attributes: Option[Map[String, String]] = None) {
  def toProto: PubSubMessageProto = {
    val builder = PubSubMessageProto.newBuilder()
    builder.setData(ByteString.copyFrom(payload))
    publishTs.foreach(
      ts =>
        builder.setPublishTime(
          Timestamp.newBuilder().setSeconds(ts.toEpochSecond).build()))
    msgId.foreach(id => builder.setMessageId(id))
    attributes.foreach(attr => builder.putAllAttributes(attr))
    builder.build()
  }
}

object PubSubMessage {
  def fromProto(proto: PubSubMessageProto): PubSubMessage = {
    val payload = proto.getData.toByteArray
    val msgId = Some(proto.getMessageId)
    val attributes = if (proto.getAttributesMap.isEmpty) { None } else {
      Some(proto.getAttributesMap.toMap)
    }
    val publishTs = if (proto.hasPublishTime) {
      Some(
        ZonedDateTime.ofInstant(
          Instant.ofEpochSecond(proto.getPublishTime.getSeconds),
          ZoneOffset.UTC))
    } else {
      None
    }

    PubSubMessage(payload,
                  msgId = msgId,
                  publishTs = publishTs,
                  attributes = attributes)
  }
}

final case class ReceivedPubSubMessage(ackId: String, payload: PubSubMessage)

object ReceivedPubSubMessage {
  def fromProto(proto: ReceivedPubSubMessageProto): ReceivedPubSubMessage = {
    val ackId = proto.getAckId
    val payload = PubSubMessage.fromProto(proto.getMessage)
    ReceivedPubSubMessage(ackId, payload)
  }
} 
Example 76
Source File: UserManagementModel.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package models

import java.time.ZonedDateTime
import java.util.UUID

import play.api.libs.json.Json

case class UserManagementModel(id: UUID,
                               firstName: Option[String],
                               lastName: Option[String],
                               email: Option[String],
                               roleId: Int,
                               confirmed: Boolean,
                               signedUpAt: ZonedDateTime,
                               credentialsProvider: Boolean,
                               googleProvider: Boolean,
                               facebookProvider: Boolean,
                               twitterProvider: Boolean)

object UserManagementModel {
  implicit val w = Json.writes[UserManagementModel]
} 
Example 77
Source File: MockVersions.scala    From eidos   with Apache License 2.0 5 votes vote down vote up
package org.clulab.wm.eidos.groundings

import java.time.ZonedDateTime

case class MockVersion(commit: String, date: ZonedDateTime)

object MockVersions {
  val codeDir = "src/main/resources"
  val ontologyDir = codeDir + "/org/clulab/wm/eidos/english/ontologies/"

  // This first value applies to the entire repository.
  val version: Option[MockVersion] = Some(MockVersion("2db42aa7c62d9b3b4cf99a08ec393121e53ce5cd", ZonedDateTime.parse("2019-10-07T17:00:49-07:00"))) // 2019-10-04T20:49:00Z")))

  // These values are for individual files.
  val versions: Map[String, Option[MockVersion]] = Map(
    ontologyDir + "un_ontology.yml" -> Some(MockVersion("8c3d191c837e973a9ebfacaa78d3a96ab1701981", ZonedDateTime.parse("2019-10-04T17:18:20Z"))),
    ontologyDir + "interventions.yml" -> Some(MockVersion("9fc7e0860cf54b7b54378bf3b73efe6e68e4e10b", ZonedDateTime.parse("2019-07-09T12:49:08Z")))
  )
} 
Example 78
Source File: DomainHandler.scala    From eidos   with Apache License 2.0 5 votes vote down vote up
package org.clulab.wm.eidos.groundings

import java.time.ZonedDateTime

import com.github.clulab.eidos.Version
import com.github.clulab.eidos.Versions
import com.github.worldModelers.ontologies.{Versions => AwayVersions}
import org.clulab.wm.eidos.SentencesExtractor
import org.clulab.wm.eidos.groundings.ontologies.FullTreeDomainOntology.FullTreeDomainOntologyBuilder
import org.clulab.wm.eidos.groundings.OntologyHandler.serializedPath
import org.clulab.wm.eidos.groundings.ontologies.CompactDomainOntology
import org.clulab.wm.eidos.groundings.ontologies.FastDomainOntology
import org.clulab.wm.eidos.groundings.ontologies.HalfTreeDomainOntology.HalfTreeDomainOntologyBuilder
import org.clulab.wm.eidos.utils.Canonicalizer
import org.clulab.wm.eidos.utils.StringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

object DomainHandler {
  protected lazy val logger: Logger = LoggerFactory.getLogger(getClass)

  // The intention is to stop the proliferation of the generated Version class to this single method.
  protected def getVersionOpt(ontologyPath: String): (Option[String], Option[ZonedDateTime]) = {
    // This should work for local ontologies.  Absolute
    val goodVersionOpt = Versions.versions.get(MockVersions.codeDir + ontologyPath)
    // See what might have come from WordModelers/Ontologies
    val bestVersionOpt = goodVersionOpt.getOrElse {
      // These are always stored in top level directory.
      val awayVersionOpt = AwayVersions.versions.get(StringUtils.afterLast(ontologyPath, '/')).getOrElse(None)
      val homeVersionOpt = awayVersionOpt.map { awayVersion => Version(awayVersion.commit, awayVersion.date) }

      homeVersionOpt
    }

    if (bestVersionOpt.isDefined)
      (Some(bestVersionOpt.get.commit), Some(bestVersionOpt.get.date))
    else
      (None, None)
  }

  def apply(ontologyPath: String, serializedPath: String, sentencesExtractor: SentencesExtractor,
      canonicalizer: Canonicalizer, filter: Boolean = true, useCacheForOntologies: Boolean = false,
      includeParents: Boolean = false): DomainOntology = {

    // As coded below, when parents are included, the FullTreeDomainOntology is being used.
    // The faster loading version is the FastDomainOntology.
    // If parents are not included, as had traditionally been the case, the HalfTreeDomainOntology suffices.
    // Being smaller and faster, it is preferred.  The faster loading counterpart is CompactDomainOntology.
    if (includeParents) {
      if (useCacheForOntologies) {
        logger.info(s"Processing cached yml ontology with parents from $serializedPath...")
        FastDomainOntology.load(serializedPath)
      }
      else {
        logger.info(s"Processing yml ontology with parents from $ontologyPath...")
        val (versionOpt, dateOpt) = getVersionOpt(ontologyPath)
        new FullTreeDomainOntologyBuilder(sentencesExtractor, canonicalizer, filter).buildFromPath(ontologyPath, versionOpt, dateOpt)
      }
    }
    else {
      if (useCacheForOntologies) {
        logger.info(s"Processing cached yml ontology without parents from $serializedPath...")
        CompactDomainOntology.load(serializedPath)
      }
      else {
        logger.info(s"Processing yml ontology without parents from $ontologyPath...")
        val (versionOpt, dateOpt) = getVersionOpt(ontologyPath)
        new HalfTreeDomainOntologyBuilder(sentencesExtractor, canonicalizer, filter).buildFromPath(ontologyPath, versionOpt, dateOpt)
      }
    }
  }

  def mkDomainOntology(name: String, ontologyPath: String, sentenceExtractor: SentencesExtractor,
      canonicalizer: Canonicalizer, cacheDir: String, useCacheForOntologies: Boolean,
      includeParents: Boolean): DomainOntology = {
    val ontSerializedPath: String = serializedPath(name, cacheDir, includeParents)

    DomainHandler(ontologyPath, ontSerializedPath, sentenceExtractor, canonicalizer: Canonicalizer, filter = true,
        useCacheForOntologies = useCacheForOntologies, includeParents = includeParents)
  }
} 
Example 79
Source File: OntologyGrounder.scala    From eidos   with Apache License 2.0 5 votes vote down vote up
package org.clulab.wm.eidos.groundings

import java.time.ZonedDateTime

import org.clulab.wm.eidos.groundings.OntologyAliases._
import org.clulab.wm.eidos.mentions.EidosMention
import org.clulab.wm.eidos.utils.Namer

object OntologyAliases {
  type SingleOntologyGrounding = (Namer, Float)
  type MultipleOntologyGrounding = Seq[SingleOntologyGrounding]
  // The first string is the name, something like wm or un.  The second is a branch/category.
  type OntologyGroundings = Map[String, OntologyGrounding]
}

case class OntologyGrounding(version: Option[String], date: Option[ZonedDateTime], grounding: MultipleOntologyGrounding = Seq.empty, branch: Option[String] = None) {
  def nonEmpty: Boolean = grounding.nonEmpty
  def take(n: Int): MultipleOntologyGrounding = grounding.take(n)
  def headOption: Option[SingleOntologyGrounding] = grounding.headOption
  def headName: Option[String] = headOption.map(_._1.name)
}

trait OntologyGrounder {
  def name: String
  def domainOntology: DomainOntology
  def groundOntology(mention: EidosMention, topN: Option[Int], threshold: Option[Float]): Seq[OntologyGrounding]
  def groundStrings(strings: Array[String]): Seq[OntologyGrounding]
} 
Example 80
Source File: BlockStampTest.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol

import java.time.{ZoneId, ZonedDateTime}

import org.bitcoins.core.protocol.BlockStamp.{BlockHash, BlockHeight, BlockTime}
import org.bitcoins.crypto.DoubleSha256DigestBE
import org.bitcoins.testkit.util.BitcoinSUnitTest

import scala.util.Success

class BlockStampTest extends BitcoinSUnitTest {

  it must "format and parse its string representation" in {
    val blockHeight = BlockHeight(0xc0de)
    assert(blockHeight.mkString == "49374")
    assert(BlockStamp.fromString(blockHeight.mkString) == blockHeight)

    val hex = "000102030405060708090a0b0c0d0e0f00112233445566778899aabbccddeeff"
    val blockHash = BlockHash(DoubleSha256DigestBE.fromHex(hex))
    assert(blockHash.mkString == hex)
    assert(BlockStamp.fromString(blockHash.mkString) == blockHash)

    val hex1 = DoubleSha256DigestBE.empty.hex
    val blockHash1 = BlockHash(DoubleSha256DigestBE.fromHex(hex1))
    assert(blockHash1.mkString == hex1)
    assert(BlockStamp.fromString(blockHash1.mkString) == blockHash1)

    val time =
      ZonedDateTime.of(2089, 4, 15, 16, 25, 37, 0, ZoneId.of("UTC"))
    val blockTime = BlockTime(time)
    assert(blockTime.mkString == "2089-04-15T16:25:37Z")
    assert(BlockStamp.fromString(blockTime.mkString) == blockTime)
  }

} 
Example 81
Source File: LogJson.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.stream

import java.nio.file.{ Files, Path }
import java.io.File
import java.time.ZonedDateTime

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.util.{ Success, Failure }

import akka.Done
import akka.actor._
import akka.util.ByteString

import akka.stream.{ ActorAttributes, ActorMaterializer, IOResult }
import akka.stream.scaladsl.JsonFraming
import akka.stream.scaladsl.{ FileIO, BidiFlow, Flow, Framing, Keep, Sink, Source }

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import spray.json._

object LogJson extends EventMarshalling 
    with NotificationMarshalling 
    with MetricMarshalling {
  def textInFlow(maxLine: Int) = {
    Framing.delimiter(ByteString("\n"), maxLine)
    .map(_.decodeString("UTF8"))
    .map(LogStreamProcessor.parseLineEx)
    .collect { case Some(e) => e }
  }

  def jsonInFlow(maxJsonObject: Int) = {
    JsonFraming.objectScanner(maxJsonObject) 
      .map(_.decodeString("UTF8").parseJson.convertTo[Event])
  }

  def jsonFramed(maxJsonObject: Int) =
    JsonFraming.objectScanner(maxJsonObject) 

  val jsonOutFlow = Flow[Event].map { event => 
    ByteString(event.toJson.compactPrint)
  }

  val notifyOutFlow = Flow[Summary].map { ws => 
    ByteString(ws.toJson.compactPrint)
  }

  val metricOutFlow = Flow[Metric].map { m => 
    ByteString(m.toJson.compactPrint)
  }

  val textOutFlow = Flow[Event].map{ event => 
    ByteString(LogStreamProcessor.logLine(event))
  }

  def logToJson(maxLine: Int) = {
    BidiFlow.fromFlows(textInFlow(maxLine), jsonOutFlow)
  }

  def jsonToLog(maxJsonObject: Int) = {
    BidiFlow.fromFlows(jsonInFlow(maxJsonObject), textOutFlow)
  }

  def logToJsonFlow(maxLine: Int) = {
    logToJson(maxLine).join(Flow[Event])
  }

  def jsonToLogFlow(maxJsonObject: Int) = {
    jsonToLog(maxJsonObject).join(Flow[Event])
  }
} 
Example 82
Source File: Event.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.stream

import java.io.File
import java.time.ZonedDateTime
import scala.concurrent.Future
import akka.NotUsed
import akka.util.ByteString
import akka.stream.IOResult
import akka.stream.scaladsl.{ Source, FileIO, Framing }

import scala.concurrent.duration.FiniteDuration


case class Event(
  host: String,
  service: String,
  state: State,
  time: ZonedDateTime,
  description: String,
  tag: Option[String] = None, 
  metric: Option[Double] = None
)


sealed trait State
case object Critical extends State
case object Error  extends State
case object Ok extends State
case object Warning extends State

object State {
  def norm(str: String): String = str.toLowerCase
  def norm(state: State): String = norm(state.toString)

  val ok = norm(Ok)
  val warning = norm(Warning)
  val error = norm(Error)
  val critical = norm(Critical)

  def unapply(str: String): Option[State] = {
    val normalized = norm(str)
    if(normalized == norm(Ok)) Some(Ok)
    else if(normalized == norm(Warning)) Some(Warning)
    else if(normalized == norm(Error)) Some(Error)
    else if(normalized == norm(Critical)) Some(Critical)
    else None
  }
}

case class LogReceipt(logId: String, written: Long)
case class ParseError(logId: String, msg: String) 
Example 83
Source File: ISO8601DateTime.scala    From toketi-iothubreact   with MIT License 5 votes vote down vote up
// Copyright (c) Microsoft. All rights reserved.

package A_APIUSage

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

import scala.util.matching.Regex


case class ISO8601DateTime(text: String) {

  private lazy val pattern1: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{1,3})Z""".r
  private lazy val pattern2: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})Z""".r
  private lazy val pattern3: Regex             = """(\d{4})-(\d{1,2})-(\d{1,2})""".r
  private lazy val format  : DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
  private lazy val zone    : ZoneId            = ZoneId.of("UTC")

  private lazy val zonedDateTime: ZonedDateTime = {
    text match {
      case pattern1(y, m, d, h, i, s, n) ⇒
        val ni = n.toInt
        val nanos = if (ni > 99) ni * 1000000 else if (ni > 9) ni * 10000000 else ni * 100000000
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, h.toInt, i.toInt, s.toInt, nanos, zone)

      case pattern2(y, m, d, h, i, s) ⇒
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, h.toInt, i.toInt, s.toInt, 0, zone)

      case pattern3(y, m, d) ⇒
        ZonedDateTime.of(y.toInt, m.toInt, d.toInt, 0, 0, 0, 0, zone)

      case null ⇒ null
      case _    ⇒ throw new Exception(s"wrong date time format: $text")
    }
  }

  override def toString: String = if (zonedDateTime == null) "" else zonedDateTime.format(format)
} 
Example 84
Source File: EventMarshalling.scala    From 006877   with MIT License 5 votes vote down vote up
package aia.stream

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

import scala.util.Try
import spray.json._

trait EventMarshalling extends DefaultJsonProtocol {
  implicit val dateTimeFormat = new JsonFormat[ZonedDateTime] {
    def write(dateTime: ZonedDateTime) = JsString(dateTime.format(DateTimeFormatter.ISO_INSTANT))
    def read(value: JsValue) = value match {
      case JsString(str) => 
        try {
          ZonedDateTime.parse(str)
        } catch {
          case e: DateTimeParseException => 
            val msg = s"Could not deserialize $str to ZonedDateTime"
            deserializationError(msg)
        }
      case js => 
        val msg = s"Could not deserialize $js to ZonedDateTime."
        deserializationError(msg)
    }
  }

  implicit val stateFormat = new JsonFormat[State] {
    def write(state: State) = JsString(State.norm(state))
    def read(value: JsValue) = value match {
      case JsString("ok") => Ok
      case JsString("warning") => Warning
      case JsString("error") => Error
      case JsString("critical") => Critical
      case js => 
        val msg = s"Could not deserialize $js to State."
        deserializationError(msg)
    }
  }

  implicit val eventFormat = jsonFormat7(Event)
  implicit val logIdFormat = jsonFormat2(LogReceipt)
  implicit val errorFormat = jsonFormat2(ParseError)
} 
Example 85
Source File: TransactionHistory.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.result

import java.time.ZonedDateTime

import org.json4s.{DefaultFormats, Formats}
import org.json4s.JsonAST.JObject
import stellar.sdk.model._
import stellar.sdk.model.ledger.TransactionLedgerEntries.arr
import stellar.sdk.model.ledger.{LedgerEntryChange, LedgerEntryChanges, TransactionLedgerEntries}
import stellar.sdk.model.response.ResponseParser
import stellar.sdk.util.ByteArrays.base64
import stellar.sdk.{KeyPair, PublicKey}

import scala.util.Try


case class TransactionHistory(hash: String, ledgerId: Long, createdAt: ZonedDateTime, account: PublicKey,
                              sequence: Long, maxFee: NativeAmount, feeCharged: NativeAmount, operationCount: Int,
                              memo: Memo, signatures: Seq[String], envelopeXDR: String, resultXDR: String,
                              resultMetaXDR: String, feeMetaXDR: String, validAfter: Option[ZonedDateTime],
                              validBefore: Option[ZonedDateTime], feeBump: Option[FeeBumpHistory]) {

  lazy val result: TransactionResult = TransactionResult.decodeXDR(resultXDR)

  def ledgerEntries: TransactionLedgerEntries = TransactionLedgerEntries.decodeXDR(resultMetaXDR)
  def feeLedgerEntries: Seq[LedgerEntryChange] = LedgerEntryChanges.decodeXDR(feeMetaXDR)

  @deprecated("Replaced by `feeCharged`", "v0.7.2")
  val feePaid: NativeAmount = feeCharged

}


object TransactionHistoryDeserializer extends {
} with ResponseParser[TransactionHistory]({
  o: JObject =>
    implicit val formats: Formats = DefaultFormats

    val maxFee = NativeAmount((o \ "max_fee").extract[String].toInt)
    val signatures = (o \ "signatures").extract[List[String]]
    val hash = (o \ "hash").extract[String]

    val inner = for {
      hash <- (o \ "inner_transaction" \ "hash").extractOpt[String]
      maxFee <- (o \ "inner_transaction" \ "max_fee").extractOpt[Int].map(NativeAmount(_))
      signatures <- (o \ "inner_transaction" \ "signatures").extractOpt[List[String]]
    } yield (hash, maxFee, signatures)

    TransactionHistory(
      hash = inner.map(_._1).getOrElse(hash),
      ledgerId = (o \ "ledger").extract[Long],
      createdAt = ZonedDateTime.parse((o \ "created_at").extract[String]),
      account = KeyPair.fromAccountId((o \ "source_account").extract[String]),
      sequence = (o \ "source_account_sequence").extract[String].toLong,
      maxFee = inner.map(_._2).getOrElse(maxFee),
      feeCharged = NativeAmount((o \ "fee_charged").extract[String].toInt),
      operationCount = (o \ "operation_count").extract[Int],
      memo = (o \ "memo_type").extract[String] match {
        case "none" => NoMemo
        case "id" => MemoId(BigInt((o \ "memo").extract[String]).toLong)
        case "text" => MemoText((o \ "memo").extractOpt[String].getOrElse(""))
        case "hash" => MemoHash(base64((o \ "memo").extract[String]).toIndexedSeq)
        case "return" => MemoReturnHash(base64((o \ "memo").extract[String]).toIndexedSeq)
      },
      signatures = inner.map(_._3).getOrElse(signatures),
      envelopeXDR = (o \ "envelope_xdr").extract[String],
      resultXDR = (o \ "result_xdr").extract[String],
      resultMetaXDR = (o \ "result_meta_xdr").extract[String],
      feeMetaXDR = (o \ "fee_meta_xdr").extract[String],
      // TODO (jem) - Remove the Try wrappers when https://github.com/stellar/go/issues/1381 is fixed.
      validBefore = Try((o \ "valid_before").extractOpt[String].map(ZonedDateTime.parse)).getOrElse(None),
      validAfter = Try((o \ "valid_after").extractOpt[String].map(ZonedDateTime.parse)).getOrElse(None),
      feeBump = inner.map { _ => FeeBumpHistory(maxFee, hash, signatures) }
    )
}) 
Example 86
Source File: Trade.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model

import java.time.ZonedDateTime

import org.json4s.DefaultFormats
import org.json4s.JsonAST.JObject
import stellar.sdk.model.response.ResponseParser
import stellar.sdk.{KeyPair, PublicKeyOps}

case class Trade(id: String, ledgerCloseTime: ZonedDateTime, offerId: Long,
                 baseOfferId: Long, counterOfferId: Long,
                 baseAccount: PublicKeyOps, baseAmount: Amount,
                 counterAccount: PublicKeyOps, counterAmount: Amount,
                 baseIsSeller: Boolean)


object TradeDeserializer extends ResponseParser[Trade]({
  o: JObject =>
    implicit val formats = DefaultFormats

    def account(accountKey: String = "account") = KeyPair.fromAccountId((o \ accountKey).extract[String])

    def date(key: String) = ZonedDateTime.parse((o \ key).extract[String])

    def doubleFromString(key: String) = (o \ key).extract[String].toDouble

    def asset(prefix: String = "", issuerKey: String = "asset_issuer") = {
      def assetCode = (o \ s"${prefix}asset_code").extract[String]

      def assetIssuer = KeyPair.fromAccountId((o \ s"$prefix$issuerKey").extract[String])

      (o \ s"${prefix}asset_type").extract[String] match {
        case "native" => NativeAsset
        case "credit_alphanum4" => IssuedAsset4(assetCode, assetIssuer)
        case "credit_alphanum12" => IssuedAsset12(assetCode, assetIssuer)
        case t => throw new RuntimeException(s"Unrecognised asset type '$t'")
      }
    }

    def amount(prefix: String = "") = {
      val units = Amount.toBaseUnits(doubleFromString(s"${prefix}amount")).get
      asset(prefix) match {
        case nna: NonNativeAsset => IssuedAmount(units, nna)
        case NativeAsset => NativeAmount(units)
      }
    }

    Trade(
      id = (o \ "id").extract[String],
      ledgerCloseTime = date("ledger_close_time"),
      offerId = (o \ "offer_id").extract[String].toLong,
      baseOfferId = (o \ "base_offer_id").extract[String].toLong,
      counterOfferId = (o \ "counter_offer_id").extract[String].toLong,
      baseAccount = account("base_account"),
      baseAmount = amount("base_"),
      counterAccount = account("counter_account"),
      counterAmount = amount("counter_"),
      baseIsSeller = (o \ "base_is_seller").extract[Boolean]
    )
}) 
Example 87
Source File: OfferResponse.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.time.ZonedDateTime

import org.json4s.DefaultFormats
import org.json4s.JsonAST.JObject
import stellar.sdk._
import stellar.sdk.model._

case class OfferResponse(id: Long, seller: PublicKeyOps, selling: Amount, buying: Asset, price: Price,
                         lastModifiedLedger: Long, lastModifiedTime: ZonedDateTime) {

  override def toString = {
    s"Offer $id: ${seller.accountId} selling $selling, buying $buying @ rate $price"
  }
}

object OfferRespDeserializer extends ResponseParser[OfferResponse]({ o: JObject =>
  implicit val formats = DefaultFormats
  val id = (o \ "id").extract[String].toLong

  def account(accountKey: String = "account") = KeyPair.fromAccountId((o \ accountKey).extract[String])

  def asset(prefix: String = "", issuerKey: String = "asset_issuer") = {
    def assetCode = (o \ prefix \ "asset_code").extract[String]

    def assetIssuer = KeyPair.fromAccountId((o \ prefix \ issuerKey).extract[String])

    (o \ prefix \ "asset_type").extract[String] match {
      case "native" => NativeAsset
      case "credit_alphanum4" => IssuedAsset4(assetCode, assetIssuer)
      case "credit_alphanum12" => IssuedAsset12(assetCode, assetIssuer)
      case t => throw new RuntimeException(s"Unrecognised asset type '$t'")
    }
  }

  def doubleFromString(key: String) = (o \ key).extract[String].toDouble

  def amount(prefix: String = "") = {
    val units = Amount.toBaseUnits(doubleFromString("amount")).get
    asset(prefix) match {
      case nna: NonNativeAsset => IssuedAmount(units, nna)
      case NativeAsset => NativeAmount(units)
    }
  }

  def price = {
    val priceObj = o \ "price_r"
    Price(
      (priceObj \ "n").extract[Int],
      (priceObj \ "d").extract[Int]
    )
  }

  def lastModifiedLedger = (o \ "last_modified_ledger").extract[Long]

  def lastModifiedTime = ZonedDateTime.parse((o \ "last_modified_time").extract[String])

  OfferResponse(id, account("seller"), amount("selling"), asset("buying"), price, lastModifiedLedger, lastModifiedTime)
}) 
Example 88
Source File: LedgerResponse.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.response

import java.time.ZonedDateTime

import org.json4s.DefaultFormats
import org.json4s.JsonAST.JObject
import stellar.sdk.model.{Amount, NativeAmount}

case class LedgerResponse(id: String, hash: String, previousHash: Option[String], sequence: Long, successTransactionCount: Int,
                          failureTransactionCount: Int, operationCount: Int, closedAt: ZonedDateTime,
                          totalCoins: NativeAmount, feePool: NativeAmount, baseFee: NativeAmount, baseReserve: NativeAmount,
                          maxTxSetSize: Int) {

  def transactionCount: Int = successTransactionCount + failureTransactionCount

}

object LedgerRespDeserializer extends ResponseParser[LedgerResponse]({ o: JObject =>
  implicit val formats = DefaultFormats

  LedgerResponse(
    id = (o \ "id").extract[String],
    hash = (o \ "hash").extract[String],
    previousHash = (o \ "prev_hash").extractOpt[String],
    sequence = (o \ "sequence").extract[Long],
    successTransactionCount = (o \ "successful_transaction_count").extract[Int],
    failureTransactionCount = (o \ "failed_transaction_count").extract[Int],
    operationCount = (o \ "operation_count").extract[Int],
    closedAt = ZonedDateTime.parse((o \ "closed_at").extract[String]),
    totalCoins = Amount.toBaseUnits((o \ "total_coins").extract[String]).map(NativeAmount.apply).get,
    feePool = Amount.toBaseUnits((o \ "fee_pool").extract[String]).map(NativeAmount.apply).get,
    baseFee = NativeAmount((o \ "base_fee").extractOpt[Long].getOrElse((o \ "base_fee_in_stroops").extract[Long])),
    baseReserve = {
      val old: Option[Long] = (o \ "base_reserve").extractOpt[String].map(_.toDouble).map(Amount.toBaseUnits).map(_.get)
      NativeAmount(old.getOrElse((o \ "base_reserve_in_stroops").extract[Long]))
    },
    maxTxSetSize = (o \ "max_tx_set_size").extract[Int]
  )
}) 
Example 89
Source File: Transacted.scala    From scala-stellar-sdk   with Apache License 2.0 5 votes vote down vote up
package stellar.sdk.model.op

import java.time.ZonedDateTime

import org.json4s.DefaultFormats
import org.json4s.JsonAST.JObject
import stellar.sdk.model.response.ResponseParser


case class Transacted[+O <: Operation](id: Long,
                                      txnHash: String,
                                      createdAt: ZonedDateTime,
                                      operation: O)

object TransactedOperationDeserializer extends ResponseParser[Transacted[Operation]]({ o: JObject =>
  implicit val formats = DefaultFormats + OperationDeserializer

  def date(key: String) = ZonedDateTime.parse((o \ key).extract[String])

  Transacted(
    id = (o \ "id").extract[String].toLong,
    txnHash = (o \ "transaction_hash").extract[String],
    createdAt = date("created_at"),
    operation = o.extract[Operation])
}) 
Example 90
Source File: CookieSpec.scala    From hammock   with MIT License 5 votes vote down vote up
package hammock
package hi

import java.time.ZonedDateTime

import cats._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class CookieSpec extends AnyWordSpec with Matchers {

  "Show[Cookie].show" should {
    "render a simple cookie in the correct format" in {
      val cookie = Cookie("name", "value")

      Show[Cookie].show(cookie) shouldEqual "name=value"
    }

    "render a complex cookie in the correct format" in {
      val cookie = Cookie(
        "name",
        "value",
        Some(ZonedDateTime.parse("2020-01-04T17:03:54.000Z")),
        Some(123),
        Some("pepegar.com"),
        Some("/blog"),
        Some(false),
        Some(true),
        Some(Cookie.SameSite.Strict)
      )

      Show[Cookie].show(cookie) shouldEqual "name=value; Expires=Sat, 04 Jan 2020 17:03:54 GMT; MaxAge=123; Domain=pepegar.com; Path=/blog; Secure=false; HttpOnly=true; SameSite=Strict"
    }

    "render a cookie with custom values in the correct format" in {
      val cookie = Cookie("hello", "dolly", custom = Some(Map("potatoes" -> "22")))

      Show[Cookie].show(cookie) shouldEqual "hello=dolly; potatoes=22"
    }
  }

} 
Example 91
Source File: ReadsSpec.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion.cli

import java.time.{DayOfWeek, ZonedDateTime}
import org.scalatest.WordSpec

class ReadsSpec extends WordSpec {
  "`with` function of ZonedDateTime" should {
    "shift the date to the expected" in {

      val dt = ZonedDateTime.parse("2019-11-20T00:00:00Z")

      assert(
          dt.`with`(DayOfWeek.MONDAY)    === ZonedDateTime.parse("2019-11-18T00:00:00Z") &&
          dt.`with`(DayOfWeek.TUESDAY)   === ZonedDateTime.parse("2019-11-19T00:00:00Z") &&
          dt.`with`(DayOfWeek.WEDNESDAY) === ZonedDateTime.parse("2019-11-20T00:00:00Z") &&
          dt.`with`(DayOfWeek.THURSDAY)  === ZonedDateTime.parse("2019-11-21T00:00:00Z") &&
          dt.`with`(DayOfWeek.FRIDAY)    === ZonedDateTime.parse("2019-11-22T00:00:00Z") &&
          dt.`with`(DayOfWeek.SATURDAY)  === ZonedDateTime.parse("2019-11-23T00:00:00Z") &&
          dt.`with`(DayOfWeek.SUNDAY)    === ZonedDateTime.parse("2019-11-24T00:00:00Z")
      )
    }
  }
} 
Example 92
Source File: ParameterSpec.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion.expression

import java.time.ZonedDateTime
import org.scalatest.{ OptionValues, WordSpec }

import com.krux.hyperion.aws.AdpParameter

class ParameterSpec extends WordSpec with OptionValues {
  "Parameter[ZonedDateTime]" should {
    "be serialized in the correct datetime format" in {
      implicit val values = new ParameterValues()

      val dateTimeParam = Parameter[ZonedDateTime]("datetime", ZonedDateTime.parse("2014-04-02T00:00:00Z"))

      assert(dateTimeParam.serialize.value === AdpParameter(
        id = "my_datetime",
        `default` = Some("2014-04-02T00:00:00")
      ))
    }
  }
} 
Example 93
Source File: ScheduleSpec.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion

import java.time.format.DateTimeFormatter
import java.time.{DayOfWeek, ZoneId, ZonedDateTime}

import org.joda.time.{DateTime, DateTimeZone}
import org.scalatest.WordSpec

class ScheduleSpec extends WordSpec{
  "`with` function of DayOfWeek" should {
    "shift the date to the expected" in {

      val dt = ZonedDateTime.parse("2019-11-20T00:00:00Z")

      assert(
        dt.`with`(DayOfWeek.of(1)) === ZonedDateTime.parse("2019-11-18T00:00:00Z") &&
        dt.`with`(DayOfWeek.of(2)) === ZonedDateTime.parse("2019-11-19T00:00:00Z") &&
        dt.`with`(DayOfWeek.of(3)) === ZonedDateTime.parse("2019-11-20T00:00:00Z") &&
        dt.`with`(DayOfWeek.of(4)) === ZonedDateTime.parse("2019-11-21T00:00:00Z") &&
        dt.`with`(DayOfWeek.of(5)) === ZonedDateTime.parse("2019-11-22T00:00:00Z") &&
        dt.`with`(DayOfWeek.of(6)) === ZonedDateTime.parse("2019-11-23T00:00:00Z") &&
        dt.`with`(DayOfWeek.of(7)) === ZonedDateTime.parse("2019-11-24T00:00:00Z")
      )
    }
  }

  "`with` function of DayOfWeek" should {
    "shift the date same as withDayOfWeek in Joda time" in {

      val dateTimeFormatStr = "yyyy-MM-dd'T'HH:mm:ss"
      val datetimeFormat = DateTimeFormatter.ofPattern(dateTimeFormatStr)

      val javaDt = ZonedDateTime.parse("2019-11-20T00:00:00Z").withZoneSameInstant(ZoneId.of("UTC"))
      val jodaDt = new DateTime("2019-11-20T00:00:00Z").withZone(DateTimeZone.UTC)

      assert(
        javaDt.`with`(DayOfWeek.of(1)).format(datetimeFormat) === jodaDt.withDayOfWeek(1).toString(dateTimeFormatStr) &&
        javaDt.`with`(DayOfWeek.of(2)).format(datetimeFormat) === jodaDt.withDayOfWeek(2).toString(dateTimeFormatStr) &&
        javaDt.`with`(DayOfWeek.of(3)).format(datetimeFormat) === jodaDt.withDayOfWeek(3).toString(dateTimeFormatStr) &&
        javaDt.`with`(DayOfWeek.of(4)).format(datetimeFormat) === jodaDt.withDayOfWeek(4).toString(dateTimeFormatStr) &&
        javaDt.`with`(DayOfWeek.of(5)).format(datetimeFormat) === jodaDt.withDayOfWeek(5).toString(dateTimeFormatStr) &&
        javaDt.`with`(DayOfWeek.of(6)).format(datetimeFormat) === jodaDt.withDayOfWeek(6).toString(dateTimeFormatStr) &&
        javaDt.`with`(DayOfWeek.of(7)).format(datetimeFormat) === jodaDt.withDayOfWeek(7).toString(dateTimeFormatStr)
      )
    }
  }

  "withZoneSameLocal" should {
    "be consistent with toDateTime in joda time" in {

      val dateTimeFormatStr = "yyyy-MM-dd'T'HH:mm:ss"
      val datetimeFormat = DateTimeFormatter.ofPattern( dateTimeFormatStr)

      val javaDt = ZonedDateTime.parse("2019-11-18T00:00:00Z").withZoneSameLocal(ZoneId.of("UTC"))
      val jodaDt = new DateTime("2019-11-18T00:00:00Z").toDateTime(DateTimeZone.UTC)

      assert(javaDt.format(datetimeFormat) === jodaDt.toString(dateTimeFormatStr))
    }
  }
}