java.time.temporal.ChronoUnit Scala Examples

The following examples show how to use java.time.temporal.ChronoUnit. 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: InMemoryStoreSpec.scala    From slab   with Apache License 2.0 5 votes vote down vote up
package com.criteo.slab.lib

import java.time.Instant
import java.time.temporal.ChronoUnit

import org.scalatest.{FlatSpec, Matchers}
import org.slf4j.LoggerFactory

import scala.collection.concurrent.TrieMap

class InMemoryStoreSpec extends FlatSpec with Matchers {
  val logger = LoggerFactory.getLogger(this.getClass)
  "Cleaner" should "remove expired entries" in {
    val cache = TrieMap.empty[(String, Long), Any]
    val cleaner = InMemoryStore.createCleaner(cache, 1, logger)

    cache += ("a", Instant.now.minus(2, ChronoUnit.DAYS).toEpochMilli) -> 1
    cache += ("b", Instant.now.minus(1, ChronoUnit.DAYS).toEpochMilli) -> 2
    cache += ("c", Instant.now.toEpochMilli) -> 3
    cleaner.run()
    cache.size shouldBe 1
    cache.head._1._1 shouldBe "c"
  }

} 
Example 2
Source File: ProducerConvertersSpec.scala    From skafka   with MIT License 5 votes vote down vote up
package com.evolutiongaming.skafka.producer

import java.time.Instant
import java.time.temporal.ChronoUnit

import cats.implicits._
import com.evolutiongaming.skafka.producer.ProducerConverters._
import com.evolutiongaming.skafka.{Header, Offset, Partition, TopicPartition}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

import scala.util.Try

class ProducerConvertersSpec extends AnyWordSpec with Matchers {

  "ProducerConverters" should {

    val instant = Instant.now().truncatedTo(ChronoUnit.MILLIS)

    "convert Producer.Record" in {
      val record1 = ProducerRecord[Int, String](topic = "topic", value = Some("value"))
      record1.asJava.asScala[Try] shouldEqual record1.pure[Try]

      val record2 = ProducerRecord[Int, String](
        topic = "topic",
        value = Some("value"),
        key = Some(1),
        partition = Some(Partition.min),
        timestamp = Some(instant),
        headers = List(Header("key", Array[Byte](1, 2, 3))))
      record2.asJava.asScala[Try] shouldEqual record2.pure[Try]
    }

    "convert RecordMetadata" in {
      val topicPartition = TopicPartition("topic", Partition.min)
      val metadata1 = RecordMetadata(topicPartition)
      metadata1.pure[Try] shouldEqual metadata1.asJava.asScala[Try]

      val metadata2 = RecordMetadata(topicPartition, Some(instant), Offset.min.some, 10.some, 100.some)
      metadata2.pure[Try] shouldEqual metadata2.asJava.asScala[Try]
    }
  }
} 
Example 3
Source File: ConsumerConvertersSpec.scala    From skafka   with MIT License 5 votes vote down vote up
package com.evolutiongaming.skafka.consumer

import java.time.Instant
import java.time.temporal.ChronoUnit

import cats.implicits._
import com.evolutiongaming.skafka._
import com.evolutiongaming.skafka.Converters._
import com.evolutiongaming.skafka.consumer.ConsumerConverters._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

import scala.util.Try


class ConsumerConvertersSpec extends AnyWordSpec with Matchers {

  val instant: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS)

  "ConsumerConverters" should {

    "convert OffsetAndMetadata" in {
      val value = OffsetAndMetadata(Offset.min, "metadata")
      value.pure[Try] shouldEqual value.asJava.asScala[Try]
    }

    "convert OffsetAndTimestamp" in {
      val value = OffsetAndTimestamp(Offset.min, instant)
      value.pure[Try] shouldEqual value.asJava.asScala[Try]
    }

    for {
      timestampAndType <- List(
        None,
        Some(TimestampAndType(instant, TimestampType.Create)),
        Some(TimestampAndType(instant, TimestampType.Append)))
      key <- List(Some(WithSize("key", 1)), None)
      value <- List(Some(WithSize("value", 1)), None)
    } {
      s"convert ConsumerRecord, key: $key, value: $value, timestampAndType: $timestampAndType" in {
        val consumerRecord = ConsumerRecord(
          topicPartition = TopicPartition("topic", Partition.min),
          offset = Offset.min,
          timestampAndType = timestampAndType,
          key = key,
          value = value,
          headers = List(Header("key", Bytes.empty)))
        consumerRecord.pure[Try] shouldEqual consumerRecord.asJava.asScala[Try]
      }
    }
  }
} 
Example 4
Source File: AvroMessageFormatterMain.scala    From affinity   with Apache License 2.0 5 votes vote down vote up
import java.time.temporal.ChronoUnit
import java.util.Properties

import io.amient.affinity.kafka.AvroMessageFormatter
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.serialization.ByteArrayDeserializer

import scala.collection.JavaConverters._

object AvroMessageFormatterMain extends App {

  val consumerProps = new Properties()
  consumerProps.put("bootstrap.servers", args(0))
  consumerProps.put("security.protocol", "SASL_SSL")
  consumerProps.put("sasl.mechanism", "PLAIN")
  consumerProps.put("client.id", "console")
  consumerProps.put("group.id", "console")
  consumerProps.put("key.deserializer", classOf[ByteArrayDeserializer])
  consumerProps.put("value.deserializer", classOf[ByteArrayDeserializer])
  consumerProps.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username='" + args(1) + "' password='" + args(2) + "';")
  consumerProps.put("schema.registry.url", args(3))
  val c = new KafkaConsumer[Array[Byte], Array[Byte]](consumerProps)
  c.subscribe(List(args(4)).asJava)
  val formatter = new AvroMessageFormatter()
  formatter.init(consumerProps)
  while (true) {
    c.poll(java.time.Duration.of(1, ChronoUnit.SECONDS)).asScala.foreach {
      record => formatter.writeTo(record, System.out)
    }
  }

} 
Example 5
Source File: ScheduleProcess.scala    From aecor   with MIT License 5 votes vote down vote up
package aecor.schedule.process

import java.time.temporal.ChronoUnit
import java.time.{Clock => _, _}

import aecor.data._
import aecor.runtime.KeyValueStore
import aecor.schedule.ScheduleEvent.{ScheduleEntryAdded, ScheduleEntryFired}
import aecor.schedule.{ScheduleBucket, ScheduleBucketId, ScheduleEntryRepository}
import cats.Monad
import cats.implicits._

import scala.concurrent.duration.FiniteDuration

object ScheduleProcess {
  def apply[F[_]: Monad](journal: ScheduleEventJournal[F],
                         dayZero: LocalDate,
                         consumerId: ConsumerId,
                         offsetStore: KeyValueStore[F, TagConsumer, LocalDateTime],
                         eventualConsistencyDelay: FiniteDuration,
                         repository: ScheduleEntryRepository[F],
                         buckets: ScheduleBucketId => ScheduleBucket[F],
                         clock: F[LocalDateTime],
                         parallelism: Int): F[Unit] = {
    val scheduleEntriesTag = EventTag("io.aecor.ScheduleDueEntries")

    val tagConsumerId = TagConsumer(scheduleEntriesTag, consumerId)

    val updateRepository: F[Unit] =
      journal.processNewEvents {
        case EntityEvent(id, _, ScheduleEntryAdded(entryId, _, dueDate, _)) =>
          for {
            _ <- repository.insertScheduleEntry(id, entryId, dueDate)
            now <- clock
            _ <- if (dueDate.isEqual(now) || dueDate.isBefore(now)) {
                buckets(id).fireEntry(entryId)
              } else {
                ().pure[F]
              }
          } yield ()
        case EntityEvent(id, _, ScheduleEntryFired(entryId, _, _)) =>
          repository.markScheduleEntryAsFired(id, entryId)
      }
    def fireEntries(from: LocalDateTime,
                    to: LocalDateTime): F[Option[ScheduleEntryRepository.ScheduleEntry]] =
      repository.processEntries(from, to, parallelism) {
        entry =>
          if (entry.fired)
            ().pure[F]
          else
            buckets(entry.bucketId).fireEntry(entry.entryId)
      }

    val loadOffset: F[LocalDateTime] =
      offsetStore
        .getValue(tagConsumerId)
        .map(_.getOrElse(dayZero.atStartOfDay()))

    def saveOffset(value: LocalDateTime): F[Unit] =
      offsetStore.setValue(tagConsumerId, value)

    for {
      _ <- updateRepository
      from <- loadOffset
      now <- clock
      entry <- fireEntries(from.minus(eventualConsistencyDelay.toMillis, ChronoUnit.MILLIS), now)
      _ <- entry.map(_.dueDate).traverse(saveOffset)
    } yield ()
  }

} 
Example 6
Source File: CommonCfp.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.core.domain

import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDateTime}

import gospeak.core.domain.utils.Constants
import gospeak.core.domain.utils.SocialAccounts.SocialAccount.TwitterAccount
import gospeak.libs.scala.Extensions._
import gospeak.libs.scala.domain._

final case class CommonCfp(name: String,
                           logo: Option[Logo],
                           begin: Option[LocalDateTime],
                           close: Option[LocalDateTime],
                           location: Option[GMapPlace],
                           description: Markdown,
                           tags: Seq[Tag],
                           extra: Either[CommonCfp.External, CommonCfp.Internal]) {
  def closesInDays(nb: Int, now: Instant): Boolean = close.exists(_.toInstant(Constants.defaultZoneId).isBefore(now.minus(nb, ChronoUnit.DAYS)))

  def fold[A](f: CommonCfp.External => A)(g: CommonCfp.Internal => A): A = extra.fold(f, g)

  def internal: Option[CommonCfp.Internal] = extra.right.toOption

  def external: Option[CommonCfp.External] = extra.left.toOption
}

