java.time.Period Scala Examples

The following examples show how to use java.time.Period. 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: DateInterval.scala    From chronoscala   with MIT License 5 votes vote down vote up
package jp.ne.opt.chronoscala

import java.time.{LocalDate, Period}
import jp.ne.opt.chronoscala.Imports._


case class DateInterval(startDate: LocalDate, endDate: LocalDate, step: Period) extends Seq[LocalDate] {
  def apply(idx: Int): LocalDate = {
    if (0 <= idx && idx < length) {
      iterator.drop(idx).next
    } else {
      throw new IndexOutOfBoundsException(idx.toString)
    }
  }

  def iterator: Iterator[LocalDate] = Iterator.iterate(startDate)(_ + step).takeWhile(_ <= endDate)

  def length: Int = iterator.length

  def by(step: Period): DateInterval = this.copy(step = step)
} 
Example 2
Source File: DurationConverters.scala    From hyperion   with Apache License 2.0 5 votes vote down vote up
package com.krux.hyperion.common

import java.time.Period
import com.krux.hyperion.expression._


object DurationConverters {

  implicit class AsJavaDuration(duration: Duration) {

    def asDurationMultiplied(multiplier: Int): java.time.Duration = duration match {
      case Year(n)   => java.time.Duration.ofDays(Period.ofYears(n * multiplier).getDays)
      case Month(n)  => java.time.Duration.ofDays(Period.ofMonths(n * multiplier).getDays)
      case Week(n)   => java.time.Duration.ofDays(Period.ofWeeks(n * multiplier).getDays)
      case Day(n)    => java.time.Duration.ofDays(n * multiplier)
      case Hour(n)   => java.time.Duration.ofHours(n * multiplier)
      case Minute(n) => java.time.Duration.ofMinutes(n * multiplier)
    }

  }
} 
Example 3
Source File: EvalProposals.scala    From docspell   with GNU General Public License v3.0 5 votes vote down vote up
package docspell.joex.process

import java.time.{LocalDate, Period}

import cats.effect.Sync
import cats.implicits._

import docspell.common._
import docspell.joex.scheduler.Task
import docspell.store.records.RAttachmentMeta


object EvalProposals {

  def apply[F[_]: Sync](data: ItemData): Task[F, ProcessItemArgs, ItemData] =
    Task { _ =>
      Timestamp
        .current[F]
        .map { now =>
          val metas = data.metas.map(calcCandidateWeight(now.toUtcDate))
          data.copy(metas = metas)
        }
    }

  def calcCandidateWeight(now: LocalDate)(rm: RAttachmentMeta): RAttachmentMeta = {
    val list = rm.proposals.change(mp => mp.addWeights(weight(rm, mp, now)))
    rm.copy(proposals = list.sortByWeights)
  }

  def weight(rm: RAttachmentMeta, mp: MetaProposal, ref: LocalDate)(
      cand: MetaProposal.Candidate
  ): Double =
    mp.proposalType match {
      case MetaProposalType.DueDate =>
        //for due dates, sort earliest on top
        MetaProposal
          .parseDate(cand)
          .map { ld =>
            val p = Period.between(ref, ld)
            // conversion only for sorting
            val d = p.getYears * 365 + p.getMonths * 31 + p.getDays
            d.toDouble
          }
          .getOrElse(2000.0)
      case _ =>
        val textLen  = rm.content.map(_.length).getOrElse(0)
        val tagCount = cand.origin.size.toDouble
        val pos      = cand.origin.map(_.startPosition).min
        val words    = cand.origin.map(_.label.split(' ').length).max.toDouble
        val nerFac =
          cand.origin.map(label => nerTagFactor(label.tag, mp.proposalType)).min
        (1 / words) * (1 / tagCount) * positionWeight(pos, textLen) * nerFac
    }

  def positionWeight(pos: Int, total: Int): Double =
    if (total <= 0) 1
    else {
      val p = math.abs(pos.toDouble / total.toDouble)
      if (p < 0.7) p / 2
      else p
    }