object CommonCfp {
  def apply(group: Group, cfp: Cfp): CommonCfp = new CommonCfp(
    name = cfp.name.value,
    logo = group.logo,
    begin = cfp.begin,
    close = cfp.close,
    location = group.location,
    description = cfp.description,
    tags = cfp.tags,
    extra = Right(Internal(
      slug = cfp.slug,
      group = InternalGroup(
        id = group.id,
        slug = group.slug))))

  def apply(cfp: ExternalCfp.Full): CommonCfp = new CommonCfp(
    name = cfp.event.name.value,
    logo = cfp.event.logo,
    begin = cfp.begin,
    close = cfp.close,
    location = cfp.event.location,
    description = cfp.description,
    tags = cfp.event.tags,
    extra = Left(External(
      id = cfp.id,
      url = cfp.url,
      event = ExternalExternalEvent(
        start = cfp.event.start,
        finish = cfp.event.finish,
        url = cfp.event.url,
        tickets = cfp.event.tickets,
        videos = cfp.event.videos,
        twitterAccount = cfp.event.twitterAccount,
        twitterHashtag = cfp.event.twitterHashtag))))

  final case class InternalGroup(id: Group.Id,
                                 slug: Group.Slug)

  final case class Internal(slug: Cfp.Slug,
                            group: InternalGroup)

  final case class ExternalExternalEvent(start: Option[LocalDateTime],
                                         finish: Option[LocalDateTime],
                                         url: Option[Url],
                                         tickets: Option[Url],
                                         videos: Option[Url],
                                         twitterAccount: Option[TwitterAccount],
                                         twitterHashtag: Option[TwitterHashtag])

  final case class External(id: ExternalCfp.Id,
                            url: Url,
                            event: ExternalExternalEvent)

} 
Example 7
Source File: DurationConverters.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.util

import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit
import java.time.{Duration => JavaDuration}

import scala.concurrent.duration.{FiniteDuration, Duration => ScalaDuration}



  final def toJava(duration: scala.concurrent.duration.FiniteDuration): java.time.Duration = {
    if (duration.length == 0) JavaDuration.ZERO
    else duration.unit match {
      case TimeUnit.NANOSECONDS => JavaDuration.ofNanos(duration.length)
      case TimeUnit.MICROSECONDS => JavaDuration.of(duration.length, ChronoUnit.MICROS)
      case TimeUnit.MILLISECONDS => JavaDuration.ofMillis(duration.length)
      case TimeUnit.SECONDS => JavaDuration.ofSeconds(duration.length)
      case TimeUnit.MINUTES => JavaDuration.ofMinutes(duration.length)
      case TimeUnit.HOURS => JavaDuration.ofHours(duration.length)
      case TimeUnit.DAYS => JavaDuration.ofDays(duration.length)
    }
  }
} 
Example 8
Source File: LogEntry.scala    From infinispan-spark   with Apache License 2.0 5 votes vote down vote up
package org.infinispan.spark.domain

import java.io.{ObjectInput, ObjectOutput}
import java.time.LocalDate
import java.time.temporal.ChronoUnit

import org.infinispan.commons.io.UnsignedNumeric
import org.infinispan.commons.marshall._


@SerializeWith(classOf[LogEntrySerializer])
class LogEntry(val date: LocalDate, var opCode: Int, val userAgent: String, val domain: String)

class LogEntrySerializer extends Externalizer[LogEntry] {
   override def writeObject(output: ObjectOutput, obj: LogEntry): Unit = {
      output.writeObject(obj.date)
      UnsignedNumeric.writeUnsignedInt(output, obj.opCode)
      output.writeUTF(obj.userAgent)
      output.writeUTF(obj.domain)
   }

   override def readObject(input: ObjectInput): LogEntry = {
      val date = input.readObject().asInstanceOf[LocalDate]
      val opCode = UnsignedNumeric.readUnsignedInt(input)
      val userAgent = input.readUTF()
      val domain = input.readUTF()
      new LogEntry(date, opCode, userAgent, domain)
   }
}

object EntryGenerator {

   val browser = Set("Firefox", "Chrome", "MSIE")
   val domainNames = Set("no-ip.org", "dnf.it", "google.com", "localhost")

   def generate(numEntries: Int, errorCondition: LogEntry => Boolean, startDate: LocalDate, endDate: LocalDate) = {
      val userAgentsIterator = circularIterator(browser)
      val domainNamesIterator = circularIterator(domainNames)
      val diffDays = ChronoUnit.DAYS.between(startDate, endDate)
      val daysPerEntry = diffDays.toFloat / numEntries.toFloat
      (1 to numEntries).map { i =>
         val browser = userAgentsIterator.next()
         val domain = domainNamesIterator.next()
         val dateTime = startDate.plusDays(Math.floor(daysPerEntry * i).toInt)
         val entry = new LogEntry(dateTime, 0, browser, domain)
         val op = if (errorCondition(entry)) 500 else 200
         entry.opCode = op
         entry
      }.toList
   }

   private def circularIterator[T](s: Set[T]) = Iterator.continually(s).flatten

} 
Example 9
Source File: CallRecordSplitSpec.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package carly.ingestor

import java.time.Instant
import java.time.temporal.ChronoUnit

import akka.actor._
import akka.stream.scaladsl._
import akka.testkit._
import org.scalatest._
import org.scalatest.concurrent._

import cloudflow.akkastream.testkit.scaladsl._
import carly.data._

class CallRecordSplitSpec extends WordSpec with MustMatchers with ScalaFutures with BeforeAndAfterAll {

  private implicit val system = ActorSystem("CallRecordSplitSpec")

  override def afterAll: Unit =
    TestKit.shutdownActorSystem(system)

  "A CallRecordSplit" should {
    "merge incoming data" in {
      val testkit   = AkkaStreamletTestKit(system)
      val streamlet = new CallRecordSplit

      val instant = Instant.now.toEpochMilli / 1000
      val past    = Instant.now.minus(5000, ChronoUnit.DAYS).toEpochMilli / 1000

      val cr1 = CallRecord("user-1", "user-2", "f", 10L, instant)
      val cr2 = CallRecord("user-1", "user-2", "f", 15L, instant)
      val cr3 = CallRecord("user-1", "user-2", "f", 18L, instant)

      val source = Source(Vector(cr1, cr2, cr3))

      val in   = testkit.inletFromSource(streamlet.in, source)
      val left  = testkit.outletAsTap(streamlet.left)
      val right = testkit.outletAsTap(streamlet.right)

      testkit.run(
        streamlet,
        List(in),
        List(left, right),
        () ⇒ {
          right.probe.expectMsg(("user-1", cr1))
          right.probe.expectMsg(("user-1", cr2))
          right.probe.expectMsg(("user-1", cr3))
        }
      )

      right.probe.expectMsg(Completed)
    }

    "split incoming data into valid call records and those outside the time range" in {
      val testkit   = AkkaStreamletTestKit(system)
      val streamlet = new CallRecordSplit()

      val instant = Instant.now.toEpochMilli / 1000
      val past    = Instant.now.minus(5000, ChronoUnit.DAYS).toEpochMilli / 1000

      val cr1 = CallRecord("user-1", "user-2", "f", 10L, instant)
      val cr2 = CallRecord("user-1", "user-2", "f", 15L, instant)
      val cr3 = CallRecord("user-1", "user-2", "f", 18L, instant)
      val cr4 = CallRecord("user-1", "user-2", "f", 40L, past)
      val cr5 = CallRecord("user-1", "user-2", "f", 70L, past)

      val source = Source(Vector(cr1, cr2, cr3, cr4, cr5))

      val in = testkit.inletFromSource(streamlet.in, source)

      val left  = testkit.outletAsTap(streamlet.left)
      val right = testkit.outletAsTap(streamlet.right)

      testkit.run(
        streamlet,
        List(in),
        List(left, right),
        () ⇒ {
          right.probe.expectMsg(("user-1", cr1))
          right.probe.expectMsg(("user-1", cr2))
          right.probe.expectMsg(("user-1", cr3))
          left.probe.expectMsg((cr4.toString, InvalidRecord(cr4.toString, "Timestamp outside range!")))
          left.probe.expectMsg((cr5.toString, InvalidRecord(cr5.toString, "Timestamp outside range!")))
        }
      )

      left.probe.expectMsg(Completed)
      right.probe.expectMsg(Completed)
    }
  }
} 
Example 10
Source File: InMemoryStore.scala    From slab   with Apache License 2.0 5 votes vote down vote up
package com.criteo.slab.lib

import java.time.format.{DateTimeFormatter, FormatStyle}
import java.time.temporal.ChronoUnit
import java.time.{Instant, ZoneId}
import java.util.concurrent.{Executors, TimeUnit}

import com.criteo.slab.core.{Codec, Context, Store}
import com.criteo.slab.lib.Values.Slo
import org.slf4j.{Logger, LoggerFactory}

import scala.collection.concurrent.TrieMap
import scala.concurrent.Future
import scala.util.Try


class InMemoryStore(
                     val expiryDays: Int = 30
                   ) extends Store[Any] {
  private val logger = LoggerFactory.getLogger(this.getClass)
  private val cache = TrieMap.empty[(String, Long), Any]
  private val scheduler = Executors.newSingleThreadScheduledExecutor()

  scheduler.scheduleAtFixedRate(InMemoryStore.createCleaner(cache, expiryDays, logger), 1, 1, TimeUnit.HOURS)
  logger.info(s"InMemoryStore started, entries expire in $expiryDays days")

  sys.addShutdownHook {
    logger.info(s"Shutting down...")
    scheduler.shutdown()
  }

  override def upload[T](id: String, context: Context, v: T)(implicit codec: Codec[T, Any]): Future[Unit] = {
    logger.debug(s"Uploading $id")
    Future.successful {
      cache.putIfAbsent((id, context.when.toEpochMilli), codec.encode(v))
      logger.info(s"Store updated, size: ${cache.size}")
    }
  }

  override def uploadSlo(id: String, context: Context, slo: Slo)(implicit codec: Codec[Slo, Any]): Future[Unit] = {
    upload[Slo](id, context, slo)
  }

  def fetchSloHistory(id: String, from: Instant, until: Instant)(implicit codec: Codec[Slo, Any]): Future[Seq[(Long, Slo)]] = {
    fetchHistory[Slo](id, from, until)(codec)
  }

  override def fetch[T](id: String, context: Context)(implicit codec: Codec[T, Any]): Future[Option[T]] = {
    logger.debug(s"Fetching $id")
    Future.successful {
      cache.get((id, context.when.toEpochMilli)) map { v =>
        codec.decode(v).get
      }
    }
  }

  override def fetchHistory[T](
                                id: String,
                                from: Instant,
                                until: Instant
                              )(implicit ev: Codec[T, Any]): Future[Seq[(Long, T)]] = {
    logger.debug(s"Fetching the history of $id from ${format(from)} until ${format(until)}, cache size: ${cache.size}")
    Future.successful {
      cache.withFilter { case ((_id, ts), _) =>
        _id == id && ts >= from.toEpochMilli && ts <= until.toEpochMilli
      }.map { case ((_, ts), repr) =>
        (ts, ev.decode(repr).get)
      }.toList
    }
  }

  private def format(i: Instant) = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
    .withZone(ZoneId.systemDefault)
    .format(i)
}

object InMemoryStore {
  implicit def codec[T] = new Codec[T, Any] {
    override def encode(v: T): Any = v

    override def decode(v: Any): Try[T] = Try(v.asInstanceOf[T])
  }

  def createCleaner(cache: TrieMap[(String, Long), Any], expiryDays: Int, logger: Logger): Runnable = {
    object C extends Runnable {
      override def run(): Unit = {
        val expired = cache.filterKeys(_._2 <= Instant.now.minus(expiryDays, ChronoUnit.DAYS).toEpochMilli).keys
        logger.debug(s"${expired.size} out of ${cache.size} entries have expired, cleaning up...")
        cache --= expired
      }
    }
    C
  }
} 
Example 11
Source File: StubConfirmationService.scala    From ticket-booking-aecor   with Apache License 2.0 5 votes vote down vote up
package ru.pavkin.booking.booking.service

import java.time.temporal.ChronoUnit
import java.time.{ Duration, Instant }
import java.util.concurrent.TimeUnit

import cats.Monad
import cats.data.NonEmptyList
import cats.effect.{ Clock, Sync }
import cats.effect.concurrent.Ref
import cats.implicits._
import ru.pavkin.booking.booking.service.TicketReservationService._
import ru.pavkin.booking.booking.service.StubConfirmationService.ConcertState
import ru.pavkin.booking.common.models._

class StubConfirmationService[F[_]: Monad](clock: Clock[F],
                                           state: Ref[F, Map[ConcertId, ConcertState]])
    extends TicketReservationService[F] {

  val expireAfter: Duration = Duration.of(6, ChronoUnit.HOURS)

  def reserve(bookingId: BookingKey,
           concertId: ConcertId,
           seats: NonEmptyList[Seat]): F[Either[ReservationFailure, Reservation]] =
    clock
      .realTime(TimeUnit.MILLISECONDS)
      .map(Instant.ofEpochMilli)
      .flatMap(
        now =>
          state.modify[Either[ReservationFailure, Reservation]](
            concerts =>
              concerts.get(concertId) match {
                case None => concerts -> Left(UnknownSeats)
                case Some(concertState) =>
                  concertState
                    .book(bookingId, seats)
                    .fold(e => concerts -> Left(e), {
                      case (c, t) =>
                        concerts.updated(concertId, c) -> Right(
                          Reservation(t, Some(now.plus(expireAfter)))
                        )
                    })

            }
        )
      )

  def release(bookingId: BookingKey): F[Either[ReleaseFailure, Unit]] =
    state.modify[Either[ReleaseFailure, Unit]](
      concerts =>
        Either
          .fromOption(concerts.find(_._2.bookedSeats.contains(bookingId)), UnknownBooking)
          .flatMap {
            case (concertId, concertState) =>
              concertState.release(bookingId).map(concertId -> _)
          } match {
          case Left(value)                  => concerts -> Left(value)
          case Right((concertId, newState)) => concerts.updated(concertId, newState) -> Right(())
      }
    )
}

object StubConfirmationService {

  def apply[F[_]: Sync](clock: Clock[F],
                        initial: Map[ConcertId, ConcertState]): F[StubConfirmationService[F]] =
    Ref.of(initial).map(new StubConfirmationService(clock, _))

  case class ConcertState(prices: Map[Seat, Money],
                          availableSeats: Set[Seat],
                          bookedSeats: Map[BookingKey, NonEmptyList[Seat]]) {

    def book(
      bookingId: BookingKey,
      seats: NonEmptyList[Seat]
    ): Either[ReservationFailure, (ConcertState, NonEmptyList[Ticket])] =
      if (bookedSeats.contains(bookingId)) Left(SeatsAlreadyBooked)
      else if (!seats.forall(availableSeats)) Left(SeatsAlreadyBooked)
      else if (!seats.forall(prices.contains)) Left(UnknownSeats)
      else
        Right(
          copy(
            availableSeats = availableSeats.diff(seats.toList.toSet),
            bookedSeats = bookedSeats.updated(bookingId, seats)
          ) -> seats.map(s => Ticket(s, prices(s)))
        )

    def release(bookingId: BookingKey): Either[ReleaseFailure, ConcertState] =
      bookedSeats.get(bookingId) match {
        case Some(booked) =>
          Right(
            copy(
              availableSeats = availableSeats ++ booked.toList.toSet,
              bookedSeats = bookedSeats - bookingId
            )
          )
        case None => Left(UnknownBooking)
      }
  }

} 
Example 12
Source File: package.scala    From fs2-cron   with Apache License 2.0 5 votes vote down vote up
package eu.timepit

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit

import cats.ApplicativeError
import cats.effect.{Concurrent, Sync, Timer}
import cron4s.expr.CronExpr
import cron4s.lib.javatime._
import fs2.Stream

import scala.concurrent.duration.FiniteDuration

package object fs2cron {

  
  def sleepCron[F[_]: Sync](cronExpr: CronExpr)(implicit timer: Timer[F]): Stream[F, Unit] =
    durationFromNow(cronExpr).flatMap(Stream.sleep[F])

  def schedule[F[_]: Concurrent, A](tasks: List[(CronExpr, Stream[F, A])])(implicit
      timer: Timer[F]
  ): Stream[F, A] = {
    val scheduled = tasks.map { case (cronExpr, task) => awakeEveryCron[F](cronExpr) >> task }
    Stream.emits(scheduled).covary[F].parJoinUnbounded
  }
} 
Example 13
Source File: CronExpression.scala    From cuttle   with Apache License 2.0 5 votes vote down vote up
package com.criteo.cuttle.cron

import cron4s.Cron
import cron4s.lib.javatime._
import java.time.{Duration, Instant, ZoneId, ZoneOffset}
import java.time.temporal.ChronoUnit

import io.circe.{Encoder, Json}
import io.circe.syntax._

import java.time.ZoneOffset
import scala.concurrent.duration._


case class CronExpression(cronExpression: String, tz: ZoneId = ZoneOffset.UTC) {

  // https://www.baeldung.com/cron-expressions
  // https://www.freeformatter.com/cron-expression-generator-quartz.html
  private val cronExpr = Cron.unsafeParse(cronExpression)

  private def toZonedDateTime(instant: Instant) =
    instant.atZone(tz)

  def nextEvent(): Option[ScheduledAt] = {
    val instant = Instant.now()
    cronExpr.next(toZonedDateTime(instant)).map { next =>
      // add 1 second as between doesn't include the end of the interval
      val delay = Duration.between(instant, next).get(ChronoUnit.SECONDS).seconds.plus(1.second)
      ScheduledAt(next.toInstant, delay)
    }
  }
}

object CronExpression {
  implicit val encodeUser: Encoder[CronExpression] = new Encoder[CronExpression] {
    override def apply(cronExpression: CronExpression) =
      Json.obj("expression" -> cronExpression.cronExpression.asJson, "tz" -> cronExpression.tz.getId.asJson)
  }
} 
Example 14
Source File: DatabaseITest.scala    From cuttle   with Apache License 2.0 5 votes vote down vote up
package com.criteo.cuttle

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

import scala.concurrent.Future

import cats.effect.IO
import doobie.implicits._
import doobie.scalatest.IOChecker

import com.criteo.cuttle.Auth.User

class DatabaseITest extends DatabaseSuite with IOChecker with TestScheduling {
  val dbConfig = DatabaseConfig(
    Seq(DBLocation("localhost", 3388)),
    dbName,
    "root",
    ""
  )

  // IOChecker needs a transactor for performing its queries
  override val transactor: doobie.Transactor[IO] = Database.newHikariTransactor(dbConfig).allocated.unsafeRunSync()._1

  test("should establish the connection and instanciate a trasactor") {
    assert(Database.connect(dbConfig).isInstanceOf[doobie.Transactor[IO]])
  }

  test("should validate getPausedJobIdsQuery") {
    Database.reset()
    Database.connect(dbConfig)
    check(queries.getPausedJobIdsQuery)
  }

  test("should validate paused jobs queries") {
    Database.reset()
    val xa = Database.connect(dbConfig)
    val id = "id1"
    val job = Job(id, testScheduling) { _ =>
      Future.successful(Completed)
    }

    val pausedJob = PausedJob(job.id, User("user1"), Instant.now().truncatedTo(ChronoUnit.SECONDS))

    assert(queries.pauseJob(pausedJob).transact(xa).unsafeRunSync() == 1)
    assert(queries.getPausedJobs.transact(xa).unsafeRunSync() == Seq(pausedJob))
  }