  def nerTagFactor(tag: NerTag, mt: MetaProposalType): Double =
    tag match {
      case NerTag.Date     => 1.0
      case NerTag.Email    => 0.5
      case NerTag.Location => 1.0
      case NerTag.Misc     => 1.0
      case NerTag.Organization =>
        if (mt == MetaProposalType.CorrOrg) 0.8
        else 1.0
      case NerTag.Person =>
        if (
          mt == MetaProposalType.CorrPerson ||
          mt == MetaProposalType.ConcPerson
        ) 0.8
        else 1.0
      case NerTag.Website => 0.5
    }
} 
Example 4
Source File: ArrayOfPeriodsReading.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.Period

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.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 io.circe.parser._
import org.openjdk.jmh.annotations.Benchmark
import play.api.libs.json.Json
import spray.json._

class ArrayOfPeriodsReading extends ArrayOfPeriodsBenchmark {
  @Benchmark
  def avSystemGenCodec(): Array[Period] = JsonStringInput.read[Array[Period]](new String(jsonBytes, UTF_8))

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

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

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

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

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

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

  @Benchmark
  def uPickle(): Array[Period] = read[Array[Period]](jsonBytes)
} 
Example 5
Source File: ArrayOfPeriodsBenchmark.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.Period

import org.openjdk.jmh.annotations.{Param, Setup}

abstract class ArrayOfPeriodsBenchmark extends CommonParams {
  @Param(Array("1", "10", "100", "1000", "10000", "100000", "1000000"))
  var size: Int = 1000
  var obj: Array[Period] = _
  var jsonString: String = _
  var jsonBytes: Array[Byte] = _
  var preallocatedBuf: Array[Byte] = _

  @Setup
  def setup(): Unit = {
    obj = (1 to size).map { i =>
      val x = ((i * 1498724053) / Math.pow(10, i % 10)).toInt
      Period.of(x, x, x)
    }.toArray
    jsonString = obj.mkString("[\"", "\",\"", "\"]")
    jsonBytes = jsonString.getBytes(UTF_8)
    preallocatedBuf = new Array[Byte](jsonBytes.length + 100)
  }
} 
Example 6
Source File: HoconInputTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package hocon

import java.time.{Duration, Period}

import com.avsystem.commons.serialization.json.JsonStringOutput
import com.avsystem.commons.serialization.{GenCodecRoundtripTest, Input, Output}
import com.typesafe.config.{ConfigFactory, ConfigMemorySize, ConfigValue, ConfigValueFactory, ConfigValueType}

class HoconInputTest extends GenCodecRoundtripTest {
  type Raw = ConfigValue

  def writeToOutput(write: Output => Unit): ConfigValue = {
    val sb = new JStringBuilder
    write(new JsonStringOutput(sb))
    val config = ConfigFactory.parseString(s"""{"f":${sb.toString}}""")
    if (config.getIsNull("f")) ConfigValueFactory.fromAnyRef(null) else config.getValue("f")
  }

  def createInput(raw: ConfigValue): Input =
    new HoconInput(raw)

  def rawInput(any: Any): HoconInput =
    new HoconInput(ConfigValueFactory.fromAnyRef(any))

  test("value type reading") {
    assert(rawInput(null).valueType == ConfigValueType.NULL)
    assert(rawInput("kek").valueType == ConfigValueType.STRING)
    assert(rawInput(42).valueType == ConfigValueType.NUMBER)
    assert(rawInput(true).valueType == ConfigValueType.BOOLEAN)
    assert(rawInput(JMap()).valueType == ConfigValueType.OBJECT)
    assert(rawInput(JList()).valueType == ConfigValueType.LIST)
  }

  test("duration reading") {
    assert(rawInput("34s").readDuration() == Duration.ofSeconds(34))
  }

  test("period reading") {
    assert(rawInput("5m").readPeriod() == Period.ofMonths(5))
  }