  test("paused_jobs migration(1) should set default values for old pauses") {
    Database.reset()

    Database.schemaEvolutions.head.transact(transactor).unsafeRunSync()
    sql"INSERT INTO paused_jobs VALUES ('1')".update.run.transact(transactor).unsafeRunSync()
    val id = sql"SELECT * FROM paused_jobs".query[String].unique.transact(transactor).unsafeRunSync()
    assert(id == "1")

    Database.schemaEvolutions(1).transact(transactor).unsafeRunSync()

    val pausedJob = sql"SELECT * FROM paused_jobs".query[PausedJob].unique.transact(transactor).unsafeRunSync()
    assert(pausedJob.id == "1")
    assert(pausedJob.user == User("not defined user"))
    assert(pausedJob.date == LocalDateTime.parse("1991-11-01T15:42:00").toInstant(ZoneOffset.UTC))
  }

  test("we should be able to retrieve finished executions") {
    Database.reset()

    Database.doSchemaUpdates.transact(transactor).unsafeRunSync()
    val ctx = TestContext()
    val date = Some(Instant.now())
    val el = ExecutionLog("id", "hello", date, date, ctx.asJson, ExecutionStatus.ExecutionSuccessful, None, 10)
    (0 to 100).foreach { i =>
      queries.logExecution(el.copy(s"${el.id}-$i"), ctx.logIntoDatabase).transact(transactor).unsafeRunSync()
      val executionLogSize = queries.getExecutionLogSize(Set("hello")).transact(transactor).unsafeRunSync()
      assert(executionLogSize == i + 1)
    }
  }
} 
Example 15
Source File: MemoryCacheSnapshot.scala    From AckCord   with MIT License 5 votes vote down vote up
package ackcord

import java.time.temporal.ChronoUnit
import java.time.{Instant, OffsetDateTime}

import ackcord.CacheSnapshot.BotUser
import ackcord.cachehandlers.CacheSnapshotBuilder
import ackcord.data._
import ackcord.util.CoreCompat
import shapeless.tag.@@


  def cleanGarbage(keepMessagesFor: Int, keepTypedFor: Int): CacheProcessor = (processor, builder) => {
    val messagesCleanThreshold = OffsetDateTime.now().minusMinutes(keepMessagesFor)
    val typedCleanThreshold    = Instant.now().minus(keepTypedFor, ChronoUnit.MINUTES)

    builder.messageMap.foreach {
      case (_, messageMap) =>
        CoreCompat.filterInPlace(messageMap)((_, m) => m.timestamp.isAfter(messagesCleanThreshold))
    }

    builder.lastTypedMap.foreach {
      case (_, typedMap) => CoreCompat.filterInPlace(typedMap)((_, i) => i.isAfter(typedCleanThreshold))
    }

    processor
  }
} 
Example 16
Source File: CallStatsAggregatorSpec.scala    From pipelines-examples   with Apache License 2.0 5 votes vote down vote up
package pipelines.examples.carly.aggregator

import java.time.Instant
import java.time.temporal.ChronoUnit

import scala.concurrent.duration._

import scala.util.Random

import pipelines.examples.carly.data._

import pipelines.spark.testkit._
import pipelines.spark.sql.SQLImplicits._

class CallStatsAggregatorSpec extends SparkScalaTestSupport {

  val streamlet = new CallStatsAggregator()
  val testKit = SparkStreamletTestkit(session).withConfigParameterValues(
    ConfigParameterValue(streamlet.GroupByWindow, "1 minute"),
    ConfigParameterValue(streamlet.Watermark, "1 minute"))

  "CallStatsAggregator" should {
    "produce elements to its outlet" in {

      // setup inlet tap on inlet port
      val in = testKit.inletAsTap[CallRecord](streamlet.in)

      // setup outlet tap on outlet port
      val out = testKit.outletAsTap[AggregatedCallStats](streamlet.out)

      val maxUsers = 10
      val crs = (1 to 30).toList.map { i ⇒
        CallRecord(
          s"user-${Random.nextInt(maxUsers)}",
          s"user-${Random.nextInt(maxUsers)}",
          (if (i % 2 == 0) "incoming" else "outgoing"),
          Random.nextInt(50),
          Instant.now.minus(Random.nextInt(40), ChronoUnit.MINUTES).toEpochMilli / 1000
        )
      }

      in.addData(crs)

      testKit.run(streamlet, Seq(in), Seq(out), 30.seconds)

      // get data from outlet tap
      val results = out.asCollection(session)

      // assert
      results.size must be > 0
    }
  }
} 
Example 17
Source File: CallRecordValidationSpec.scala    From pipelines-examples   with Apache License 2.0 5 votes vote down vote up
package pipelines.examples.carly.ingestor

import java.time.Instant
import java.time.temporal.ChronoUnit

import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.testkit._
import org.scalatest._
import org.scalatest.concurrent._

import pipelines.akkastream.testkit.scaladsl._

import pipelines.examples.carly.data._

class CallRecordValidationSpec extends WordSpec with MustMatchers with ScalaFutures with BeforeAndAfterAll {
  private implicit val system = ActorSystem("CallRecordValidationSpec")
  private implicit val mat = ActorMaterializer()

  override def afterAll: Unit = {
    TestKit.shutdownActorSystem(system)
  }

  "A CallRecordValidation" should {
    "split incoming data into valid call records and those outside the time range" in {
      val testkit = AkkaStreamletTestKit(system, mat)
      val streamlet = new CallRecordValidation()

      val instant = Instant.now.toEpochMilli / 1000
      val past = Instant.now.minus(5000, ChronoUnit.DAYS).toEpochMilli / 1000

      val cr1 = CallRecord("user-1", "user-2", "f", 10L, instant)
      val cr2 = CallRecord("user-1", "user-2", "f", 15L, instant)
      val cr3 = CallRecord("user-1", "user-2", "f", 18L, instant)
      val cr4 = CallRecord("user-1", "user-2", "f", 40L, past)
      val cr5 = CallRecord("user-1", "user-2", "f", 70L, past)

      val source = Source(Vector(cr1, cr2, cr3, cr4, cr5))

      val in = testkit.inletFromSource(streamlet.in, source)
      val left = testkit.outletAsTap(streamlet.left)
      val right = testkit.outletAsTap(streamlet.right)

      testkit.run(streamlet, in, List(left, right), () ⇒ {
        right.probe.expectMsg(("user-1", cr1))
        right.probe.expectMsg(("user-1", cr2))
        right.probe.expectMsg(("user-1", cr3))
        left.probe.expectMsg((cr4.toString, InvalidRecord(cr4.toString, "Timestamp outside range!")))
        left.probe.expectMsg((cr5.toString, InvalidRecord(cr5.toString, "Timestamp outside range!")))
      })

      left.probe.expectMsg(Completed)
      right.probe.expectMsg(Completed)
    }
  }
} 
Example 18
Source File: CallRecordMergeSpec.scala    From pipelines-examples   with Apache License 2.0 5 votes vote down vote up
package pipelines.examples.carly.ingestor

import java.time.Instant
import java.time.temporal.ChronoUnit

import akka.actor._
import akka.stream._
import akka.stream.scaladsl._
import akka.testkit._
import org.scalatest._
import org.scalatest.concurrent._

import pipelines.akkastream.testkit.scaladsl._
import pipelines.examples.carly.data._

class CallRecordMergeSpec extends WordSpec with MustMatchers with ScalaFutures with BeforeAndAfterAll {

  private implicit val system = ActorSystem("CallRecordMergeSpec")
  private implicit val mat = ActorMaterializer()

  override def afterAll: Unit = {
    TestKit.shutdownActorSystem(system)
  }

  "A CallRecordMerge" should {
    "merge incoming data" in {
      val testkit = AkkaStreamletTestKit(system, mat)
      val streamlet = new CallRecordMerge

      val instant = Instant.now.toEpochMilli / 1000
      val past = Instant.now.minus(5000, ChronoUnit.DAYS).toEpochMilli / 1000

      val cr1 = CallRecord("user-1", "user-2", "f", 10L, instant)
      val cr2 = CallRecord("user-1", "user-2", "f", 15L, instant)
      val cr3 = CallRecord("user-1", "user-2", "f", 18L, instant)
      val cr4 = CallRecord("user-1", "user-2", "f", 40L, past)
      val cr5 = CallRecord("user-1", "user-2", "f", 70L, past)
      val cr6 = CallRecord("user-3", "user-1", "f", 80L, past)

      val source0 = Source(Vector(cr1, cr2, cr3))
      val source1 = Source(Vector(cr4, cr5))
      val source2 = Source(Vector(cr6))

      val in0 = testkit.inletFromSource(streamlet.in0, source0)
      val in1 = testkit.inletFromSource(streamlet.in1, source1)
      val in2 = testkit.inletFromSource(streamlet.in2, source2)
      val out = testkit.outletAsTap(streamlet.out)

      testkit.run(streamlet, List(in0, in1, in2), out, () ⇒ {
        out.probe.expectMsg(("user-1", cr1))
        out.probe.expectMsg(("user-1", cr4))
        out.probe.expectMsg(("user-3", cr6))
        out.probe.expectMsg(("user-1", cr2))
        out.probe.expectMsg(("user-1", cr5))
        out.probe.expectMsg(("user-1", cr3))
      })

      out.probe.expectMsg(Completed)
    }
  }
} 
Example 19
Source File: ExperimentVariantEventTest.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package domains.abtesting
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.scaladsl.{Flow, Sink, Source}
import domains.Key
import domains.abtesting.events._
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import test.IzanamiSpec

class ExperimentVariantEventTest extends IzanamiSpec with ScalaFutures with IntegrationPatience {