  test("temporal amount reading") {
    assert(rawInput("5 minutes").readTemporal() == Duration.ofMinutes(5))
    assert(rawInput("5 months").readTemporal() == Period.ofMonths(5))
  }

  test("size in bytes reading") {
    assert(rawInput("100M").readSizeInBytes() == 100 * 1024 * 1024L)
  }

  test("memory size reading") {
    assert(rawInput("100M").readMemorySize() == ConfigMemorySize.ofBytes(100 * 1024 * 1024L))
  }

  test("number reading") {
    assert(rawInput(42.0).readNumber().doubleValue == 42.0)
  }
} 
Example 7
Source File: PeriodUtils.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig

import java.time.Period

import scala.util.{ Success, Try }

import com.typesafe.config.impl.ConfigImplUtil
import pureconfig.error.{ CannotConvert, FailureReason }


  val fromString: String => Either[FailureReason, Period] = { str =>
    Try(Right(Period.parse(str))).getOrElse(typesafeConfigParsePeriod(str))
  }

  // This is a copy of the period parser in `com.typesafe.config.impl.SimpleConfig` adapted to be safer (dealing with
  // `Either` values instead of throwing exceptions). Try not to refactor this too much so as to be easy for anyone
  // to compare this code with the original.
  def typesafeConfigParsePeriod(input: String): Either[FailureReason, Period] = {
    val (rawValueStr, rawUnitStr) = splitUnits(ConfigImplUtil.unicodeTrim(input))
    val valueStr = ConfigImplUtil.unicodeTrim(rawValueStr)
    val unitStr = pluralize(rawUnitStr)

    // we use days as the default value in order to be compatible with Typesafe Config
    // (https://github.com/lightbend/config/blob/master/HOCON.md#period-format)
    Try(valueStr.toInt) match {
      case Success(n) =>
        unitStr match {
          case "" | "d" | "days" => Right(Period.ofDays(n))
          case "w" | "weeks" => Right(Period.ofWeeks(n))
          case "m" | "mo" | "months" => Right(Period.ofMonths(n))
          case "y" | "years" => Right(Period.ofYears(n))
          case _ => Left(CannotConvert(input, "Period", s"Could not parse time unit '$unitStr' (try d, w, mo, y)"))
        }
      case _ =>
        Left(CannotConvert(input, "Period", s"Could not parse duration number '$valueStr'"))
    }
  }

  private def splitUnits(s: String): (String, String) =
    s.splitAt(s.lastIndexWhere(!_.isLetter) + 1)

  private def pluralize(s: String): String =
    if (s.length > 2 && !s.endsWith("s")) s + "s" else s
} 
Example 8
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 9
Source File: TimeScheduleSpec.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.model.workflow

import java.time.{ Duration, Period }

import io.vamp.model.artifact.TimeSchedule
import io.vamp.model.reader.ReaderSpec
import io.vamp.model.artifact.TimeSchedule.{ RepeatForever, RepeatPeriod }
import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class TimeScheduleSpec extends FlatSpec with Matchers with ReaderSpec {

  "TimeSchedule" should "read an empty period" in {
    TimeSchedule("") should have(
      'period(RepeatPeriod(None, None)),
      'repeat(RepeatForever),
      'start(None)
    )
  }

  it should "read days" in {
    TimeSchedule("P1Y2M3D") should have(
      'period(RepeatPeriod(Some(Period.parse("P1Y2M3D")), None)),
      'repeat(RepeatForever),
      'start(None)
    )
  }

  it should "read time" in {
    TimeSchedule("PT1H2M3S") should have(
      'period(RepeatPeriod(None, Some(Duration.parse("PT1H2M3S")))),
      'repeat(RepeatForever),
      'start(None)
    )
  }

  it should "read days and time" in {
    TimeSchedule("P1Y2M3DT1H2M3S") should have(
      'period(RepeatPeriod(Some(Period.parse("P1Y2M3D")), Some(Duration.parse("PT1H2M3S")))),
      'repeat(RepeatForever),
      'start(None)
    )
  }
}