  "ExperimentVariantEvent" must {
    "aggregate event" in {

      implicit val system: ActorSystem = ActorSystem()

      val variantId = "vId"
      val variant   = Variant(variantId, "None", None, Traffic(0), None)
      val flow: Flow[ExperimentVariantEvent, VariantResult, NotUsed] =
        ExperimentVariantEvent.eventAggregation("experiment.id", 1, ChronoUnit.HOURS)

      val firstDate = LocalDateTime.now().minus(5, ChronoUnit.HOURS)

      val experimentKey = Key(s"experiment:id")
      def experimentVariantEventKey(counter: Int): ExperimentVariantEventKey =
        ExperimentVariantEventKey(experimentKey, variantId, s"client:id:$counter", "namespace", s"$counter")
      def clientId(i: Int): String    = s"client:id:$i"
      def date(i: Int): LocalDateTime = firstDate.plus(15 * i, ChronoUnit.MINUTES)

      val source = (1 to 20)
        .flatMap { counter =>
          val d   = date(counter)
          val key = experimentVariantEventKey(counter)

          counter match {
            case i if i % 2 > 0 =>
              List(ExperimentVariantDisplayed(key, experimentKey, clientId(i), variant, d, 0, variantId))
            case i =>
              List(
                ExperimentVariantDisplayed(key, experimentKey, clientId(i), variant, d, 0, variantId),
                ExperimentVariantWon(key, experimentKey, clientId(i), variant, d, 0, variantId)
              )
          }
        }

      val expectedEvents = Seq(
        ExperimentResultEvent(experimentKey, variant, date(1), 0.0, "vId"),
        ExperimentResultEvent(experimentKey, variant, date(5), 40.0, "vId"),
        ExperimentResultEvent(experimentKey, variant, date(9), 44.44444444444444, "vId"),
        ExperimentResultEvent(experimentKey, variant, date(13), 46.15384615384615, "vId"),
        ExperimentResultEvent(experimentKey, variant, date(17), 47.05882352941177, "vId")
      )

      val evts      = Source(source).via(flow).runWith(Sink.seq).futureValue
      val allEvents = evts.flatMap(_.events)

      allEvents must be(expectedEvents)
    }
  }

} 
Example 20
Source File: RemoveLogsTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.database.test

import java.io.File
import java.time.Instant
import java.time.temporal.ChronoUnit

import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

import common.StreamLogging
import common.TestUtils
import common.WhiskProperties
import common.WskActorSystem
import org.apache.openwhisk.core.entity.ActivationId
import org.apache.openwhisk.core.entity.EntityName
import org.apache.openwhisk.core.entity.EntityPath
import org.apache.openwhisk.core.entity.Subject
import org.apache.openwhisk.core.entity.WhiskActivation
import org.apache.openwhisk.core.entity.ActivationLogs

@RunWith(classOf[JUnitRunner])
class RemoveLogsTests extends FlatSpec with DatabaseScriptTestUtils with StreamLogging with WskActorSystem {

  val designDocPath = WhiskProperties
    .getFileRelativeToWhiskHome("ansible/files/logCleanup_design_document_for_activations_db.json")
    .getAbsolutePath
  val removeLogsToolPath =
    WhiskProperties.getFileRelativeToWhiskHome("tools/db/deleteLogsFromActivations.py").getAbsolutePath

  
  def removeLogsTool(dbUrl: DatabaseUrl, dbName: String, days: Int, docsPerRequest: Int = 20) = {
    println(s"Running removeLogs tool: ${dbUrl.safeUrl}, $dbName, $days, $docsPerRequest")

    val cmd = Seq(
      python,
      removeLogsToolPath,
      "--dbUrl",
      dbUrl.url,
      "--dbName",
      dbName,
      "--days",
      days.toString,
      "--docsPerRequest",
      docsPerRequest.toString)
    val rr = TestUtils.runCmd(0, new File("."), cmd: _*)
  }

  behavior of "Activation Log Cleanup Script"

  it should "delete logs in old activation and keep log in new activation" in {
    val dbName = dbPrefix + "test_log_cleanup_1"
    val db = createDatabase(dbName, Some(designDocPath))

    try {
      // Create an old and a new activation
      val oldActivation = WhiskActivation(
        namespace = EntityPath("testns1"),
        name = EntityName("testname1"),
        subject = Subject("test-sub1"),
        activationId = ActivationId.generate(),
        start = Instant.now.minus(2, ChronoUnit.DAYS),
        end = Instant.now,
        logs = ActivationLogs(Vector("first line1", "second line1")))

      val newActivation = WhiskActivation(
        namespace = EntityPath("testns2"),
        name = EntityName("testname2"),
        subject = Subject("test-sub2"),
        activationId = ActivationId.generate(),
        start = Instant.now,
        end = Instant.now,
        logs = ActivationLogs(Vector("first line2", "second line2")))

      db.putDoc(oldActivation.docid.asString, oldActivation.toJson).futureValue shouldBe 'right
      db.putDoc(newActivation.docid.asString, newActivation.toJson).futureValue shouldBe 'right

      // Run the tool to delete logs from activations that are older than 1 day
      removeLogsTool(dbUrl, dbName, 1)

      // Check, that the new activation is untouched and the old activation is without logs now
      val newActivationRequest = db.getDoc(newActivation.docid.asString).futureValue
      newActivationRequest shouldBe 'right
      val newActivationFromDb = newActivationRequest.right.get.convertTo[WhiskActivation]
      // Compare the Json of the Whiskactivations in case the test fails -> better log output
      newActivationFromDb.toJson shouldBe newActivation.toJson

      val oldActivationRequest = db.getDoc(oldActivation.docid.asString).futureValue
      oldActivationRequest shouldBe 'right
      val oldActivationFromDb = oldActivationRequest.right.get.convertTo[WhiskActivation]
      // Compare the Json of the Whiskactivations in case the test fails -> better log output
      oldActivationFromDb.toJson shouldBe oldActivation.withoutLogs.toJson
    } finally {
      removeDatabase(dbName)
    }
  }
} 
Example 21
Source File: ExpiringMap.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.jsonrpc

import java.time.temporal.ChronoUnit
import java.time.Duration

import io.iohk.ethereum.jsonrpc.ExpiringMap.ValueWithDuration

import scala.collection.mutable
import scala.util.Try

object ExpiringMap {

 case class ValueWithDuration[V](value: V, expiration: Duration)

  def empty[K, V](defaultElementRetentionTime: Duration): ExpiringMap[K, V] =
    new ExpiringMap(mutable.Map.empty, defaultElementRetentionTime)
}

//TODO: Make class thread safe
class ExpiringMap[K, V] private (val underlying: mutable.Map[K, ValueWithDuration[V]],
                                 val defaultRetentionTime: Duration) {
  private val maxHoldDuration = ChronoUnit.CENTURIES.getDuration

  def addFor(k: K, v: V, duration: Duration): ExpiringMap[K, V] = {
    underlying += k -> ValueWithDuration(v, Try(currentPlus(duration)).getOrElse(currentPlus(maxHoldDuration)))
    this
  }

  def add(k: K, v: V, duration: Duration): ExpiringMap[K, V] = {
    addFor(k, v, duration)
  }

  def addForever(k: K, v: V): ExpiringMap[K, V] =
    addFor(k, v, maxHoldDuration)

  def add(k: K, v: V): ExpiringMap[K, V] =
    addFor(k, v, defaultRetentionTime)

  def remove(k: K): ExpiringMap[K, V] = {
    underlying -= k
    this
  }

  def get(k: K): Option[V] = {
    underlying.get(k).flatMap(value =>
      if (isNotExpired(value))
        Some(value.value)
      else {
        remove(k)
        None
      }
    )
  }

  private def isNotExpired(value: ValueWithDuration[V]) =
    currentNanoDuration().minus(value.expiration).isNegative

  private def currentPlus(duration: Duration) =
    currentNanoDuration().plus(duration)

  private def currentNanoDuration() =
    Duration.ofNanos(System.nanoTime())

} 
Example 22
Source File: ChronoUnitTest.scala    From scala-js-java-time   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package org.scalajs.testsuite.javalib.time.temporal

import java.time.temporal.ChronoUnit

import org.junit.Test
import org.junit.Assert._

class ChronoUnitTest {
  import ChronoUnit._

  @Test def test_isDurationEstimated(): Unit = {
    for (u <- ChronoUnit.values)
      assertTrue(u.isDurationEstimated != u.isTimeBased)
  }

  @Test def test_isDateBased(): Unit = {
    assertFalse(NANOS.isDateBased)
    assertFalse(MICROS.isDateBased)
    assertFalse(MILLIS.isDateBased)
    assertFalse(SECONDS.isDateBased)
    assertFalse(MINUTES.isDateBased)
    assertFalse(HOURS.isDateBased)
    assertFalse(HALF_DAYS.isDateBased)
    assertTrue(DAYS.isDateBased)
    assertTrue(WEEKS.isDateBased)
    assertTrue(MONTHS.isDateBased)
    assertTrue(YEARS.isDateBased)
    assertTrue(DECADES.isDateBased)
    assertTrue(CENTURIES.isDateBased)
    assertTrue(MILLENNIA.isDateBased)
    assertTrue(ERAS.isDateBased)
    assertFalse(FOREVER.isDateBased)
  }

  @Test def test_isTimeBased(): Unit = {
    assertTrue(NANOS.isTimeBased)
    assertTrue(MICROS.isTimeBased)
    assertTrue(MILLIS.isTimeBased)
    assertTrue(SECONDS.isTimeBased)
    assertTrue(MINUTES.isTimeBased)
    assertTrue(HOURS.isTimeBased)
    assertTrue(HALF_DAYS.isTimeBased)
    assertFalse(DAYS.isTimeBased)
    assertFalse(WEEKS.isTimeBased)
    assertFalse(MONTHS.isTimeBased)
    assertFalse(YEARS.isTimeBased)
    assertFalse(DECADES.isTimeBased)
    assertFalse(CENTURIES.isTimeBased)
    assertFalse(MILLENNIA.isTimeBased)
    assertFalse(ERAS.isTimeBased)
    assertFalse(FOREVER.isTimeBased)
  }

  @Test def test_values(): Unit = {
    val units = Array[AnyRef](NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS,
        HALF_DAYS, DAYS, WEEKS, MONTHS, YEARS, DECADES, CENTURIES, MILLENNIA,
        ERAS, FOREVER)
    assertArrayEquals(units, values.asInstanceOf[Array[AnyRef]])
  }

  @Test def test_valueOf(): Unit = {
    assertEquals(NANOS, valueOf("NANOS"))
    assertEquals(MICROS, valueOf("MICROS"))
    assertEquals(MILLIS, valueOf("MILLIS"))
    assertEquals(SECONDS, valueOf("SECONDS"))
    assertEquals(MINUTES, valueOf("MINUTES"))
    assertEquals(HOURS, valueOf("HOURS"))
    assertEquals(HALF_DAYS, valueOf("HALF_DAYS"))
    assertEquals(DAYS, valueOf("DAYS"))
    assertEquals(WEEKS, valueOf("WEEKS"))
    assertEquals(MONTHS, valueOf("MONTHS"))
    assertEquals(YEARS, valueOf("YEARS"))
    assertEquals(DECADES, valueOf("DECADES"))
    assertEquals(CENTURIES, valueOf("CENTURIES"))
    assertEquals(MILLENNIA, valueOf("MILLENNIA"))
    assertEquals(ERAS, valueOf("ERAS"))
    assertEquals(FOREVER, valueOf("FOREVER"))
  }
} 
Example 23
Source File: TemporalAmountTest.scala    From scala-js-java-time   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package org.scalajs.testsuite.javalib.time

import java.time.temporal.{UnsupportedTemporalTypeException, ChronoUnit, TemporalAmount}

import org.junit.Test
import org.junit.Assert._
import org.scalajs.testsuite.utils.AssertThrows._

abstract class TemporalAmountTest {
  val samples: Seq[TemporalAmount]

  val units: Seq[ChronoUnit]

  @Test def test_get_unsupported_unit(): Unit = {
    val illegalUnits = ChronoUnit.values.filterNot(units.contains)
    for {
      amount <- samples
      unit <- illegalUnits
    } {
      expectThrows(classOf[UnsupportedTemporalTypeException], amount.get(unit))
    }
  }

  @Test def test_getUnits(): Unit = {
    for (amount <- samples)
      assertArrayEquals(units.toArray[AnyRef], amount.getUnits.toArray())
  }
} 
Example 24
Source File: DateTimeTestUtil.scala    From scala-js-java-time   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package org.scalajs.testsuite.javalib.time

import java.time.DateTimeException
import java.time.temporal.{ChronoUnit, Temporal, UnsupportedTemporalTypeException}

import org.junit.Assert._

object DateTimeTestUtil {
  import org.scalajs.testsuite.utils.AssertThrows._

  val dateBasedUnits = ChronoUnit.values.filter(_.isDateBased)

  val timeBasedUnits = ChronoUnit.values.filter(_.isTimeBased)

  def testDateTime(actual: => Any)(expected: => Any): Unit = {
    try {
      val e = expected
      //expectNoException(actual)
      assertEquals(e, actual)
    } catch {
      case _: UnsupportedTemporalTypeException =>
        expectThrows(classOf[UnsupportedTemporalTypeException], actual)

      case _: DateTimeException =>
        expectThrows(classOf[DateTimeException], actual)

      case _: ArithmeticException =>
        expectThrows(classOf[ArithmeticException], actual)
    }
  }
} 
Example 25
Source File: ZonedDateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws


import java.time.temporal.ChronoUnit
import java.time.{Duration, LocalDate, LocalTime}

import cats.kernel.laws.discipline.{catsLawsIsEqToProp => p}
import cats.kernel.laws._
import cats.instances.long._
import dtc._
import dtc.syntax.zoned._
import org.scalacheck.Prop._
import org.scalacheck.{Arbitrary, Gen, Prop}


trait ZonedDateTimeLaws[A] {
  implicit def D: Zoned[A]

  val genA: Gen[A]
  val genDateAndDurationWithinSameOffset: Gen[(A, Duration)]
  val genDataSuite: Gen[ZonedDateTimeTestData[A]]
  val genLocalDate: Gen[LocalDate]
  val genLocalTime: Gen[LocalTime]
  val genValidYear: Gen[Int]
  val genTimeZone: Gen[TimeZoneId]

  def crossOffsetAddition: Prop = forAll(genDataSuite) { data =>
    val target = D.plus(data.source, data.diff)
    p(D.offset(target) <-> data.targetOffset) &&
      (D.date(target) <-> data.targetDate) &&
      (D.time(target) <-> data.targetTime.truncatedTo(ChronoUnit.MILLIS))
  }

  def localTimeAndOffsetCorrelation: Prop = forAll(genA, genTimeZone) { (date: A, zone: TimeZoneId) =>
    val target = D.withZoneSameInstant(date, zone)
    D.time(date) <-> D.time(target).plusSeconds((date.offset.seconds - target.offset.seconds).toLong)
  }

  def withZoneSameInstantGivesSameInstant: Prop = forAll(genA, genTimeZone) { (date: A, zone: TimeZoneId) =>
    val target = D.withZoneSameInstant(date, zone)
    p(D.zone(target) <-> zone) &&
      (D.millisecondsUntil(date, target) <-> 0L)
  }
}

object ZonedDateTimeLaws {
  def apply[A](
    gDateAndDurationWithinSameDST: Gen[(A, Duration)],
    gDataSuite: Gen[ZonedDateTimeTestData[A]],
    gLocalTime: Gen[LocalTime],
    gLocalDate: Gen[LocalDate],
    gValidYear: Gen[Int],
    gTimeZone: Gen[TimeZoneId])(
    implicit ev: Zoned[A],
    arbA: Arbitrary[A]): ZonedDateTimeLaws[A] = new ZonedDateTimeLaws[A] {

    def D: Zoned[A] = ev

    val genTimeZone: Gen[TimeZoneId] = gTimeZone
    val genDateAndDurationWithinSameOffset: Gen[(A, Duration)] = gDateAndDurationWithinSameDST
    val genDataSuite: Gen[ZonedDateTimeTestData[A]] = gDataSuite
    val genLocalDate: Gen[LocalDate] = gLocalDate
    val genLocalTime: Gen[LocalTime] = gLocalTime
    val genValidYear: Gen[Int] = gValidYear
    val genA: Gen[A] = arbA.arbitrary
  }
} 
Example 26
Source File: LocalDateTimeLaws.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.laws

import java.time.temporal.{ChronoField, ChronoUnit}
import java.time.{LocalDate, LocalTime}

import cats.kernel.laws._
import cats.kernel.laws.discipline.{catsLawsIsEqToProp => p}
import dtc.Local
import dtc.syntax.local._
import org.scalacheck.{Gen, Prop}
import org.scalacheck.Prop.forAll


trait LocalDateTimeLaws[A] {
  implicit def D: Local[A]

  val genLocalDate: Gen[LocalDate]
  val genLocalTime: Gen[LocalTime]

  def constructorConsistency: Prop = forAll(genLocalDate, genLocalTime) { (date: LocalDate, time: LocalTime) =>
    val dt = D.of(date, time)
    p(dt.date <-> date) && (dt.time <-> time.truncatedTo(ChronoUnit.MILLIS))
  }

  def plainConstructorConsistency: Prop = forAll(genLocalDate, genLocalTime) { (date: LocalDate, time: LocalTime) =>
    val dt = D.of(
      date.getYear, date.getMonthValue, date.getDayOfMonth,
      time.getHour, time.getMinute, time.getSecond, time.get(ChronoField.MILLI_OF_SECOND))
    p(dt.date <-> date) && (dt.time <-> time.truncatedTo(ChronoUnit.MILLIS))
  }
}

object LocalDateTimeLaws {
  def apply[A](
    gLocalTime: Gen[LocalTime],
    gLocalDate: Gen[LocalDate])(
    implicit ev: Local[A]): LocalDateTimeLaws[A] = new LocalDateTimeLaws[A] {
    def D: Local[A] = ev
    val genLocalDate: Gen[LocalDate] = gLocalDate
    val genLocalTime: Gen[LocalTime] = gLocalTime
  }
} 
Example 27
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 28
Source File: ZonedDateTimeInstanceWithoutOrder.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.instances

import java.time._
import java.time.temporal.{ChronoField, ChronoUnit}

import dtc.{Offset, TimeZoneId, Zoned, millisToNanos, truncateToMillis}
import dtc.syntax.timeZone._

trait ZonedDateTimeInstanceWithoutOrder extends Zoned[ZonedDateTime] { self =>
  def capture(date: LocalDate, time: LocalTime, zone: TimeZoneId): ZonedDateTime =
    ZonedDateTime.of(date, time.truncatedTo(ChronoUnit.MILLIS), zone.zoneId)

  def withZoneSameInstant(x: ZonedDateTime, zone: TimeZoneId): ZonedDateTime = x.withZoneSameInstant(zone.zoneId)
  def withZoneSameLocal(x: ZonedDateTime, zone: TimeZoneId): ZonedDateTime = x.withZoneSameLocal(zone.zoneId)
  def zone(x: ZonedDateTime): TimeZoneId = TimeZoneId(x.getZone.getId)

  def date(x: ZonedDateTime): LocalDate = x.toLocalDate
  def time(x: ZonedDateTime): LocalTime = x.toLocalTime.truncatedTo(ChronoUnit.MILLIS)

  def plus(x: ZonedDateTime, d: Duration): ZonedDateTime = x.plus(truncateToMillis(d))
  def minus(x: ZonedDateTime, d: Duration): ZonedDateTime = x.minus(truncateToMillis(d))
  def plusDays(x: ZonedDateTime, days: Int): ZonedDateTime = x.plusDays(days.toLong)
  def plusMonths(x: ZonedDateTime, months: Int): ZonedDateTime = x.plusMonths(months.toLong)
  def plusYears(x: ZonedDateTime, years: Int): ZonedDateTime = x.plusYears(years.toLong)

  def withYear(x: ZonedDateTime, year: Int): ZonedDateTime = x.withYear(year)
  def withMonth(x: ZonedDateTime, month: Int): ZonedDateTime = x.withMonth(month)
  def withDayOfMonth(x: ZonedDateTime, dayOfMonth: Int): ZonedDateTime = x.withDayOfMonth(dayOfMonth)
  def withHour(x: ZonedDateTime, hour: Int): ZonedDateTime = x.withHour(hour)
  def withMinute(x: ZonedDateTime, minute: Int): ZonedDateTime = x.withMinute(minute)
  def withSecond(x: ZonedDateTime, second: Int): ZonedDateTime = x.withSecond(second)
  def withMillisecond(x: ZonedDateTime, millisecond: Int): ZonedDateTime = x.withNano(millisToNanos(millisecond))
  def withTime(x: ZonedDateTime, time: LocalTime): ZonedDateTime = ZonedDateTime.of(date(x), time, zone(x).zoneId)
  def withDate(x: ZonedDateTime, date: LocalDate): ZonedDateTime = ZonedDateTime.of(date, time(x), zone(x).zoneId)

  def offset(x: ZonedDateTime): Offset = Offset(x.getOffset.getTotalSeconds)

  def dayOfWeek(x: ZonedDateTime): DayOfWeek = x.getDayOfWeek
  def dayOfMonth(x: ZonedDateTime): Int = x.getDayOfMonth
  def month(x: ZonedDateTime): Int = x.getMonthValue
  def year(x: ZonedDateTime): Int = x.getYear
  def millisecond(x: ZonedDateTime): Int = x.get(ChronoField.MILLI_OF_SECOND)
  def second(x: ZonedDateTime): Int = x.getSecond
  def minute(x: ZonedDateTime): Int = x.getMinute
  def hour(x: ZonedDateTime): Int = x.getHour

  def yearsUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.YEARS)
  def monthsUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.MONTHS)
  def daysUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.DAYS)
  def hoursUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.HOURS)
  def minutesUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.MINUTES)
  def secondsUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.SECONDS)
  def millisecondsUntil(x: ZonedDateTime, until: ZonedDateTime): Long = x.until(until, ChronoUnit.MILLIS)

  def utc(x: ZonedDateTime): (LocalDate, LocalTime) = {
    val utcTime = x.withZoneSameInstant(ZoneOffset.UTC)
    utcTime.toLocalDate -> utcTime.toLocalTime
  }
} 
Example 29
Source File: localDateTime.scala    From dtc   with Apache License 2.0 5 votes vote down vote up
package dtc.instances

import java.time.temporal.{ChronoField, ChronoUnit}
import java.time._

import dtc._

object localDateTime {
  implicit val localDateTimeDTC: Local[LocalDateTime] =
    new Local[LocalDateTime] {
      def compare(x: LocalDateTime, y: LocalDateTime): Int = x.compareTo(y)

      def date(x: LocalDateTime): LocalDate = x.toLocalDate
      def time(x: LocalDateTime): LocalTime = x.toLocalTime.truncatedTo(ChronoUnit.MILLIS)

      def of(date: LocalDate, time: LocalTime): LocalDateTime =
        LocalDateTime.of(date, time.truncatedTo(ChronoUnit.MILLIS))
      def of(
        year: Int, month: Int, day: Int,
        hour: Int, minute: Int, second: Int, millisecond: Int): LocalDateTime =
        LocalDateTime.of(year, month, day, hour, minute, second, millisToNanos(millisecond))

      def plus(x: LocalDateTime, d: Duration): LocalDateTime = x.plus(truncateToMillis(d))
      def minus(x: LocalDateTime, d: Duration): LocalDateTime = x.minus(truncateToMillis(d))
      def plusDays(x: LocalDateTime, days: Int): LocalDateTime = x.plusDays(days.toLong)
      def plusMonths(x: LocalDateTime, months: Int): LocalDateTime = x.plusMonths(months.toLong)
      def plusYears(x: LocalDateTime, years: Int): LocalDateTime = x.plusYears(years.toLong)

      def withYear(x: LocalDateTime, year: Int): LocalDateTime = x.withYear(year)
      def withMonth(x: LocalDateTime, month: Int): LocalDateTime = x.withMonth(month)
      def withDayOfMonth(x: LocalDateTime, dayOfMonth: Int): LocalDateTime = x.withDayOfMonth(dayOfMonth)
      def withHour(x: LocalDateTime, hour: Int): LocalDateTime = x.withHour(hour)
      def withMinute(x: LocalDateTime, minute: Int): LocalDateTime = x.withMinute(minute)
      def withSecond(x: LocalDateTime, second: Int): LocalDateTime = x.withSecond(second)
      def withMillisecond(x: LocalDateTime, millisecond: Int): LocalDateTime = x.withNano(millisToNanos(millisecond))
      def withTime(x: LocalDateTime, time: LocalTime): LocalDateTime = LocalDateTime.of(date(x), time)
      def withDate(x: LocalDateTime, date: LocalDate): LocalDateTime = LocalDateTime.of(date, time(x))

      def dayOfWeek(x: LocalDateTime): DayOfWeek = x.getDayOfWeek
      def dayOfMonth(x: LocalDateTime): Int = x.getDayOfMonth
      def month(x: LocalDateTime): Int = x.getMonthValue
      def year(x: LocalDateTime): Int = x.getYear
      def millisecond(x: LocalDateTime): Int = x.get(ChronoField.MILLI_OF_SECOND)
      def second(x: LocalDateTime): Int = x.getSecond
      def minute(x: LocalDateTime): Int = x.getMinute
      def hour(x: LocalDateTime): Int = x.getHour

      def yearsUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.YEARS)
      def monthsUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.MONTHS)
      def daysUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.DAYS)
      def hoursUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.HOURS)
      def minutesUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.MINUTES)
      def secondsUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.SECONDS)
      def millisecondsUntil(x: LocalDateTime, until: LocalDateTime): Long = x.until(until, ChronoUnit.MILLIS)
    }

  implicit val captureLocalDateTime: Capture[LocalDateTime] = new Capture[LocalDateTime] {
    def capture(date: LocalDate, time: LocalTime, zone: TimeZoneId): LocalDateTime =
      ZonedDateTime.of(date, time, ZoneId.of(zone.id)).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime
  }

} 
Example 30
Source File: Common.scala    From chymyst-core   with Apache License 2.0 5 votes vote down vote up
package io.chymyst.benchmark

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

object Common {
  val warmupTimeMs = 50L

  def elapsed(initTime: LocalDateTime): Long = initTime.until(LocalDateTime.now, ChronoUnit.MILLIS)

  def elapsed(initTime: Long): Long = System.currentTimeMillis() - initTime

  def timeThis(task: => Unit): Long = {
    val initTime = LocalDateTime.now
    task
    elapsed(initTime)
  }

  def timeWithPriming(task: => Unit): Long = {
    task // this is just priming, no measurement

    val result1 = timeThis {
      task
    }
    val result2 = timeThis {
      task
    }
    (result1 + result2 + 1) / 2
  }

  def waitSome(): Unit = Thread.sleep(warmupTimeMs)

} 
Example 31
Source File: GeneratableStringFormats.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.gen.formats

import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}

import de.leanovate.swaggercheck.generators.Generators
import de.leanovate.swaggercheck.schema.model.formats.StringFormats
import de.leanovate.swaggercheck.schema.model.{JsonPath, ValidationResult}
import org.scalacheck.Gen

object GeneratableStringFormats {

  object URLString extends GeneratableFormat[String] {
    override def generate: Gen[String] = Generators.url

    override def validate(path: JsonPath, value: String): ValidationResult =
      StringFormats.URLString.validate(path, value)
  }

  object URIString extends GeneratableFormat[String] {
    override def generate: Gen[String] = Generators.uri

    override def validate(path: JsonPath, value: String): ValidationResult =
      StringFormats.URIString.validate(path, value)
  }

  object UUIDString extends GeneratableFormat[String] {
    override def generate: Gen[String] =
      Gen.uuid.map(_.toString)

    override def validate(path: JsonPath, value: String): ValidationResult =
      StringFormats.UUIDString.validate(path, value)
  }

  object EmailString extends GeneratableFormat[String] {
    val emailPattern = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])""".r

    override def generate: Gen[String] = Generators.email

    override def validate(path: JsonPath, value: String): ValidationResult =
      StringFormats.EmailString.validate(path, value)
  }

  object DateString extends GeneratableFormat[String] {
    override def generate: Gen[String] = {
      Gen.choose[Int](-300000, 300000).map {
        diff: Int =>
          val instant = LocalDate.ofEpochDay(diff)
          DateTimeFormatter.ISO_DATE.format(instant)
      }
    }

    override def validate(path: JsonPath, value: String): ValidationResult =
      StringFormats.DateString.validate(path, value)
  }

  object DateTimeString extends GeneratableFormat[String] {
    override def generate: Gen[String] = {
      Gen.choose[Long](Long.MinValue, Long.MaxValue).map {
        diff: Long =>
          val instant = Instant.now().plus(diff, ChronoUnit.NANOS)
          DateTimeFormatter.ISO_INSTANT.format(instant)
      }
    }

    override def validate(path: JsonPath, value: String): ValidationResult =
      StringFormats.DateTimeString.validate(path, value)
  }

  val defaultFormats = Map(
    "url" -> URLString,
    "uri" -> URIString,
    "uuid" -> UUIDString,
    "email" -> EmailString,
    "date" -> DateString,
    "date-time" -> DateTimeString
  )
} 
Example 32
Source File: AnyThing.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.net.{URI, URL}
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}
import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.{Json, OFormat}

import scala.util.Try

case class AnyThing(
                     anUUID: String,
                     anURL: String,
                     anURI: String,
                     anEmail: String,
                     aDate: LocalDate,
                     aDateTime: Instant,
                     anInt32: Int,
                     anInt64: Long,
                     aFloat: Float,
                     aDouble: Double,
                     aBoolean: Boolean,
                     anEnum: String,
                     aMap: Map[String, String]
                   ) {
  def isValid: Boolean = {
    Try {
      UUID.fromString(anUUID)
      new URL(anURL)
      new URI(anURI)
    }.isSuccess && Set("V1", "V2", "V3").contains(anEnum)
  }
}

object AnyThing {
  implicit val jsonFormat: OFormat[AnyThing] = Json.format[AnyThing]

  implicit val arbitrary = Arbitrary(for {
    anUUID <- Gen.uuid.map(_.toString)
    anURL <- Generators.url
    anURI <- Generators.uri
    anEmail <- Generators.email
    aDate <- Arbitrary.arbitrary[Int].map(diff => LocalDate.now().plus(diff, ChronoUnit.DAYS))
    aDateTime <- Arbitrary.arbitrary[Long].map(diff => Instant.now().plus(diff, ChronoUnit.NANOS))
    anInt32 <- Arbitrary.arbitrary[Int]
    anInt64 <- Arbitrary.arbitrary[Long]
    aFloat <- Arbitrary.arbitrary[Float]
    aDouble <- Arbitrary.arbitrary[Double]
    aBoolean <- Arbitrary.arbitrary[Boolean]
    anEnum <- Gen.oneOf("V1", "V2", "V3")
    aMap <- Arbitrary.arbitrary[Map[String, String]]
  } yield AnyThing(anUUID, anURL, anURI, anEmail, aDate, aDateTime, anInt32, anInt64, aFloat, aDouble, aBoolean, anEnum, aMap))
} 
Example 33
Source File: StringFormats.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.model.formats

import java.net.{URI, URL}
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}
import java.util.UUID

import de.leanovate.swaggercheck.schema.model.{JsonPath, ValidationResult}

import scala.util.Try

object StringFormats {

  object URLString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(new URL(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not an url: $path")
  }

  object URIString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(new URI(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not an uri: $path")
  }

  object UUIDString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(UUID.fromString(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not an uuid: $path")
  }

  object EmailString extends ValueFormat[String] {
    val emailPattern = """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])""".r

    override def validate(path: JsonPath, value: String): ValidationResult =
      if (emailPattern.pattern.matcher(value).matches()) {
        ValidationResult.success
      } else {
        ValidationResult.error(s"'$value' is not an email: $path")
      }  }

  object DateString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(DateTimeFormatter.ISO_DATE.parse(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not a date: $path")
  }

  object DateTimeString extends ValueFormat[String] {
    override def validate(path: JsonPath, value: String): ValidationResult =
      if (Try(DateTimeFormatter.ISO_DATE_TIME.parse(value)).isSuccess)
        ValidationResult.success
      else
        ValidationResult.error(s"'$value' is not a date-time: $path")
  }

  val defaultFormats = Map(
    "url" -> URLString,
    "uri" -> URIString,
    "uuid" -> UUIDString,
    "email" -> EmailString,
    "date" -> DateString,
    "date-time" -> DateTimeString
  )
} 
Example 34
Source File: SurfaceJVMTest.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.surface

import java.time.temporal.ChronoUnit
import java.io.File

object SurfaceJVMTest {
  type MyChrono = ChronoUnit
}

import SurfaceJVMTest._
class SurfaceJVMTest extends SurfaceSpec {
  def `resolve ParSeq`: Unit = {
    pendingUntil("ParSeq is not available in Scala 2.13")
    //import scala.collection.parallel.ParSeq
    //check(Surface.of[ParSeq[Int]], "ParSeq[Int]")
  }

  def `resolve java util type`: Unit = {
    check(Surface.of[File], "File")
    check(Surface.of[java.util.Date], "Date")
    check(Surface.of[java.time.LocalDate], "LocalDate")
    check(Surface.of[java.time.LocalDateTime], "LocalDateTime")
    check(Surface.of[java.time.Instant], "Instant")
  }

  def `resolve java enum type`: Unit = {
    check(Surface.of[ChronoUnit], "ChronoUnit")
    check(Surface.of[MyChrono], "MyChrono:=ChronoUnit")
  }
} 
Example 35
Source File: TimeOptions.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.config.job

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit

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

case class TimeOptions(hours: Int, minutes: Int) {
  if (hours < 0 || hours > 23) {
    throw new IllegalArgumentException("Hours must be between 0 and 23: " + hours)
  } else if (minutes < 0 || minutes > 59) {
    throw new IllegalArgumentException("Minutes must be between 0 and 59: " + minutes)
  }
  
  def getInitialDelay(now: LocalDateTime, frequency: JobFrequency): FiniteDuration = {
    val firstRun = now.withHour(hours).withMinute(minutes)
    val isBefore = firstRun.isBefore(now)
    val actualFirstRun = frequency match {
      case Hourly =>
        var tmp = firstRun
        Iterator.continually({tmp = tmp.plusHours(1); tmp}).takeWhile(d => d.isBefore(now)).toList.lastOption.getOrElse(if (isBefore) firstRun else firstRun.minusHours(1)).plusHours(1)
      case Daily =>
        var tmp = firstRun
        Iterator.continually({tmp = tmp.plusDays(1); tmp}).takeWhile(d => d.isBefore(now)).toList.lastOption.getOrElse(if (isBefore) firstRun else firstRun.minusDays(1)).plusDays(1)
    }
    val secondsUntilRun = now.until(actualFirstRun, ChronoUnit.SECONDS)
    Duration.create(secondsUntilRun, TimeUnit.SECONDS)
  }
} 
Example 36
Source File: TimeOptions.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.scheduler.config.job

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit

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

case class TimeOptions(hours: Int, minutes: Int) {
  if (hours < 0 || hours > 23) {
    throw new IllegalArgumentException("Hours must be between 0 and 23: " + hours)
  } else if (minutes < 0 || minutes > 59) {
    throw new IllegalArgumentException("Minutes must be between 0 and 59: " + minutes)
  }
  
  def getInitialDelay(now: LocalDateTime, frequency: JobFrequency): FiniteDuration = {
    val firstRun = now.withHour(hours).withMinute(minutes)
    val isBefore = firstRun.isBefore(now)
    val actualFirstRun = frequency match {
      case Hourly =>
        var tmp = firstRun
        Iterator.continually({tmp = tmp.plusHours(1); tmp}).takeWhile(d => d.isBefore(now)).toList.lastOption.getOrElse(if (isBefore) firstRun else firstRun.minusHours(1)).plusHours(1)
      case Daily =>
        var tmp = firstRun
        Iterator.continually({tmp = tmp.plusDays(1); tmp}).takeWhile(d => d.isBefore(now)).toList.lastOption.getOrElse(if (isBefore) firstRun else firstRun.minusDays(1)).plusDays(1)
    }
    val secondsUntilRun = now.until(actualFirstRun, ChronoUnit.SECONDS)
    Duration.create(secondsUntilRun, TimeUnit.SECONDS)
  }
} 
Example 37
Source File: LoadBalancer.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.balancer

import java.time.Instant
import java.time.temporal.ChronoUnit

import com.olegych.scastie.api._
import org.slf4j.LoggerFactory

import scala.util.Random

case class Ip(v: String)

case class Task(config: Inputs, ip: Ip, taskId: TaskId, ts: Instant)

case class TaskHistory(data: Vector[Task], maxSize: Int) {
  def add(task: Task): TaskHistory = {
    val cappedData = if (data.length < maxSize) data else data.drop(1)
    copy(data = cappedData :+ task)
  }
}
case class LoadBalancer[R, S <: ServerState](servers: Vector[Server[R, S]]) {
  private val log = LoggerFactory.getLogger(getClass)

  def done(taskId: TaskId): Option[LoadBalancer[R, S]] = {
    Some(copy(servers = servers.map(_.done(taskId))))
  }

  def addServer(server: Server[R, S]): LoadBalancer[R, S] = {
    copy(servers = server +: servers)
  }

  def removeServer(ref: R): LoadBalancer[R, S] = {
    copy(servers = servers.filterNot(_.ref == ref))
  }

  def getRandomServer: Option[Server[R, S]] = {
    def random[T](xs: Seq[T]) = if (xs.nonEmpty) Some(xs(Random.nextInt(xs.size))) else None
    random(servers.filter(_.state.isReady))
  }

  def add(task: Task): Option[(Server[R, S], LoadBalancer[R, S])] = {
    log.info("Task added: {}", task.taskId)

    val (availableServers, unavailableServers) =
      servers.partition(_.state.isReady)

    def lastTenMinutes(v: Vector[Task]) = v.filter(_.ts.isAfter(Instant.now.minus(10, ChronoUnit.MINUTES)))
    def lastWithIp(v: Vector[Task]) = lastTenMinutes(v.filter(_.ip == task.ip)).lastOption

    if (availableServers.nonEmpty) {
      val selectedServer = availableServers.maxBy { s =>
        (
          s.mailbox.length < 3, //allow reload if server gets busy
          !s.currentConfig.needsReload(task.config), //pick those without need for reload
          -s.mailbox.length, //then those least busy
          lastTenMinutes(s.mailbox ++ s.history.data).exists(!_.config.needsReload(task.config)), //then those which use(d) this config
          lastWithIp(s.mailbox).orElse(lastWithIp(s.history.data)).map(_.ts.toEpochMilli), //then one most recently used by this ip, if any
          s.mailbox.lastOption.orElse(s.history.data.lastOption).map(-_.ts.toEpochMilli).getOrElse(0L) //then one least recently used
        )
      }
      val updatedServers = availableServers.map(old => if (old.id == selectedServer.id) old.add(task) else old)
      Some(
        (
          selectedServer,
          copy(
            servers = updatedServers ++ unavailableServers,
//            history = updatedHistory
          )
        )
      )
    } else {
      if (servers.isEmpty) {
        val msg = "All instances are down"
        log.error(msg)
      }
      None
    }
  }

} 
Example 38
Source File: JavaTimeCronDateTimeRegressionSpec.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s.lib.javatime

import java.time.LocalDateTime
import java.time.temporal.{ChronoField, ChronoUnit}

import cron4s._

import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec

10 * * * ?")
    val next = cron.next(from).get

    from.until(next, ChronoUnit.SECONDS) shouldBe 17L
  }

  // https://github.com/alonsodomin/cron4s/issues/59
  "Cron with day of week" should "yield a date in the future" in {
    val cron = Cron.unsafeParse("0 0 0 ? * 1-3")

    for (dayOfMonth <- 1 to 30) {
      val from = LocalDateTime.of(2017, 3, dayOfMonth, 2, 0, 0)
      cron.next(from).forall(_.isAfter(from)) shouldBe true
    }
  }
}