org.joda.time.LocalDate Scala Examples

The following examples show how to use org.joda.time.LocalDate. 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: RestFormats.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http.controllers

import org.joda.time.format.ISODateTimeFormat
import play.api.libs.json._
import play.api.libs.json.JsString
import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime}
import scala.util.Try

object RestFormats extends RestFormats

trait RestFormats {

  private val dateTimeFormat = ISODateTimeFormat.dateTime.withZoneUTC
  private val localDateRegex = """^(\d\d\d\d)-(\d\d)-(\d\d)$""".r

  implicit val localDateTimeRead: Reads[LocalDateTime] = new Reads[LocalDateTime] {
    override def reads(json: JsValue): JsResult[LocalDateTime] =
      json match {
        case JsString(s) =>
          Try {
            JsSuccess(new LocalDateTime(dateTimeFormat.parseDateTime(s), DateTimeZone.UTC))
          }.getOrElse {
            JsError(s"Could not parse $s as a DateTime with format ${dateTimeFormat.toString}")
          }
        case _ => JsError(s"Expected value to be a string, was actually $json")
      }
  }

  implicit val localDateTimeWrite: Writes[LocalDateTime] = new Writes[LocalDateTime] {
    def writes(dateTime: LocalDateTime): JsValue = JsString(dateTimeFormat.print(dateTime.toDateTime(DateTimeZone.UTC)))
  }

  implicit val dateTimeRead: Reads[DateTime] = new Reads[DateTime] {
    override def reads(json: JsValue): JsResult[DateTime] =
      json match {
        case JsString(s) =>
          Try {
            JsSuccess(dateTimeFormat.parseDateTime(s))
          }.getOrElse {
            JsError(s"Could not parse $s as a DateTime with format ${dateTimeFormat.toString}")
          }
        case _ => JsError(s"Expected value to be a string, was actually $json")
      }
  }

  implicit val dateTimeWrite: Writes[DateTime] = new Writes[DateTime] {
    def writes(dateTime: DateTime): JsValue = JsString(dateTimeFormat.print(dateTime))
  }

  implicit val localDateRead: Reads[LocalDate] = new Reads[LocalDate] {
    override def reads(json: JsValue): JsResult[LocalDate] =
      json match {
        case JsString(s @ localDateRegex(y, m, d)) =>
          Try {
            JsSuccess(new LocalDate(y.toInt, m.toInt, d.toInt))
          }.getOrElse {
            JsError(s"$s is not a valid date")
          }
        case JsString(s) => JsError(s"Cannot parse $s as a LocalDate")
        case _           => JsError(s"Expected value to be a string, was actually $json")
      }
  }

  implicit val localDateWrite: Writes[LocalDate] = new Writes[LocalDate] {
    def writes(date: LocalDate): JsValue =
      JsString("%04d-%02d-%02d".format(date.getYear, date.getMonthOfYear, date.getDayOfMonth))
  }

  implicit val dateTimeFormats      = Format(dateTimeRead, dateTimeWrite)
  implicit val localDateTimeFormats = Format(localDateTimeRead, localDateTimeWrite)
  implicit val localDateFormats     = Format(localDateRead, localDateWrite)

} 
Example 2
Source File: NRSSubmission.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json._
import uk.gov.hmrc.auth.core.retrieve._
import uk.gov.hmrc.auth.core.{AffinityGroup, ConfidenceLevel, CredentialRole}
import uk.gov.hmrc.domain.Vrn

case class NRSSubmission(payload: String,
                         metadata: Metadata)

object NRSSubmission {
  implicit val mdFormat: OFormat[Metadata] = Metadata.format
  implicit val format: OFormat[NRSSubmission] = Json.format[NRSSubmission]
}

//Identity Data should always be populated, but allow it to be optional for when the authEnabled flag is disabled
case class Metadata(businessId: String,
                    notableEvent: String,
                    payloadContentType: String,
                    payloadSha256Checksum: Option[String],
                    userSubmissionTimestamp: DateTime,
                    identityData: Option[IdentityData],
                    userAuthToken: String,
                    headerData: JsValue,
                    searchKeys: SearchKeys)

object Metadata {
  implicit val idformat: OFormat[IdentityData] = IdentityData.format
  implicit val dateFormats: Format[DateTime] = isoInstantDateFormat
  implicit val format: OFormat[Metadata] = Json.format[Metadata]
}

//Todo: match against NRS mandatory fields with what may not be returned from auth.  Appropriate error handling
case class IdentityData(internalId: Option[String] = None,
                        externalId: Option[String] = None,
                        agentCode: Option[String] = None,
                        credentials: Option[Credentials] = None,
                        confidenceLevel: ConfidenceLevel,
                        nino: Option[String] = None,
                        saUtr: Option[String] = None,
                        name: Option[Name] = None,
                        dateOfBirth: Option[LocalDate] = None,
                        email: Option[String] = None,
                        agentInformation: AgentInformation,
                        groupIdentifier: Option[String] = None,
                        credentialRole: Option[CredentialRole],
                        mdtpInformation: Option[MdtpInformation] = None,
                        itmpName: ItmpName,
                        itmpDateOfBirth: Option[LocalDate] = None,
                        itmpAddress: ItmpAddress,
                        affinityGroup: Option[AffinityGroup],
                        credentialStrength: Option[String] = None,
                        loginTimes: LoginTimes)

object IdentityData {
  implicit val localDateFormats: Format[LocalDate] = dateFormat
  implicit val credFormat: OFormat[Credentials] = Json.format[Credentials]
  implicit val nameFormat: OFormat[Name] = Json.format[Name]
  implicit val agentInfoFormat: OFormat[AgentInformation] = Json.format[AgentInformation]
  implicit val mdtpInfoFormat: OFormat[MdtpInformation] = Json.format[MdtpInformation]
  implicit val itmpNameFormat: OFormat[ItmpName] = Json.format[ItmpName]
  implicit val itmpAddressFormat: OFormat[ItmpAddress] = Json.format[ItmpAddress]
  implicit val dateTimeFormats: Format[DateTime] = isoInstantDateFormat
  implicit val loginTimesFormat: OFormat[LoginTimes] = Json.format[LoginTimes]
  implicit val format: OFormat[IdentityData] = Json.format[IdentityData]
}

case class SearchKeys(vrn: Option[Vrn] = None,
                      companyName: Option[String] = None,
                      taxPeriodEndDate: Option[LocalDate] = None,
                      periodKey: Option[String] = None
                     )

object SearchKeys {
  implicit val dateFormats: Format[LocalDate] = dateFormat
  implicit val format: OFormat[SearchKeys] = Json.format[SearchKeys]
} 
Example 3
Source File: FinancialDataQueryParams.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models

import org.joda.time.LocalDate
import org.joda.time.format.ISODateTimeFormat
import uk.gov.hmrc.vatapi.config.FixedConfig

import scala.util.Try

case class FinancialDataQueryParams(from: LocalDate, to: LocalDate) {
  val map: Map[SourceId, LocalDate] = Map("from" -> from, "to" -> to)
}

object FinancialDataQueryParams extends FixedConfig {
  val dateRegex: SourceId = """^\d{4}-\d{2}-\d{2}$"""

  def from(fromOpt: OptEither[String], toOpt: OptEither[String]): Either[String, FinancialDataQueryParams] = {

    val from = checkMinFromDate(dateQueryParam(fromOpt, "DATE_FROM_INVALID"))
    val to = checkFutureToDate(dateQueryParam(toOpt, "DATE_TO_INVALID"))

    val errors = for {
      paramOpt <- Seq(from, to, validDateRange(from, to))
      param <- paramOpt
      if param.isLeft
    } yield param.left.get

    if (errors.isEmpty) {
      Right(FinancialDataQueryParams(from.map(_.right.get).get, to.map(_.right.get).get))
    } else {
      Left(errors.head)
    }
  }

  private def dateQueryParam(dateOpt: OptEither[String], errorCode: String): OptEither[LocalDate] = {
    val paramValue = dateOpt match {
      case Some(value) =>
        val dateString = value.right.get
        if (dateString.matches(dateRegex))
          Try(Right(LocalDate.parse(dateString))).getOrElse(Left(errorCode))
        else
          Left(errorCode)
      case None => Left(errorCode)
    }
    Some(paramValue)
  }

  def validDateRange(fromOpt: OptEither[LocalDate], toOpt: OptEither[LocalDate]): Option[Either[SourceId, Unit] with Product with Serializable] = {

    for {
      fromVal <- fromOpt
      if fromVal.isRight
      toVal <- toOpt
      if toVal.isRight
    } yield
      (fromVal.right.get, toVal.right.get) match {
        case (from, to) if !from.isBefore(to) || from.plusYears(1).minusDays(1).isBefore(to) =>
          Left("DATE_RANGE_INVALID")
        case _ => Right(()) // object wrapped in Right irrelevant
      }
  }

  def checkMinFromDate(date: OptEither[LocalDate]): OptEither[LocalDate] = {
    val minDate: LocalDate = LocalDate.parse(mtdDate, ISODateTimeFormat.date())
    val out = date match {
      case Some(value) =>
        value match {
          case Right(d) if d.isBefore(minDate) => Left("DATE_FROM_INVALID")
          case _ => value
        }
      case None => Left("DATE_FROM_INVALID")
    }
    Some(out)
  }

  def checkFutureToDate(date: OptEither[LocalDate]): OptEither[LocalDate] = {
    val out = date match {
      case Some(value) =>
        value match {
          case Right(d) if d.isAfter(LocalDate.now()) => Left("DATE_TO_INVALID")
          case _ => value
        }
      case None => Left("DATE_TO_INVALID")
    }
    Some(out)
  }

} 
Example 4
Source File: Obligations.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models

import com.github.nscala_time.time.OrderingImplicits
import org.joda.time.LocalDate
import play.api.libs.json._

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

case class Obligations(obligations: Seq[Obligation])

object Obligations {
  implicit val writes: Writes[Obligations] = Json.writes[Obligations]
}

case class Obligation(start: LocalDate, end: LocalDate, due: LocalDate, status: String, periodKey: String, received: Option[LocalDate] = None)

object Obligation {
  implicit val jodaDateWrites: Writes[LocalDate] = new Writes[LocalDate] {
    def writes(d: LocalDate): JsValue = JsString(d.toString())
  }

  implicit val from = new DesTransformValidator[des.ObligationDetail, Obligation] {
    def from(desObligation: des.ObligationDetail) = {
      Try(Obligation(
        start = LocalDate.parse(desObligation.inboundCorrespondenceFromDate),
        end = LocalDate.parse(desObligation.inboundCorrespondenceToDate),
        due = LocalDate.parse(desObligation.inboundCorrespondenceDueDate),
        status = desObligation.status,
        periodKey = desObligation.periodKey,
        received = desObligation.inboundCorrespondenceDateReceived.map(LocalDate.parse))
      ) match {
        case Success(obj) => Right(obj)
        case Failure(ex) => Left(InvalidDateError(s"Unable to parse the date from des response $ex"))
      }
    }
  }

  implicit val localDateOrder: Ordering[LocalDate] = OrderingImplicits.LocalDateOrdering
  implicit val ordering: Ordering[Obligation] = Ordering.by(_.start)

  implicit val writes: Writes[Obligation] = Json.writes[Obligation]
}

case class InvalidDateError(msg: String) extends DesTransformError 
Example 5
Source File: FinancialDataQueryParamsSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models

import org.joda.time.LocalDate
import org.scalatest.TestData
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import uk.gov.hmrc.vatapi.UnitSpec

class FinancialDataQueryParamsSpec extends UnitSpec with GuiceOneAppPerTest {

  val testTime: LocalDate = LocalDate.now()

  implicit override def newAppForTest(testData: TestData): Application =
    new GuiceApplicationBuilder().configure(Map(s"Test.mtd-date" -> testTime.minusYears(10).toString)).build()

  "DateRangeQueryParams" should {

    "return an object when all the date range is within 1 year" in {
      val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(1).toString)), Some(Right(testTime.minusDays(1).toString)))
      response.isRight shouldBe true
      response.right.get.from shouldEqual LocalDate.parse(testTime.minusYears(1).toString)
      response.right.get.to shouldEqual LocalDate.parse(testTime.minusDays(1).toString)
    }

    "return an error when the date range is greater than one year" in {
      val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(1).toString)), Some(Right(testTime.toString)))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_RANGE_INVALID"
    }

    "return error when the from date query parameter is missing" in {
      val response = FinancialDataQueryParams.from(None, Some(Right("2019-03-31")))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_FROM_INVALID"
    }

    "return error when the from date query parameter is not a valid date" in {
      val response = FinancialDataQueryParams.from(Some(Right("ABC")), Some(Right("2019-03-31")))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_FROM_INVALID"
    }

    "return error when the from date query parameter is before mtd-date in Config" in {

      val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(11).toString)), Some(Right(testTime.minusYears(10).toString)))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_FROM_INVALID"
    }

    "return error when the to date query parameter is missing" in {
      val response = FinancialDataQueryParams.from(Some(Right("2019-03-31")), None)
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_TO_INVALID"
    }

    "return error when the to date query parameter is not a valid date" in {
      val response = FinancialDataQueryParams.from(Some(Right("2019-03-31")), Some(Right("ABC")))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_TO_INVALID"
    }

    "return error when the to date query parameter is a future date" in {
      val futureDate = LocalDate.now().plusDays(1)

      val response = FinancialDataQueryParams.from(Some(Right("2019-03-31")), Some(Right(futureDate.toString("yyyy-MM-dd"))))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_TO_INVALID"
    }

    s"return error when from date is after to date" in {
      val response = FinancialDataQueryParams.from(Some(Right(testTime.minusYears(1).toString)), Some(Right(testTime.minusYears(1).minusDays(1).toString)))
      response.isLeft shouldBe true
      response.left.get shouldBe "DATE_RANGE_INVALID"
    }
  }


} 
Example 6
Source File: ObligationsQueryParamsSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models

import org.joda.time.LocalDate
import uk.gov.hmrc.vatapi.UnitSpec

class ObligationsQueryParamsSpec extends UnitSpec {

  "ObligationsQueryParams" should {
    "return error when the from date query parameter is missing" in {
      val response = ObligationsQueryParams.from(None, Some(Right("2017-03-31")), Some(Right("A")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_DATE_FROM"
    }

    "return error when the from date query parameter is not a valid date" in {
      val response = ObligationsQueryParams.from(Some(Right("ABC")), Some(Right("2017-03-31")), Some(Right("O")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_DATE_FROM"
    }

    "return error when the to date query parameter is missing" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-03-31")), None, Some(Right("O")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_DATE_TO"
    }

    "return error when the to date query parameter is not a valid date" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-03-31")), Some(Right("ABC")), Some(Right("C")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_DATE_TO"
    }

    "return error when the status query parameter is missing" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-01-01")), Some(Right("2017-03-31")), None)
      response.isRight shouldBe true
      response.right.get.from shouldEqual Some(LocalDate.parse("2017-01-01"))
    }

    "return error when the status query parameter is not a valid status" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-01-01")), Some(Right("2017-03-31")), Some(Right("C")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_STATUS"
    }

    "return error when the status query parameter is A" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-01-01")), Some(Right("2017-03-31")), Some(Right("A")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_STATUS"
    }

    "return error when from date is after to date " in {
      val response = ObligationsQueryParams.from(Some(Right("2017-01-02")), Some(Right("2017-01-01")), Some(Right("F")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_DATE_RANGE"
    }


    "return error when the date range is more than 365 days" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-01-01")), Some(Right("2018-01-02")), Some(Right("F")))
      response.isLeft shouldBe true
      response.left.get shouldBe "INVALID_DATE_RANGE"
    }

    "return an object when all the query params are valid" in {
      val response = ObligationsQueryParams.from(Some(Right("2017-01-01")), Some(Right("2017-03-31")), Some(Right("F")))
      response.isRight shouldBe true
      response.right.get.from shouldEqual Some(LocalDate.parse("2017-01-01"))
    }
  }

} 
Example 7
Source File: UnitSpec.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi

import org.joda.time.{DateTime, DateTimeZone, LocalDate}
import org.scalatest.OptionValues
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.{AnyWordSpec, AsyncWordSpec}
import play.api.test.{DefaultAwaitTimeout, FutureAwaits}

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

trait BaseUnitSpec extends Matchers with OptionValues with TestUtils with FutureAwaits
  with DefaultAwaitTimeout {
  implicit val timeout: FiniteDuration = 5 seconds

  def await[T](f: Future[T])(implicit duration: FiniteDuration = timeout): T =
    Await.result(f, duration)
}

trait UnitSpec extends AnyWordSpec with BaseUnitSpec{
  implicit def extractAwait[A](future: Future[A]): A = await[A](future)

  def await[A](future: Future[A])(implicit timeout: Duration): A = Await.result(future, timeout)
}

trait AsyncUnitSpec extends AsyncWordSpec with BaseUnitSpec

trait TestUtils {
  private val vrnGenerator = VrnGenerator()

  def now: DateTime = DateTime.now(DateTimeZone.UTC)
  def generateVrn = vrnGenerator.nextVrn()

  implicit def toLocalDate(d: DateTime): LocalDate = d.toLocalDate
}

object TestUtils extends TestUtils 
Example 8
Source File: DatumTest.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.nl.datum

import nl.rabobank.oss.rules.dsl.nl.datum.DatumTestGlossary._
import nl.rabobank.oss.rules.dsl.nl.grammar.aanwezig
import nl.rabobank.oss.rules.utils.InternalBerekeningenTester
import org.joda.time.LocalDate

class DatumTest extends InternalBerekeningenTester(new DatumTestsBerekening) with DatumImplicits {

  val supportedDateFormats = Set(
    "d-M-yyyy",
    "d-MM-yyyy",
    "dd-M-yyyy",
    "dd-MM-yyyy"
  )

  val datumEerder = new LocalDate(2014, 1, 1)
  val datumGelijk = new LocalDate(2015, 1, 1)
  val datumLater = new LocalDate(2016, 1, 1)

  supportedDateFormats.foreach( pattern => {

    test(s"${pattern} parsen werkt (1/3)") gegeven (
      InvoerDatum is datumEerder.toString(pattern).datum
    ) verwacht (
      EerderDan is "success",
      EerderDanGelijk is "success",
      LaterDan niet aanwezig,
      LaterDanGelijk niet aanwezig,
      GelijkAan niet aanwezig
    )

    test(s"${pattern} parsen werkt (2/3)") gegeven (
      InvoerDatum is datumLater.toString(pattern).datum
    ) verwacht (
      EerderDan niet aanwezig,
      EerderDan niet aanwezig,
      LaterDan is "success",
      LaterDanGelijk is "success",
      GelijkAan niet aanwezig
    )

    test(s"${pattern} parsen werkt (3/3)") gegeven (
      InvoerDatum is datumGelijk.toString(pattern).datum
    ) verwacht (
      EerderDan niet aanwezig,
      EerderDanGelijk is "success",
      LaterDan niet aanwezig,
      LaterDanGelijk is "success",
      GelijkAan is "success"
    )

  })

} 
Example 9
Source File: Rfc3339Util.scala    From play-swagger   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, LocalDate}


object Rfc3339Util {

  private val fullDate = DateTimeFormat.forPattern("yyyy-MM-dd")
  private val shortDateTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")
  private val shortDTWithTicks = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
  private val fullDTWithTicks = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'")
  private val dateTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ")

  def parseDateTime(datestring: String): DateTime =
    if(datestring.endsWith("Z") || datestring.endsWith("z")) parseFull(datestring)
    else parseParts(datestring)

  def parseDate(datestring: String): LocalDate =
    fullDate.parseDateTime(datestring).toLocalDate

  def writeDate(date: LocalDate): String = fullDate.print(date)

  def writeDateTime(date: DateTime): String = dateTime.print(date)

  private def parseParts(datestring: String): DateTime = {
    //step one, split off the timezone.
    val sepChar = if (datestring.indexOf('+')>0) '+' else '-'
    val firstpart = datestring.substring(0, datestring.lastIndexOf(sepChar.toInt))
    val secondpart = datestring.substring(datestring.lastIndexOf(sepChar.toInt))
    //step two, remove the colon from the timezone offset
    val thirdpart = secondpart.substring(0, secondpart.indexOf(':')) + secondpart.substring(secondpart.indexOf(':') + 1)
    val dstring = firstpart + thirdpart
    try {
      shortDateTime.parseDateTime(dstring)
    } catch {
      case pe: IllegalArgumentException =>  dateTime.parseDateTime(dstring)
    }
  }

  private def parseFull(datestring: String): DateTime = {
    try {
      shortDTWithTicks.parseDateTime(datestring)
    } catch {
      case p: IllegalArgumentException => fullDTWithTicks.parseDateTime(datestring)
    }
  }

} 
Example 10
Source File: string_formats_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package string_formats.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import de.zalando.play.controllers.Base64String
import Base64String._
import de.zalando.play.controllers.BinaryString
import BinaryString._
import org.joda.time.DateTime
import java.util.UUID
import org.joda.time.LocalDate
// ----- constraints and wrapper validations -----
class GetBase64OptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetBase64OptValidator(instance: Base64String) extends RecursiveValidator {
    override val validators = Seq(new GetBase64OptConstraints(instance))
}
class GetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class GetPetIdValidator(instance: BinaryString) extends RecursiveValidator {
    override val validators = Seq(new GetPetIdConstraints(instance))
}
class GetDate_timeOptConstraints(override val instance: DateTime) extends ValidationBase[DateTime] {
    override def constraints: Seq[Constraint[DateTime]] =
        Seq()
}
class GetDate_timeOptValidator(instance: DateTime) extends RecursiveValidator {
    override val validators = Seq(new GetDate_timeOptConstraints(instance))
}
class GetUuidOptConstraints(override val instance: UUID) extends ValidationBase[UUID] {
    override def constraints: Seq[Constraint[UUID]] =
        Seq()
}
class GetUuidOptValidator(instance: UUID) extends RecursiveValidator {
    override val validators = Seq(new GetUuidOptConstraints(instance))
}
class GetDateOptConstraints(override val instance: LocalDate) extends ValidationBase[LocalDate] {
    override def constraints: Seq[Constraint[LocalDate]] =
        Seq()
}
class GetDateOptValidator(instance: LocalDate) extends RecursiveValidator {
    override val validators = Seq(new GetDateOptConstraints(instance))
}
// ----- complex type validators -----
// ----- option delegating validators -----
class GetBase64Validator(instance: GetBase64) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetBase64OptValidator(_) }
}
class GetDate_timeValidator(instance: GetDate_time) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetDate_timeOptValidator(_) }
}
class GetUuidValidator(instance: GetUuid) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetUuidOptValidator(_) }
}
class GetDateValidator(instance: GetDate) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new GetDateOptValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class GetValidator(date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid, petId: BinaryString) extends RecursiveValidator {
    override val validators = Seq(
        new GetDate_timeValidator(date_time), 
    
        new GetDateValidator(date), 
    
        new GetBase64Validator(base64), 
    
        new GetUuidValidator(uuid), 
    
        new GetPetIdValidator(petId)
    
    )
} 
Example 11
Source File: string_formats_yaml.base.scala    From play-swagger   with MIT License 5 votes vote down vote up
package string_formats.yaml

import scala.language.existentials

import play.api.mvc.{Action, Controller, Results}
import play.api.http._
import Results.Status

import de.zalando.play.controllers.{PlayBodyParsing, ParsingError, ResultWrapper}
import PlayBodyParsing._
import scala.util._
import de.zalando.play.controllers.Base64String
import Base64String._
import de.zalando.play.controllers.BinaryString
import BinaryString._
import org.joda.time.DateTime
import java.util.UUID
import org.joda.time.LocalDate

import de.zalando.play.controllers.PlayPathBindables





trait String_formatsYamlBase extends Controller with PlayBodyParsing {
    sealed trait GetType[T] extends ResultWrapper[T]
    
    case object Get200 extends EmptyReturn(200)
    

    private type getActionRequestType       = (GetDate_time, GetDate, GetBase64, GetUuid, BinaryString)
    private type getActionType[T]            = getActionRequestType => GetType[T] forSome { type T }

        private def getParser(acceptedTypes: Seq[String], maxLength: Int = parse.DefaultMaxTextLength) = {
            def bodyMimeType: Option[MediaType] => String = mediaType => {
                val requestType = mediaType.toSeq.map {
                    case m: MediaRange => m
                    case MediaType(a,b,c) => new MediaRange(a,b,c,None,Nil)
                }
                negotiateContent(requestType, acceptedTypes).orElse(acceptedTypes.headOption).getOrElse("application/json")
            }
            
            import de.zalando.play.controllers.WrappedBodyParsers
            
            val customParsers = WrappedBodyParsers.anyParser[BinaryString]
            anyParser[BinaryString](bodyMimeType, customParsers, "Invalid BinaryString", maxLength)
        }

    val getActionConstructor  = Action
    def getAction[T] = (f: getActionType[T]) => (date_time: GetDate_time, date: GetDate, base64: GetBase64, uuid: GetUuid) => getActionConstructor(getParser(Seq[String]())) { request =>
        val providedTypes = Seq[String]("application/json", "application/yaml")

        negotiateContent(request.acceptedTypes, providedTypes).map { getResponseMimeType =>

            val petId = request.body
            
            

                val result =
                        new GetValidator(date_time, date, base64, uuid, petId).errors match {
                            case e if e.isEmpty => processValidgetRequest(f)((date_time, date, base64, uuid, petId))(getResponseMimeType)
                            case l =>
                                implicit val marshaller: Writeable[Seq[ParsingError]] = parsingErrors2Writable(getResponseMimeType)
                                BadRequest(l)
                        }
                result
            
        }.getOrElse(Status(406)("The server doesn't support any of the requested mime types"))
    }

    private def processValidgetRequest[T](f: getActionType[T])(request: getActionRequestType)(mimeType: String) = {
      f(request).toResult(mimeType).getOrElse {
        Results.NotAcceptable
      }
    }
    abstract class EmptyReturn(override val statusCode: Int = 204) extends ResultWrapper[Results.EmptyContent]  with GetType[Results.EmptyContent] { val result = Results.EmptyContent(); val writer = (x: String) => Some(new DefaultWriteables{}.writeableOf_EmptyContent); override def toResult(mimeType: String): Option[play.api.mvc.Result] = Some(Results.NoContent) }
    case object NotImplementedYet extends ResultWrapper[Results.EmptyContent]  with GetType[Results.EmptyContent] { val statusCode = 501; val result = Results.EmptyContent(); val writer = (x: String) => Some(new DefaultWriteables{}.writeableOf_EmptyContent); override def toResult(mimeType: String): Option[play.api.mvc.Result] = Some(Results.NotImplemented) }
} 
Example 12
Source File: BigQuerySchema.scala    From shapeless-datatype   with Apache License 2.0 5 votes vote down vote up
package shapeless.datatype.bigquery

import com.google.api.services.bigquery.model.{TableFieldSchema, TableSchema}
import org.joda.time.{Instant, LocalDate, LocalDateTime, LocalTime}

import scala.collection.JavaConverters._
import scala.reflect.runtime.universe._

object BigQuerySchema {
  private def isField(s: Symbol): Boolean =
    s.isPublic && s.isMethod && !s.isSynthetic && !s.isConstructor && s.asMethod.isCaseAccessor

  private def isCaseClass(tpe: Type): Boolean =
    !tpe.toString.startsWith("scala.") &&
      List(typeOf[Product], typeOf[Serializable], typeOf[Equals])
        .forall(b => tpe.baseClasses.contains(b.typeSymbol))

  private def rawType(tpe: Type): (String, Iterable[TableFieldSchema]) = tpe match {
    case t if t =:= typeOf[Boolean]       => ("BOOLEAN", Nil)
    case t if t =:= typeOf[Int]           => ("INTEGER", Nil)
    case t if t =:= typeOf[Long]          => ("INTEGER", Nil)
    case t if t =:= typeOf[Float]         => ("FLOAT", Nil)
    case t if t =:= typeOf[Double]        => ("FLOAT", Nil)
    case t if t =:= typeOf[String]        => ("STRING", Nil)
    case t if t =:= typeOf[Array[Byte]]   => ("BYTES", Nil)
    case t if t =:= typeOf[Instant]       => ("TIMESTAMP", Nil)
    case t if t =:= typeOf[LocalDate]     => ("DATE", Nil)
    case t if t =:= typeOf[LocalTime]     => ("TIME", Nil)
    case t if t =:= typeOf[LocalDateTime] => ("DATETIME", Nil)
    case t if isCaseClass(t)              => ("RECORD", toFields(t))
  }

  private def toField(s: Symbol): TableFieldSchema = {
    val name = s.name.toString
    val tpe = s.asMethod.returnType

    val (mode, valType) = tpe match {
      case t if t.erasure =:= typeOf[Option[_]].erasure => ("NULLABLE", t.typeArgs.head)
      case t
          if t.erasure <:< typeOf[Traversable[_]].erasure || (t.erasure <:< typeOf[
            Array[_]
          ] && !(t.typeArgs.head =:= typeOf[
            Byte
          ])) =>
        ("REPEATED", t.typeArgs.head)
      case t => ("REQUIRED", t)
    }
    val (tpeParam, nestedParam) = customTypes.get(valType.toString) match {
      case Some(t) => (t, Nil)
      case None    => rawType(valType)
    }
    val tfs = new TableFieldSchema().setMode(mode).setName(name).setType(tpeParam)
    if (nestedParam.nonEmpty) {
      tfs.setFields(nestedParam.toList.asJava)
    }
    tfs
  }

  private def toFields(t: Type): Iterable[TableFieldSchema] = t.decls.filter(isField).map(toField)

  private val customTypes = scala.collection.mutable.Map[String, String]()
  private val cachedSchemas = scala.collection.concurrent.TrieMap.empty[TypeTag[_], TableSchema]

  private[bigquery] def register(tpe: Type, typeName: String): Unit =
    customTypes += tpe.toString -> typeName

  def apply[T: TypeTag]: TableSchema = {
    val tt = implicitly[TypeTag[T]]
    cachedSchemas.getOrElseUpdate(tt, new TableSchema().setFields(toFields(tt.tpe).toList.asJava))
  }
} 
Example 13
Source File: BigQueryTypeSpec.scala    From shapeless-datatype   with Apache License 2.0 5 votes vote down vote up
package shapeless.datatype.bigquery

import java.net.URI

import com.fasterxml.jackson.databind.{ObjectMapper, SerializationFeature}
import com.google.api.services.bigquery.model.TableRow
import com.google.common.io.BaseEncoding
import com.google.protobuf.ByteString
import org.joda.time.{Instant, LocalDate, LocalDateTime, LocalTime}
import org.scalacheck.Prop.forAll
import org.scalacheck.ScalacheckShapeless._
import org.scalacheck._
import shapeless._
import shapeless.datatype.record._

import scala.reflect.runtime.universe._

object BigQueryTypeSpec extends Properties("BigQueryType") {
  import shapeless.datatype.test.Records._
  import shapeless.datatype.test.SerializableUtils._

  val mapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)

  implicit def compareByteArrays(x: Array[Byte], y: Array[Byte]) = java.util.Arrays.equals(x, y)
  implicit def compareIntArrays(x: Array[Int], y: Array[Int]) = java.util.Arrays.equals(x, y)

  def roundTrip[A: TypeTag, L <: HList](m: A)(implicit
    gen: LabelledGeneric.Aux[A, L],
    fromL: FromTableRow[L],
    toL: ToTableRow[L],
    mr: MatchRecord[L]
  ): Boolean = {
    BigQuerySchema[A] // FIXME: verify the generated schema
    val t = ensureSerializable(BigQueryType[A])
    val f1: SerializableFunction[A, TableRow] =
      new SerializableFunction[A, TableRow] {
        override def apply(m: A): TableRow = t.toTableRow(m)
      }
    val f2: SerializableFunction[TableRow, Option[A]] =
      new SerializableFunction[TableRow, Option[A]] {
        override def apply(m: TableRow): Option[A] = t.fromTableRow(m)
      }
    val toFn = ensureSerializable(f1)
    val fromFn = ensureSerializable(f2)
    val copy = fromFn(mapper.readValue(mapper.writeValueAsString(toFn(m)), classOf[TableRow]))
    val rm = RecordMatcher[A]
    copy.exists(rm(_, m))
  }

  implicit val byteStringBigQueryMappableType = BigQueryType.at[ByteString]("BYTES")(
    x => ByteString.copyFrom(BaseEncoding.base64().decode(x.toString)),
    x => BaseEncoding.base64().encode(x.toByteArray)
  )
  property("required") = forAll { m: Required => roundTrip(m) }
  property("optional") = forAll { m: Optional => roundTrip(m) }
  property("repeated") = forAll { m: Repeated => roundTrip(m) }
  property("mixed") = forAll { m: Mixed => roundTrip(m) }
  property("nested") = forAll { m: Nested => roundTrip(m) }
  property("seqs") = forAll { m: Seqs => roundTrip(m) }

  implicit val arbDate = Arbitrary(arbInstant.arbitrary.map(i => new LocalDate(i.getMillis)))
  implicit val arbTime = Arbitrary(arbInstant.arbitrary.map(i => new LocalTime(i.getMillis)))
  implicit val arbDateTime = Arbitrary(
    arbInstant.arbitrary.map(i => new LocalDateTime(i.getMillis))
  )

  case class DateTimeTypes(
    instant: Instant,
    date: LocalDate,
    time: LocalTime,
    dateTime: LocalDateTime
  )
  property("date time types") = forAll { m: DateTimeTypes => roundTrip(m) }

  implicit val uriBigQueryType =
    BigQueryType.at[URI]("STRING")(v => URI.create(v.toString), _.toASCIIString)
  property("custom") = forAll { m: Custom => roundTrip(m) }
} 
Example 14
Source File: Dates.scala    From play-ui   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.views.formatting

import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, DateTimeZone, LocalDate}
import play.api.i18n.Lang

object Dates {

  private val MonthNamesInWelsh = Map(
    1  -> "Ionawr",
    2  -> "Chwefror",
    3  -> "Mawrth",
    4  -> "Ebrill",
    5  -> "Mai",
    6  -> "Mehefin",
    7  -> "Gorffennaf",
    8  -> "Awst",
    9  -> "Medi",
    10 -> "Hydref",
    11 -> "Tachwedd",
    12 -> "Rhagfyr")
  private val WeekDaysInWelsh = Map(
    1 -> "Dydd Llun",
    2 -> "Dydd Mawrth",
    3 -> "Dydd Mercher",
    4 -> "Dydd Iau",
    5 -> "Dydd Gwener",
    6 -> "Dydd Sadwrn",
    7 -> "Dydd Sul")

  private[formatting] val dateFormat =
    DateTimeFormat.forPattern("d MMMM y").withZone(DateTimeZone.forID("Europe/London"))
  private[formatting] val dateFormatAbbrMonth =
    DateTimeFormat.forPattern("d MMM y").withZone(DateTimeZone.forID("Europe/London"))
  private[formatting] val shortDateFormat =
    DateTimeFormat.forPattern("yyyy-MM-dd").withZone(DateTimeZone.forID("Europe/London"))
  private[formatting] val easyReadingDateFormat =
    DateTimeFormat.forPattern("EEEE d MMMM yyyy").withZone(DateTimeZone.forID("Europe/London"))
  private[formatting] val easyReadingTimestampFormat =
    DateTimeFormat.forPattern("h:mmaa").withZone(DateTimeZone.forID("Europe/London"))

  def formatDate(date: LocalDate) = dateFormat.print(date)

  def formatDateAbbrMonth(date: LocalDate) = dateFormatAbbrMonth.print(date)

  def formatDate(date: Option[LocalDate], default: String) = date match {
    case Some(d) => dateFormat.print(d)
    case None    => default
  }

  def formatDateTime(date: DateTime) = dateFormat.print(date)

  def formatEasyReadingTimestamp(date: Option[DateTime], default: String)(implicit lang: Lang) = {
    val englishEasyDate: DateTime => String = d =>
      s"${easyReadingTimestampFormat.print(d).toLowerCase}, ${easyReadingDateFormat.print(d)}"
    val welshEasyDate: DateTime => String = d =>
      s"${easyReadingTimestampFormat.print(d).toLowerCase}, ${WeekDaysInWelsh(d.getDayOfWeek)} ${d.getDayOfMonth} ${MonthNamesInWelsh(
        d.getMonthOfYear)} ${d.getYear}"
    val formatter = lang.code match {
      case "cy" => welshEasyDate
      case _    => englishEasyDate
    }

    date.fold(default)(formatter)
  }

  def shortDate(date: LocalDate) = shortDateFormat.print(date)

  def formatDays(days: Int) = s"$days day${if (days > 1) "s" else ""}"

} 
Example 15
Source File: models.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json._

package object models {

  type Amount = BigDecimal
  type SourceId = String
  type PropertyId = String
  type PeriodId = String
  type SummaryId = String
  type ValidationErrors = Seq[(JsPath, Seq[JsonValidationError])]

  type OptEither[T] = Option[Either[String, T]]

  val vatAmountValidator: Reads[Amount] = Reads
    .of[Amount]
    .filter(
      JsonValidationError(
        "amount should be a monetary value (to 2 decimal places), between -9,999,999,999,999.99 and 9,999,999,999,999.99",
        ErrorCode.INVALID_MONETARY_AMOUNT))(amount =>
      amount.scale < 3 && amount >= -VAT_MAX_AMOUNT_13_DIGITS && amount <= VAT_MAX_AMOUNT_13_DIGITS)

  val vatNonNegativeAmountValidator: Reads[Amount] = Reads
    .of[Amount]
    .filter(
      JsonValidationError(
        "amount should be a monetary value (to 2 decimal places), between 0 and 99,999,999,999.99",
        ErrorCode.INVALID_MONETARY_AMOUNT))(amount =>
      amount.scale < 3 && amount >= 0 && amount <= VAT_MAX_AMOUNT_11_DIGITS)

  val vatAmountValidatorWithZeroDecimals: Reads[Amount] = Reads
    .of[Amount]
    .filter(
      JsonValidationError(
        "The value must be between -9999999999999 and 9999999999999",
        ErrorCode.INVALID_MONETARY_AMOUNT))(
      amount =>
        (amount.scale <= 0 || amount
          .remainder(1) == 0) && amount.scale < 3 && amount
          .toBigInt() >= -VAT_MAX_AMOUNT_13_DIGITS.toBigInt && amount
          .toBigInt() <= VAT_MAX_AMOUNT_13_DIGITS.toBigInt)
  val isoInstantDatePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"
  val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  val datePattern = "yyyy-MM-dd"

  val isoInstantDateFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(isoInstantDatePattern),
    JodaWrites.jodaDateWrites(isoInstantDatePattern)
  )
  private val VAT_MAX_AMOUNT_13_DIGITS = BigDecimal("9999999999999.99")

  val dateTimeFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(dateTimePattern),
    JodaWrites.jodaDateWrites(dateTimePattern)
  )

  val defaultDateTimeFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(isoInstantDatePattern),
    JodaWrites.jodaDateWrites(dateTimePattern)
  )
  private val VAT_MAX_AMOUNT_11_DIGITS = BigDecimal("99999999999.99")

  val dateFormat: Format[LocalDate] = Format[LocalDate](
    JodaReads.jodaLocalDateReads(datePattern),
    JodaWrites.jodaLocalDateWrites(datePattern)
  )

} 
Example 16
Source File: RestFormatsSpec.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http.controllers

import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime}
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{JsSuccess, _}

class RestFormatsSpec extends AnyWordSpecLike with Matchers {
  "localDateTimeRead" should {
    "return a LocalDateTime for correctly formatted JsString" in {
      val testDate = new LocalDateTime(0)
      val jsValue  = RestFormats.localDateTimeWrite.writes(testDate)

      val JsSuccess(result, _) = RestFormats.localDateTimeRead.reads(jsValue)
      result shouldBe testDate
    }

    "return a JsError for a json value that is not a JsString" in {
      RestFormats.localDateTimeRead.reads(Json.obj()) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is not a well-formatted date" in {
      RestFormats.localDateTimeRead.reads(JsString("not a valid date")) shouldBe a[JsError]
    }
  }

  "dateTimeRead" should {
    "return a DateTime in zone UTC for correctly formatted JsString" in {
      val testDate = new DateTime(0)
      val jsValue  = RestFormats.dateTimeWrite.writes(testDate)

      val JsSuccess(result, _) = RestFormats.dateTimeRead.reads(jsValue)
      result shouldBe testDate.withZone(DateTimeZone.UTC)
    }

    "return a JsError for a json value that is not a JsString" in {
      RestFormats.dateTimeRead.reads(Json.obj()) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is not a well-formatted date" in {
      RestFormats.dateTimeRead.reads(JsString("not a valid date")) shouldBe a[JsError]
    }
  }

  "localDateRead" should {
    "return a LocalDate in zone UTC for correctly formatted JsString" in {
      val json         = JsString("1994-05-01")
      val expectedDate = new LocalDate(1994, 5, 1)

      val JsSuccess(result, _) = RestFormats.localDateRead.reads(json)
      result shouldBe expectedDate
    }

    "return a JsError for a json value that is not a JsString" in {
      RestFormats.localDateRead.reads(Json.obj()) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is not a well-formatted date" in {
      RestFormats.localDateRead.reads(JsString("not a valid date")) shouldBe a[JsError]
    }

    "return a JsError for a JsString that is well formatted but has bad values" in {
      RestFormats.localDateRead.reads(JsString("1994-13-32")) shouldBe a[JsError]
    }
  }
} 
Example 17
Source File: package.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s.lib

import cats.{Eq, Show}

import cron4s.datetime.IsDateTime

import org.joda.time.{DateTime, LocalDate, LocalDateTime, LocalTime}


package object joda {
  implicit val jodaDateTimeEq: Eq[DateTime] = Eq.fromUniversalEquals[DateTime]
  implicit val jodaLocalDateEq: Eq[LocalDate] =
    Eq.fromUniversalEquals[LocalDate]
  implicit val jodaLocalTimeEq: Eq[LocalTime] =
    Eq.fromUniversalEquals[LocalTime]
  implicit val jodaLocalDateTimeEq: Eq[LocalDateTime] =
    Eq.fromUniversalEquals[LocalDateTime]

  implicit val jodaDateTimeShow: Show[DateTime]           = Show.fromToString
  implicit val jodaLocalDateShow: Show[LocalDate]         = Show.fromToString
  implicit val jodaLocalTimeShow: Show[LocalTime]         = Show.fromToString
  implicit val jodaLocalDateTimeShow: Show[LocalDateTime] = Show.fromToString

  implicit val jodaDateTimeInstance: IsDateTime[DateTime] =
    new JodaDateTimeInstance
  implicit val jodaLocalDateInstance: IsDateTime[LocalDate] =
    new JodaLocalDateInstance
  implicit val jodaLocalTimeInstance: IsDateTime[LocalTime] =
    new JodaLocalTimeInstance
  implicit val jodaLocalDateTimeInstance: IsDateTime[LocalDateTime] =
    new JodaLocalDateTimeInstance
} 
Example 18
Source File: Models.scala    From swagger-finatra   with Apache License 2.0 5 votes vote down vote up
package com.github.xiaodongw.swagger.finatra

import com.twitter.finagle.http.Request
import com.twitter.finatra.request.{QueryParam, RouteParam}
import io.swagger.annotations.{ApiModel, ApiModelProperty}
import javax.inject.Inject
import org.joda.time.{DateTime, LocalDate}

@ApiModel(value="AddressModel", description="Sample address model for documentation")
case class Address(street: String, zip: String)

case class Student(firstName: String, lastName: String, gender: Gender, birthday: LocalDate, grade: Int, address: Option[Address])

case class StudentWithRoute(
  @RouteParam
  @ApiModelProperty(name = "student_id", value = "Id of the student")
  id: String,
  @Inject request: Request,
  firstName: String,
  lastName: String,
  gender: Gender,
  birthday: LocalDate,
  grade: Int,
  emails: Array[String],
  address: Option[Address]
)

case class StringWithRequest(
  @Inject request: Request,
  firstName: String
)

object CourseType extends Enumeration {
  val LEC, LAB = Value
}

case class Course(time: DateTime,
                  name: String,
                  @ApiModelProperty(required = false, example = "[math,stem]")
                  tags: Seq[String],
                  @ApiModelProperty(dataType = "string", allowableValues = "LEC,LAB")
                  typ: CourseType.Value,
                  @ApiModelProperty(readOnly = true)
                  capacity: Int,
                  @ApiModelProperty(dataType = "double", required = true)
                  cost: BigDecimal) 
Example 19
Source File: Implicits.scala    From scala-cass   with MIT License 5 votes vote down vote up
package com.weather.scalacass.joda

import com.datastax.driver.core.{ Cluster, DataType }
import com.google.common.reflect.TypeToken
import com.weather.scalacass.{ CassFormatDecoder, CassFormatEncoder }
import com.weather.scalacass.CassFormatEncoder.sameTypeCassFormatEncoder
import com.weather.scalacass.CassFormatDecoderVersionSpecific.codecCassFormatDecoder
import org.joda.time.{ DateTime, Instant, LocalDate, LocalTime }

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

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

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

  implicit def timestampEncoder(implicit cluster: Cluster): CassFormatEncoder[DateTime] =
    sameTypeCassFormatEncoder(cluster.getMetadata.newTupleType(DataType.timestamp, DataType.varchar))
  implicit val timestampDecoder: CassFormatDecoder[DateTime] = codecCassFormatDecoder(TypeToken.of(classOf[DateTime]))
} 
Example 20
Source File: JodaLocalDateGenerators.scala    From scalacheck-ops   with Apache License 2.0 5 votes vote down vote up
package org.scalacheck.ops.time.joda

import org.joda.time.chrono.ISOChronology
import org.joda.time.{Chronology, LocalDate, Period, ReadablePeriod}
import org.scalacheck.Gen
import org.scalacheck.ops.time.AbstractTimeGenerators

sealed trait JodaLocalDateGenerators extends AbstractTimeGenerators {
  override type InstantType = LocalDate
  override type DurationType = ReadablePeriod
  override type ParamsType = Chronology

  override def defaultParams: Chronology = ISOChronology.getInstanceUTC

  override val defaultRange: ReadablePeriod = Period.years(1)

  override protected[time] def now(implicit params: Chronology): LocalDate = LocalDate.now(params)

  override protected[time] def addToCeil(
    instant: LocalDate,
    duration: ReadablePeriod
  )(implicit params: Chronology): LocalDate = {
    instant plus duration
  }

  override protected[time] def subtractToFloor(
    instant: LocalDate,
    duration: ReadablePeriod
  )(implicit params: Chronology): LocalDate = {
    instant minus duration
  }

  override def between(start: LocalDate, end: LocalDate)(implicit params: Chronology): Gen[LocalDate] = {
    val startYear = start.getYear
    val startMonthOfYear = start.getMonthOfYear
    for {
      year <- Gen.choose(startYear, end.getYear)
      monthOfYear <- {
        if (year == startYear) Gen.choose(start.getMonthOfYear, end.getMonthOfYear)
        else Gen.choose(params.monthOfYear.getMinimumValue, params.monthOfYear.getMaximumValue)
      }
      dayOfMonth <- {
        if (year == startYear && monthOfYear == startMonthOfYear) Gen.choose(startMonthOfYear, end.getDayOfMonth)
        else Gen.choose(params.dayOfMonth.getMinimumValue, params.dayOfMonth.getMaximumValue)
      }
    } yield new LocalDate(year, monthOfYear, dayOfMonth, params)
  }
}

object JodaLocalDateGenerators extends JodaLocalDateGenerators 
Example 21
Source File: SlackSearch.scala    From slack-client   with MIT License 5 votes vote down vote up
package com.kifi.slack.models

import org.joda.time.LocalDate
import play.api.libs.json.{Json, Reads}
import scala.language.implicitConversions

case class SlackSearchRequest(query: SlackSearchRequest.Query, optional: SlackSearchRequest.Param*)

object SlackSearchRequest {
  sealed abstract class Param(val name: String, val value: Option[String])

  case class Query(query: String) extends Param("query", Some(query))
  object Query {
    val trivial = Query("")
    def apply(queries: Option[Query]*): Query = Query(queries.flatten.map(_.query).mkString(" "))
    def in(channelName: SlackChannelName) = Query(s"in:#${channelName.value.stripPrefix("#").stripPrefix("@")}")
    def from(username: SlackUsername) = Query(s"from:${username.value}")
    def before(date: LocalDate) = Query(s"before:$date")
    def after(date: LocalDate) = Query(s"after:$date")
    val hasLink = Query(s"has:link")

    implicit val reads = Reads.of[String].map(Query(_))
  }

  sealed abstract class Sort(sort: String) extends Param("sort", Some(sort))
  object Sort {
    case object ByScore extends Sort("score")
    case object ByTimestamp extends Sort("timestamp")
  }

  sealed abstract class SortDirection(dir: String) extends Param("sort_dir", Some(dir))
  object SortDirection {
    case object Descending extends SortDirection("desc")
    case object Ascending extends SortDirection("asc")
  }

  object Highlight extends Param("highlight", Some("1"))

  case class Page(page: Int) extends Param("page", Some(page.toString))
  object Page {
    val max = 100
  }

  case class PageSize(count: Int) extends Param("count", Some(count.toString))
  object PageSize {
    val max = 1000
  }
}

case class SlackSearchResponse(query: SlackSearchRequest.Query, messages: SlackSearchResponse.Messages)
object SlackSearchResponse {
  val trivial = SlackSearchResponse(SlackSearchRequest.Query.trivial, SlackSearchResponse.Messages.empty)

  case class Paging(count: Int, total: Int, page: Int, pages: Int)
  object Paging {
    val empty = Paging(0, 0, 0, 0)
    implicit val reads = Json.reads[Paging]
  }
  case class Messages(total: Int, paging: Paging, matches: Seq[SlackMessage])
  object Messages {
    val empty = Messages(0, Paging.empty, Seq.empty)
    implicit val reads = Json.reads[Messages]
  }

  implicit val reads = Json.reads[SlackSearchResponse]
} 
Example 22
Source File: Bindables.scala    From cave   with MIT License 5 votes vote down vote up
package com.gilt.cavellc.models

object Bindables {

  import org.joda.time.format.ISODateTimeFormat
  import org.joda.time.{DateTime, LocalDate}
  import play.api.mvc.{PathBindable, QueryStringBindable}

  // Type: date-time-iso8601
  implicit val pathBindableTypeDateTimeIso8601 = new PathBindable.Parsing[DateTime](
    ISODateTimeFormat.dateTimeParser.parseDateTime(_), _.toString, (key: String, e: Exception) => s"Error parsing date time $key. Example: 2014-04-29T11:56:52Z"
  )

  // Type: date-time-iso8601
  implicit val queryStringBindableTypeDateTimeIso8601 = new QueryStringBindable.Parsing[DateTime](
    ISODateTimeFormat.dateTimeParser.parseDateTime(_), _.toString, (key: String, e: Exception) => s"Error parsing date time $key. Example: 2014-04-29T11:56:52Z"
  )

  // Type: date-iso8601
  implicit val pathBindableTypeDateIso8601 = new PathBindable.Parsing[LocalDate](
    ISODateTimeFormat.yearMonthDay.parseLocalDate(_), _.toString, (key: String, e: Exception) => s"Error parsing date time $key. Example: 2014-04-29"
  )

  // Enum: Role
  private val enumRoleNotFound = (key: String, e: Exception) => s"Unrecognized $key, should be one of ${Role.all.mkString(", ")}"

  private val enumAggregatorNotFound = (key: String, e: Exception) => s"Unrecognized $key, should be one of ${Aggregator.all.mkString(", ")}"

  implicit val pathBindableEnumRole = new PathBindable.Parsing[Role](
    Role.fromString(_).get, _.toString, enumRoleNotFound
  )

  implicit val queryStringBindableEnumRole = new QueryStringBindable.Parsing[Role](
    Role.fromString(_).get, _.toString, enumRoleNotFound
  )

  implicit val queryStringBindableAggregator = new QueryStringBindable.Parsing[Aggregator](
    Aggregator.fromString(_).get, _.toString, enumAggregatorNotFound
  )

} 
Example 23
Source File: ToTableRow.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.extra.bigquery

import com.spotify.scio.extra.bigquery.AvroConverters.AvroConversionException

import java.math.{BigDecimal => JBigDecimal}
import java.nio.ByteBuffer
import java.util

import com.spotify.scio.bigquery.TableRow
import org.apache.avro.Schema
import org.apache.avro.generic.{GenericFixed, IndexedRecord}
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.BaseEncoding
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, LocalDate, LocalTime}

import scala.jdk.CollectionConverters._


private[bigquery] trait ToTableRow {
  private lazy val encodingPropName: String = "bigquery.bytes.encoder"
  private lazy val base64Encoding: BaseEncoding = BaseEncoding.base64()
  private lazy val hexEncoding: BaseEncoding = BaseEncoding.base16()

  // YYYY-[M]M-[D]D
  private[this] val localDateFormatter =
    DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC()

  // YYYY-[M]M-[D]D[( |T)[H]H:[M]M:[S]S[.DDDDDD]]
  private[this] val localTimeFormatter =
    DateTimeFormat.forPattern("HH:mm:ss.SSSSSS")

  // YYYY-[M]M-[D]D[( |T)[H]H:[M]M:[S]S[.DDDDDD]][time zone]
  private[this] val timestampFormatter =
    DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS")

  private[bigquery] def toTableRowField(fieldValue: Any, field: Schema.Field): Any =
    fieldValue match {
      case x: CharSequence          => x.toString
      case x: Enum[_]               => x.name()
      case x: JBigDecimal           => x.toString
      case x: Number                => x
      case x: Boolean               => x
      case x: GenericFixed          => encodeByteArray(x.bytes(), field.schema())
      case x: ByteBuffer            => encodeByteArray(toByteArray(x), field.schema())
      case x: util.Map[_, _]        => toTableRowFromMap(x.asScala, field)
      case x: java.lang.Iterable[_] => toTableRowFromIterable(x.asScala, field)
      case x: IndexedRecord         => AvroConverters.toTableRow(x)
      case x: LocalDate             => localDateFormatter.print(x)
      case x: LocalTime             => localTimeFormatter.print(x)
      case x: DateTime              => timestampFormatter.print(x)
      case _ =>
        throw AvroConversionException(
          s"ToTableRow conversion failed:" +
            s"could not match ${fieldValue.getClass}"
        )
    }

  private def toTableRowFromIterable(iterable: Iterable[Any], field: Schema.Field): util.List[_] =
    iterable
      .map { item =>
        if (item.isInstanceOf[Iterable[_]] || item.isInstanceOf[Map[_, _]]) {
          throw AvroConversionException(
            s"ToTableRow conversion failed for item $item: " +
              s"iterable and map types not supported"
          )
        }
        toTableRowField(item, field)
      }
      .toList
      .asJava

  private def toTableRowFromMap(map: Iterable[Any], field: Schema.Field): util.List[_] =
    map
      .map {
        case (k, v) =>
          new TableRow()
            .set("key", toTableRowField(k, field))
            .set("value", toTableRowField(v, field))
      }
      .toList
      .asJava

  private def encodeByteArray(bytes: Array[Byte], fieldSchema: Schema): String =
    Option(fieldSchema.getProp(encodingPropName)) match {
      case Some("BASE64") => base64Encoding.encode(bytes)
      case Some("HEX")    => hexEncoding.encode(bytes)
      case Some(encoding) =>
        throw AvroConversionException(s"Unsupported encoding $encoding")
      case None => base64Encoding.encode(bytes)
    }

  private def toByteArray(buffer: ByteBuffer) = {
    val copy = buffer.asReadOnlyBuffer
    val bytes = new Array[Byte](copy.limit)
    copy.rewind
    copy.get(bytes)
    bytes
  }
} 
Example 24
Source File: TableRowSyntax.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.bigquery.syntax

// import com.google.api.services.bigquery.model.{TableRow => GTableRow}
import com.spotify.scio.bigquery.{Date, DateTime, TableRow, Time, Timestamp}
import org.joda.time.{Instant, LocalDate, LocalDateTime, LocalTime}

import scala.jdk.CollectionConverters._

import scala.util.Try


final class TableRowOps(private val r: TableRow) extends AnyVal {
  def getBoolean(name: AnyRef): Boolean =
    this.getValue(name, _.toString.toBoolean, false)

  def getBooleanOpt(name: AnyRef): Option[Boolean] =
    this.getValueOpt(name, _.toString.toBoolean)

  def getLong(name: AnyRef): Long = this.getValue(name, _.toString.toLong, 0L)

  def getLongOpt(name: AnyRef): Option[Long] =
    this.getValueOpt(name, _.toString.toLong)

  def getDouble(name: AnyRef): Double =
    this.getValue(name, _.toString.toDouble, 0.0)

  def getDoubleOpt(name: AnyRef): Option[Double] =
    this.getValueOpt(name, _.toString.toDouble)

  def getString(name: AnyRef): String = this.getValue(name, _.toString, null)

  def getStringOpt(name: AnyRef): Option[String] =
    this.getValueOpt(name, _.toString)

  def getTimestamp(name: AnyRef): Instant =
    this.getValue(name, v => Timestamp.parse(v.toString), null)

  def getTimestampOpt(name: AnyRef): Option[Instant] =
    this.getValueOpt(name, v => Timestamp.parse(v.toString))

  def getDate(name: AnyRef): LocalDate =
    this.getValue(name, v => Date.parse(v.toString), null)

  def getDateOpt(name: AnyRef): Option[LocalDate] =
    this.getValueOpt(name, v => Date.parse(v.toString))

  def getTime(name: AnyRef): LocalTime =
    this.getValue(name, v => Time.parse(v.toString), null)

  def getTimeOpt(name: AnyRef): Option[LocalTime] =
    this.getValueOpt(name, v => Time.parse(v.toString))

  def getDateTime(name: AnyRef): LocalDateTime =
    this.getValue(name, v => DateTime.parse(v.toString), null)

  def getDateTimeOpt(name: AnyRef): Option[LocalDateTime] =
    this.getValueOpt(name, v => DateTime.parse(v.toString))

  def getRepeated(name: AnyRef): Seq[AnyRef] =
    this.getValue(name, x => x.asInstanceOf[java.util.List[AnyRef]].iterator().asScala.toSeq, null)

  def getRecord(name: AnyRef): Map[String, AnyRef] =
    r.get(name).asInstanceOf[java.util.Map[String, AnyRef]].asScala.toMap

  private def getValue[T](name: AnyRef, fn: AnyRef => T, default: T): T = {
    val o = r.get(name)
    if (o == null) {
      default
    } else {
      fn(o)
    }
  }

  private def getValueOpt[T](name: AnyRef, fn: AnyRef => T): Option[T] = {
    val o = r.get(name)
    if (o == null) {
      None
    } else {
      Try(fn(o)).toOption
    }
  }
}

trait TableRowSyntax {
  implicit def bigQueryTableRowOps(tr: TableRow): TableRowOps = new TableRowOps(tr)
} 
Example 25
Source File: Schemas.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.bigquery.types

import com.google.protobuf.ByteString
import org.joda.time.{Instant, LocalDate, LocalDateTime, LocalTime}

object Schemas {
  // primitives
  case class Required(
    boolF: Boolean,
    intF: Int,
    longF: Long,
    floatF: Float,
    doubleF: Double,
    stringF: String,
    byteArrayF: Array[Byte],
    byteStringF: ByteString,
    timestampF: Instant,
    dateF: LocalDate,
    timeF: LocalTime,
    datetimeF: LocalDateTime,
    bigDecimalF: BigDecimal,
    geographyF: Geography
  )
  case class Optional(
    boolF: Option[Boolean],
    intF: Option[Int],
    longF: Option[Long],
    floatF: Option[Float],
    doubleF: Option[Double],
    stringF: Option[String],
    byteArrayF: Option[Array[Byte]],
    byteStringF: Option[ByteString],
    timestampF: Option[Instant],
    dateF: Option[LocalDate],
    timeF: Option[LocalTime],
    datetimeF: Option[LocalDateTime],
    bigDecimalF: Option[BigDecimal],
    geographyF: Option[Geography]
  )
  case class Repeated(
    boolF: List[Boolean],
    intF: List[Int],
    longF: List[Long],
    floatF: List[Float],
    doubleF: List[Double],
    stringF: List[String],
    byteArrayF: List[Array[Byte]],
    byteStringF: List[ByteString],
    timestampF: List[Instant],
    dateF: List[LocalDate],
    timeF: List[LocalTime],
    datetimeF: List[LocalDateTime],
    bigDecimalF: List[BigDecimal],
    geographyF: List[Geography]
  )

  // records
  case class RequiredNested(required: Required, optional: Optional, repeated: Repeated)
  case class OptionalNested(
    required: Option[Required],
    optional: Option[Optional],
    repeated: Option[Repeated]
  )
  case class RepeatedNested(
    required: List[Required],
    optional: List[Optional],
    repeated: List[Repeated]
  )

  case class User(@description("user name") name: String, @description("user age") age: Int)
  case class Account(
    @description("account user") user: User,
    @description("in USD") balance: Double
  )
} 
Example 26
Source File: JodaSerializer.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.coders.instances.kryo

import com.esotericsoftware.kryo.io.{Input, Output}
import com.esotericsoftware.kryo.{Kryo, Serializer}
import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime, LocalTime}
import org.joda.time.chrono.ISOChronology

private[coders] class JodaLocalDateTimeSerializer extends Serializer[LocalDateTime] {
  setImmutable(true)

  def write(kryo: Kryo, output: Output, ldt: LocalDateTime): Unit = {
    output.writeInt(ldt.getYear,  false)
    val month = input.readByte().toInt
    val day = input.readByte().toInt

    new LocalDate(year, month, day)
  }
}

private[coders] class JodaDateTimeSerializer extends Serializer[DateTime] {
  setImmutable(true)

  def write(kryo: Kryo, output: Output, dt: DateTime): Unit = {
    output.writeLong(dt.getMillis)
    output.writeString(dt.getZone.getID)
  }

  def read(kryo: Kryo, input: Input, tpe: Class[DateTime]): DateTime = {
    val millis = input.readLong()
    val zone = DateTimeZone.forID(input.readString())
    new DateTime(millis, zone)
  }
} 
Example 27
Source File: TypedBigQueryIT.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.bigquery

import com.google.protobuf.ByteString
import com.spotify.scio._
import com.spotify.scio.bigquery.client.BigQuery
import com.spotify.scio.testing._
import magnolify.scalacheck.auto._
import org.apache.beam.sdk.options.PipelineOptionsFactory
import org.joda.time.format.DateTimeFormat
import org.joda.time.{Instant, LocalDate, LocalDateTime, LocalTime}
import org.scalacheck._
import org.scalatest.BeforeAndAfterAll

import scala.util.Random

object TypedBigQueryIT {
  @BigQueryType.toTable
  case class Record(
    bool: Boolean,
    int: Int,
    long: Long,
    float: Float,
    double: Double,
    string: String,
    byteString: ByteString,
    timestamp: Instant,
    date: LocalDate,
    time: LocalTime,
    datetime: LocalDateTime
  )

  // Workaround for millis rounding error
  val epochGen = Gen.chooseNum[Long](0L, 1000000000000L).map(x => x / 1000 * 1000)
  implicit val arbByteString = Arbitrary(Gen.alphaStr.map(ByteString.copyFromUtf8))
  implicit val arbInstant = Arbitrary(epochGen.map(new Instant(_)))
  implicit val arbDate = Arbitrary(epochGen.map(new LocalDate(_)))
  implicit val arbTime = Arbitrary(epochGen.map(new LocalTime(_)))
  implicit val arbDatetime = Arbitrary(epochGen.map(new LocalDateTime(_)))

  private val recordGen = {
    implicitly[Arbitrary[Record]].arbitrary
  }

  private val table = {
    val TIME_FORMATTER = DateTimeFormat.forPattern("yyyyMMddHHmmss")
    val now = Instant.now().toString(TIME_FORMATTER)
    val spec =
      "data-integration-test:bigquery_avro_it.records_" + now + "_" + Random.nextInt(Int.MaxValue)
    Table.Spec(spec)
  }
  private val records = Gen.listOfN(1000, recordGen).sample.get
  private val options = PipelineOptionsFactory
    .fromArgs(
      "--project=data-integration-test",
      "--tempLocation=gs://data-integration-test-eu/temp"
    )
    .create()
}

class TypedBigQueryIT extends PipelineSpec with BeforeAndAfterAll {
  import TypedBigQueryIT._

  override protected def beforeAll(): Unit = {
    val sc = ScioContext(options)
    sc.parallelize(records).saveAsTypedBigQueryTable(table)

    sc.run()
    ()
  }

  override protected def afterAll(): Unit =
    BigQuery.defaultInstance().tables.delete(table.ref)

  "TypedBigQuery" should "read records" in {
    val sc = ScioContext(options)
    sc.typedBigQuery[Record](table) should containInAnyOrder(records)
    sc.run()
  }
} 
Example 28
Source File: JodaSerializerTest.scala    From scio   with Apache License 2.0 5 votes vote down vote up
package com.spotify.scio.coders.instances.kryo

import com.spotify.scio.coders.{CoderTestUtils, KryoAtomicCoder, KryoOptions}
import org.joda.time.{DateTime, DateTimeZone, LocalDate, LocalDateTime, LocalTime}
import org.scalacheck._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatestplus.scalacheck.Checkers

import scala.jdk.CollectionConverters._
import scala.util.Try

class JodaSerializerTest extends AnyFlatSpec with Checkers {
  // TODO: remove this once https://github.com/scalatest/scalatest/issues/1090 is addressed
  implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
    PropertyCheckConfiguration(minSuccessful = 100)

  implicit val dateTimeArb = Arbitrary {
    for {
      year <- Gen.choose(-292275054, 292278993)
      month <- Gen.choose(1, 12)
      maxDayOfMonth <- Try {
        Gen.const(new LocalDateTime(year, month, 1, 0, 0).dayOfMonth().getMaximumValue)
      }.getOrElse(Gen.fail)
      day <- Gen.choose(1, maxDayOfMonth)
      hour <- Gen.choose(0, 23)
      minute <- Gen.choose(0, 59)
      second <- Gen.choose(0, 59)
      ms <- Gen.choose(0, 999)
      tz <- Gen.oneOf(DateTimeZone.getAvailableIDs.asScala.toSeq)
      attempt <- Try {
        val ldt = new DateTime(year, month, day, hour, minute, second, ms, DateTimeZone.forID(tz))
        Gen.const(ldt)
      }.getOrElse(Gen.fail)
    } yield attempt
  }

  implicit val localDateTimeArb = Arbitrary {
    Arbitrary.arbitrary[DateTime].map(_.toLocalDateTime)
  }

  implicit val localTimeArb = Arbitrary {
    Arbitrary.arbitrary[LocalDateTime].map(_.toLocalTime)
  }

  implicit val localDateArb = Arbitrary {
    Arbitrary.arbitrary[LocalDateTime].map(_.toLocalDate)
  }

  val coder = new KryoAtomicCoder[Any](KryoOptions())

  def roundTripProp[T](value: T): Prop = Prop.secure {
    CoderTestUtils.testRoundTrip(coder, value)
  }

  "KryoAtomicCoder" should "roundtrip LocalDate" in {
    check(roundTripProp[LocalDate] _)
  }

  it should "roundtrip LocalTime" in {
    check(roundTripProp[LocalTime] _)
  }

  it should "roundtrip LocalDateTime" in {
    check(roundTripProp[LocalDateTime] _)
  }

  it should "roundtrip DateTime" in {
    check(roundTripProp[DateTime] _)
  }
} 
Example 29
Source File: MockNIRecordController.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.helpers

import org.joda.time.LocalDate
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.cache.client.SessionCache
import uk.gov.hmrc.nisp.config.ApplicationGlobalTrait
import uk.gov.hmrc.nisp.controllers.NIRecordController
import uk.gov.hmrc.nisp.controllers.auth.AuthAction
import uk.gov.hmrc.nisp.controllers.connectors.CustomAuditConnector
import uk.gov.hmrc.nisp.services.{MetricsService, NationalInsuranceService, StatePensionService}
import uk.gov.hmrc.nisp.utils.MockTemplateRenderer
import uk.gov.hmrc.play.partials.CachedStaticHtmlPartialRetriever
import uk.gov.hmrc.renderer.TemplateRenderer

class MockNIRecordControllerImpl(nino: Nino) extends MockNIRecordController {
  override val customAuditConnector: CustomAuditConnector = MockCustomAuditConnector
  override val sessionCache: SessionCache = MockSessionCache
  override lazy val showFullNI: Boolean = true
  override val currentDate = new LocalDate(2016,9,9)
  override val metricsService: MetricsService = MockMetricsService
  override val authenticate: AuthAction = new MockAuthAction(nino)
}

trait MockNIRecordController extends NIRecordController {
  override val nationalInsuranceService: NationalInsuranceService = MockNationalInsuranceServiceViaNationalInsurance
  override val statePensionService: StatePensionService = MockStatePensionServiceViaStatePension

  override implicit val cachedStaticHtmlPartialRetriever: CachedStaticHtmlPartialRetriever = MockCachedStaticHtmlPartialRetriever
  override implicit val templateRenderer: TemplateRenderer = MockTemplateRenderer
  override val applicationGlobal:ApplicationGlobalTrait = MockApplicationGlobal

} 
Example 30
Source File: Person.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package models

import org.joda.time.{DateTime, Instant, LocalDate}
import play.api.libs.json._
import uk.gov.hmrc.domain.Nino
import _root_.util.DateTimeTools
import play.api.libs.json.JodaWrites._
import play.api.libs.json.JodaReads._
import play.api.libs.functional.syntax._

case class Person(
  firstName: Option[String],
  middleName: Option[String],
  lastName: Option[String],
  initials: Option[String],
  title: Option[String],
  honours: Option[String],
  sex: Option[String],
  dateOfBirth: Option[LocalDate],
  nino: Option[Nino]
) {
  lazy val initialsName =
    initials.getOrElse(List(title, firstName.map(_.take(1)), middleName.map(_.take(1)), lastName).flatten.mkString(" "))
  lazy val shortName = for {
    f <- firstName
    l <- lastName
  } yield List(f, l).mkString(" ")
  lazy val fullName = List(title, firstName, middleName, lastName, honours).flatten.mkString(" ")
}

object Person {

  implicit val localdateFormatDefault = new Format[LocalDate] {
    override def reads(json: JsValue): JsResult[LocalDate] = JodaReads.DefaultJodaLocalDateReads.reads(json)
    override def writes(o: LocalDate): JsValue = JodaWrites.DefaultJodaLocalDateWrites.writes(o)
  }

  implicit val formats = Json.format[Person]

} 
Example 31
Source File: Address.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package models

import org.joda.time.{DateTime, Instant, LocalDate}
import play.api.libs.json._
import _root_.util.DateTimeTools
import play.api.libs.json.JodaWrites._
import play.api.libs.json.JodaReads._

case class Address(
  line1: Option[String],
  line2: Option[String],
  line3: Option[String],
  line4: Option[String],
  line5: Option[String],
  postcode: Option[String],
  country: Option[String],
  startDate: Option[LocalDate],
  endDate: Option[LocalDate],
  `type`: Option[String]
) {
  lazy val lines = List(line1, line2, line3, line4, line5).flatten
  lazy val fullAddress =
    List(line1, line2, line3, line4, line5, postcode.map(_.toUpperCase), internationalAddressCountry(country)).flatten

  val excludedCountries = List(
    Country("GREAT BRITAIN"),
    Country("SCOTLAND"),
    Country("ENGLAND"),
    Country("WALES"),
    Country("NORTHERN IRELAND")
  )

  def internationalAddressCountry(country: Option[String]): Option[String] =
    excludedCountries.contains(Country(country.getOrElse(""))) match {
      case false => country
      case _     => None
    }

  def isWelshLanguageUnit: Boolean = {
    val welshLanguageUnitPostcodes = Set("CF145SH", "CF145TS", "LL499BF", "BX55AB", "LL499AB")
    welshLanguageUnitPostcodes.contains(postcode.getOrElse("").toUpperCase.trim.replace(" ", ""))
  }
}

object Address {
  implicit val localdateFormatDefault = new Format[LocalDate] {
    override def reads(json: JsValue): JsResult[LocalDate] = JodaReads.DefaultJodaLocalDateReads.reads(json)
    override def writes(o: LocalDate): JsValue = JodaWrites.DefaultJodaLocalDateWrites.writes(o)
  }
  implicit val formats = Json.format[Address]
} 
Example 32
Source File: UpdateInternationalAddressController.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package controllers.address

import com.google.inject.Inject
import config.ConfigDecorator
import controllers.auth.{AuthJourney, WithActiveTabAction}
import controllers.bindable.{AddrType, PostalAddrType}
import controllers.controllershelpers.{AddressJourneyCachingHelper, CountryHelper}
import models.dto.{AddressDto, DateDto}
import models.{SubmittedAddressDtoId, SubmittedStartDateId}
import org.joda.time.LocalDate
import play.api.mvc.{Action, AnyContent, MessagesControllerComponents, Result}
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
import uk.gov.hmrc.renderer.TemplateRenderer
import util.AuditServiceTools.buildAddressChangeEvent
import util.LocalPartialRetriever
import views.html.interstitial.DisplayAddressInterstitialView
import views.html.personaldetails.UpdateInternationalAddressView

import scala.concurrent.{ExecutionContext, Future}

class UpdateInternationalAddressController @Inject()(
  countryHelper: CountryHelper,
  cachingHelper: AddressJourneyCachingHelper,
  auditConnector: AuditConnector,
  authJourney: AuthJourney,
  withActiveTabAction: WithActiveTabAction,
  cc: MessagesControllerComponents,
  updateInternationalAddressView: UpdateInternationalAddressView,
  displayAddressInterstitialView: DisplayAddressInterstitialView)(
  implicit partialRetriever: LocalPartialRetriever,
  configDecorator: ConfigDecorator,
  templateRenderer: TemplateRenderer,
  ec: ExecutionContext)
    extends AddressController(authJourney, withActiveTabAction, cc, displayAddressInterstitialView) {

  def onPageLoad(typ: AddrType): Action[AnyContent] =
    authenticate.async { implicit request =>
      cachingHelper.gettingCachedJourneyData[Result](typ) { journeyData =>
        addressJourneyEnforcer { _ => personDetails =>
          typ match {
            case PostalAddrType =>
              auditConnector.sendEvent(
                buildAddressChangeEvent("postalAddressChangeLinkClicked", personDetails, isInternationalAddress = true))
              cachingHelper.enforceDisplayAddressPageVisited(journeyData.addressPageVisitedDto) {
                Future.successful(
                  Ok(
                    updateInternationalAddressView(
                      journeyData.submittedAddressDto.fold(AddressDto.internationalForm)(
                        AddressDto.internationalForm.fill),
                      typ,
                      countryHelper.countries
                    )
                  )
                )
              }

            case _ =>
              auditConnector.sendEvent(
                buildAddressChangeEvent("mainAddressChangeLinkClicked", personDetails, isInternationalAddress = true))
              cachingHelper.enforceResidencyChoiceSubmitted(journeyData) { _ =>
                Future.successful(
                  Ok(
                    updateInternationalAddressView(AddressDto.internationalForm, typ, countryHelper.countries)
                  )
                )
              }
          }
        }
      }
    }

  def onSubmit(typ: AddrType): Action[AnyContent] =
    authenticate.async { implicit request =>
      cachingHelper.gettingCachedJourneyData[Result](typ) { _ =>
        addressJourneyEnforcer { _ => _ =>
          AddressDto.internationalForm.bindFromRequest.fold(
            formWithErrors => {
              Future.successful(
                BadRequest(updateInternationalAddressView(formWithErrors, typ, countryHelper.countries)))
            },
            addressDto => {
              cachingHelper.addToCache(SubmittedAddressDtoId(typ), addressDto) flatMap { _ =>
                typ match {
                  case PostalAddrType =>
                    cachingHelper.addToCache(SubmittedStartDateId(typ), DateDto(LocalDate.now()))
                    Future.successful(Redirect(routes.AddressSubmissionController.onPageLoad(typ)))
                  case _ =>
                    Future.successful(Redirect(routes.StartDateController.onPageLoad(typ)))
                }
              }
            }
          )
        }
      }
    }
} 
Example 33
Source File: package.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package viewmodels

import org.joda.time.LocalDate

case class Heading(label: Message, url: Url)

case class Link(message: Message, url: Url, gaLabel: String)

case class TaxYears(previousTaxYear: Int, currentTaxYear: Int)

sealed trait Message
case class Text(key: String, args: List[Message]) extends Message
case class Date(date: Option[LocalDate], default: String = "dd MMMM yyyy") extends Message
case class Literal(value: String) extends Message

object Message {

  def text(key: String): Message =
    Text(key, Nil)

  def text(key: String, args: String*): Message =
    Text(key, args.toList.map(Literal))

  def text(key: String, args: Message*)(implicit d: DummyImplicit): Message =
    Text(key, args.toList)
}

sealed trait Url
case object MakePaymentUrl extends Url
case object TaxPaidUrl extends Url
case class UnderpaidUrl(year: Int) extends Url
case class UnderpaidReasonsUrl(year: Int) extends Url
case class OverpaidUrl(year: Int) extends Url
case class OverpaidReasonsUrl(year: Int) extends Url
case class RightAmountUrl(year: Int) extends Url
case class NotCalculatedUrl(year: Int) extends Url
case class NotEmployedUrl(year: Int) extends Url
case object Empty extends Url 
Example 34
Source File: DateDtoSpec.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package models.dto

import org.joda.time.LocalDate
import util.BaseSpec

class DateDtoSpec extends BaseSpec {

  "Posting the enterStartDateForm" should {

    "bind DateDto correctly when given valid data" in {
      val formData = Map(
        "startDate.day"   -> "1",
        "startDate.month" -> "1",
        "startDate.year"  -> new LocalDate().minusYears(1).getYear.toString
      )

      val previousYear = new LocalDate(new LocalDate().minusYears(1).getYear, 1, 1)

      DateDto
        .form(LocalDate.now())
        .bind(formData)
        .fold(
          formWithErrors => {
            formWithErrors.errors.length shouldBe 0
          },
          success => {
            success shouldBe DateDto(previousYear)
          }
        )

    }

    "return error when future date is submitted" in {

      val formData = Map(
        "startDate.day"   -> "1",
        "startDate.month" -> "1",
        "startDate.year"  -> new LocalDate().plusYears(1).getYear.toString
      )

      DateDto
        .form(LocalDate.now())
        .bind(formData)
        .fold(
          formWithErrors => {
            formWithErrors.errors.length shouldBe 1
            formWithErrors.errors.head.message shouldBe "error.date_in_future"
          },
          success => {
            fail("Form should give an error")
          }
        )
    }

    "return an error date is before 01/01/1000" in {

      val formData = Map(
        "startDate.day"   -> "1",
        "startDate.month" -> "1",
        "startDate.year"  -> "0999"
      )

      DateDto
        .form(LocalDate.now())
        .bind(formData)
        .fold(
          formWithErrors => {
            formWithErrors.errors.length shouldBe 1
            formWithErrors.errors.head.message shouldBe "error.enter_valid_date"
          },
          success => {
            fail("Form should give an error")
          }
        )
    }
  }
} 
Example 35
Source File: AddressFixture.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package util.fixtures

import models.Address
import org.joda.time.LocalDate

object AddressFixture {

  def address(
    line1: Option[String] = None,
    line2: Option[String] = None,
    line3: Option[String] = None,
    line4: Option[String] = None,
    line5: Option[String] = None,
    postcode: Option[String] = None,
    country: Option[String] = None,
    startDate: Option[LocalDate] = None,
    endDate: Option[LocalDate] = None,
    `type`: Option[String] = None) =
    Address(line1, line2, line3, line4, line5, postcode, country, startDate, endDate, `type`)

} 
Example 36
Source File: Calculate.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import org.joda.time.{LocalDate, Period}
import uk.gov.hmrc.nisp.models.{SPChartModel, StatePensionAmount}

object Calculate {

  def calculateChartWidths(current: StatePensionAmount, forecast: StatePensionAmount, personalMaximum: StatePensionAmount): (SPChartModel, SPChartModel, SPChartModel) = {
    // scalastyle:off magic.number
    if (personalMaximum.weeklyAmount > forecast.weeklyAmount) {
      val currentChart = SPChartModel((current.weeklyAmount / personalMaximum.weeklyAmount * 100).toInt.max(Constants.chartWidthMinimum), current)
      val forecastChart = SPChartModel((forecast.weeklyAmount / personalMaximum.weeklyAmount * 100).toInt.max(Constants.chartWidthMinimum), forecast)
      val personalMaxChart = SPChartModel(100, personalMaximum)
      (currentChart, forecastChart, personalMaxChart)
    } else {
      if (forecast.weeklyAmount > current.weeklyAmount) {
        val currentPercentage = (current.weeklyAmount / forecast.weeklyAmount * 100).toInt
        val currentChart = SPChartModel(currentPercentage.max(Constants.chartWidthMinimum), current)
        val forecastChart = SPChartModel(100, forecast)
        (currentChart, forecastChart, forecastChart)
      } else {
        val currentChart = SPChartModel(100, current)
        val forecastChart = SPChartModel((forecast.weeklyAmount / current.weeklyAmount * 100).toInt, forecast)
        (currentChart, forecastChart, forecastChart)
      }
    }
  }

  def calculateAge(dateOfBirth: LocalDate, currentDate: LocalDate): Int = {
    new Period(dateOfBirth, currentDate).getYears
  }

} 
Example 37
Source File: Citizen.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models.citizen

import org.joda.time.{DateTime, LocalDate}
import uk.gov.hmrc.domain.Nino
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class Citizen(nino: Nino, firstName: Option[String] = None, lastName: Option[String] = None,
                   dateOfBirth: LocalDate) {
  def getNameFormatted: Option[String] = {
    (firstName, lastName) match {
      case (Some(firstName), Some(lastName)) => Some("%s %s".format(firstName, lastName))
      case _ => None
    }
  }
}

object Citizen {

  implicit val dateReads: Reads[LocalDate] = Reads[LocalDate] {
    case value: JsNumber => value.validate[Long].map(new LocalDate(_))
    case value => value.validate[String].map(LocalDate.parse)
  }

  implicit val formats = Json.format[Citizen]
} 
Example 38
Source File: NationalInsuranceRecord.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import play.api.libs.json._
import play.api.libs.functional.syntax._

case class NationalInsuranceRecord(
                                    qualifyingYears: Int,
                                    qualifyingYearsPriorTo1975: Int,
                                    numberOfGaps: Int,
                                    numberOfGapsPayable: Int,
                                    dateOfEntry: Option[LocalDate],
                                    homeResponsibilitiesProtection: Boolean,
                                    earningsIncludedUpTo: LocalDate,
                                    taxYears: List[NationalInsuranceTaxYear],
                                    reducedRateElection:Boolean
                                  )

object NationalInsuranceRecord {

  val readNullableBoolean: JsPath => Reads[Boolean] =
    jsPath => jsPath.readNullable[Boolean].map(_.getOrElse(false))

  implicit val reads: Reads[NationalInsuranceRecord] = (
    (JsPath \ "qualifyingYears").read[Int] and
      (JsPath \ "qualifyingYearsPriorTo1975").read[Int] and
      (JsPath \ "numberOfGaps").read[Int] and
      (JsPath \ "numberOfGapsPayable").read[Int] and
      (JsPath \ "dateOfEntry").readNullable[LocalDate] and
      (JsPath \ "homeResponsibilitiesProtection").read[Boolean] and
      (JsPath \ "earningsIncludedUpTo").read[LocalDate] and
      (JsPath \ "_embedded" \ "taxYears").read[JsValue].map {
        case obj: JsObject => List(obj.as[NationalInsuranceTaxYear])
        case other => other.as[List[NationalInsuranceTaxYear]]
      } and
      readNullableBoolean(JsPath \ "reducedRateElection")
    ) (NationalInsuranceRecord.apply _)

  implicit val writes: Writes[NationalInsuranceRecord] = (
    (JsPath \ "qualifyingYears").write[Int] and
      (JsPath \ "qualifyingYearsPriorTo1975").write[Int] and
      (JsPath \ "numberOfGaps").write[Int] and
      (JsPath \ "numberOfGapsPayable").write[Int] and
      (JsPath \ "dateOfEntry").writeNullable[LocalDate] and
      (JsPath \ "homeResponsibilitiesProtection").write[Boolean] and
      (JsPath \ "earningsIncludedUpTo").write[LocalDate] and
      (JsPath \ "_embedded" \ "taxYears").write[List[NationalInsuranceTaxYear]] and
      (JsPath \ "reducedRateElection").write[Boolean]
    ) (unlift(NationalInsuranceRecord.unapply))

  implicit val formats: Format[NationalInsuranceRecord] = Format(reads, writes)
} 
Example 39
Source File: NationalInsuranceTaxYear.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import play.api.libs.json.{Format, Json}

case class NationalInsuranceTaxYear(
                                     taxYear: String,
                                     qualifying: Boolean,
                                     classOneContributions: BigDecimal,
                                     classTwoCredits: Int,
                                     classThreeCredits: Int,
                                     otherCredits: Int,
                                     classThreePayable: BigDecimal,
                                     classThreePayableBy: Option[LocalDate],
                                     classThreePayableByPenalty: Option[LocalDate],
                                     payable: Boolean,
                                     underInvestigation: Boolean
                                   ) {

  def currentDateAfterCutOff(currentDate: LocalDate): Boolean = {
    classThreePayableBy match {
      case Some(classThreeDate) => currentDate.isAfter(classThreeDate)
      case None => payable
    }
  }

}



object NationalInsuranceTaxYear {
  implicit val formats: Format[NationalInsuranceTaxYear] = Json.format[NationalInsuranceTaxYear]
} 
Example 40
Source File: NpsDate.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import play.api.data.validation.ValidationError
import play.api.libs.json._
import uk.gov.hmrc.nisp.utils.Constants

case class NpsDate (localDate: LocalDate) {
  val toNpsString: String = NpsDate.dateFormat.print(localDate)

  val taxYear: Int = {
    val year = localDate.year.get
    if (localDate.isBefore(new LocalDate(year, Constants.taxYearsStartEndMonth, Constants.taxYearStartDay))) year - 1 else year
  }
}

object NpsDate {
  private val dateFormat = DateTimeFormat.forPattern("dd/MM/yyyy")
  private val npsDateRegex = """^(\d\d)/(\d\d)/(\d\d\d\d)$""".r

  implicit val reads = new Reads[NpsDate] {
    override def reads(json:JsValue): JsResult[NpsDate] = {
      json match {
        case JsString(npsDateRegex(d,m,y)) => JsSuccess(NpsDate(new LocalDate(y.toInt, m.toInt, d.toInt)))
        case JsNull => JsError(ValidationError("Null date cannot convert to NpsDate"))
      }
    }
  }

  implicit val writes = new Writes[NpsDate] {
    override def writes(date: NpsDate): JsValue = JsString(date.toNpsString)
  }
  def taxYearEndDate(taxYear: Int): NpsDate = NpsDate(taxYear + 1, Constants.taxYearsStartEndMonth, Constants.taxYearEndDay)
  def taxYearStartDate(taxYear: Int): NpsDate = NpsDate(taxYear, Constants.taxYearsStartEndMonth, Constants.taxYearStartDay)
  def apply(year: Int, month: Int, day: Int): NpsDate = NpsDate(new LocalDate(year,month,day))
} 
Example 41
Source File: StatePensionService.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.services

import org.joda.time.LocalDate
import play.api.http.Status._
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, Upstream4xxResponse}
import uk.gov.hmrc.nisp.connectors.StatePensionConnector
import uk.gov.hmrc.nisp.models._
import uk.gov.hmrc.nisp.models.enums.Exclusion
import uk.gov.hmrc.nisp.models.enums.Exclusion._
import uk.gov.hmrc.play.http.logging.MdcLoggingExecutionContext._
import uk.gov.hmrc.time.CurrentTaxYear

import scala.concurrent.Future


trait StatePensionService extends CurrentTaxYear {
  def getSummary(nino: Nino)(implicit hc: HeaderCarrier): Future[Either[StatePensionExclusionFiltered, StatePension]]

  def yearsToContributeUntilPensionAge(earningsIncludedUpTo: LocalDate, finalRelevantYearStart: Int): Int = {
    finalRelevantYearStart - taxYearFor(earningsIncludedUpTo).startYear
  }

  private[services] def filterExclusions(exclusions: List[Exclusion]): Exclusion = {
    if (exclusions.contains(Exclusion.Dead)) {
      Exclusion.Dead
    } else if (exclusions.contains(Exclusion.ManualCorrespondenceIndicator)) {
      Exclusion.ManualCorrespondenceIndicator
    } else if (exclusions.contains(Exclusion.PostStatePensionAge)) {
      Exclusion.PostStatePensionAge
    } else if (exclusions.contains(Exclusion.AmountDissonance)) {
      Exclusion.AmountDissonance
    } else if (exclusions.contains(Exclusion.IsleOfMan)) {
      Exclusion.IsleOfMan
    } else if (exclusions.contains(Exclusion.MarriedWomenReducedRateElection)) {
      Exclusion.MarriedWomenReducedRateElection
    } else {
      throw new RuntimeException(s"Un-accounted for exclusion in NispConnectionNI: $exclusions")
    }
  }
}

trait StatePensionConnection extends StatePensionService {
  val statePensionConnector: StatePensionConnector

  final val exclusionCodeDead = "EXCLUSION_DEAD"
  final val exclusionCodeManualCorrespondence = "EXCLUSION_MANUAL_CORRESPONDENCE"

  def getSummary(nino: Nino)(implicit hc: HeaderCarrier): Future[Either[StatePensionExclusionFiltered, StatePension]] = {
    statePensionConnector.getStatePension(nino)
      .map {
        case Right(statePension) => Right(statePension)

        case Left(spExclusion) => Left(StatePensionExclusionFiltered(
            filterExclusions(spExclusion.exclusionReasons),
            spExclusion.pensionAge,
            spExclusion.pensionDate,
            spExclusion.statePensionAgeUnderConsideration
          ))
      }
      .recover {
      case ex: Upstream4xxResponse if ex.upstreamResponseCode == FORBIDDEN && ex.message.contains(exclusionCodeDead) =>
        Left(StatePensionExclusionFiltered(Exclusion.Dead))
      case ex: Upstream4xxResponse if ex.upstreamResponseCode == FORBIDDEN && ex.message.contains(exclusionCodeManualCorrespondence) =>
        Left(StatePensionExclusionFiltered(Exclusion.ManualCorrespondenceIndicator))
    }
  }
} 
Example 42
Source File: AccountAccessEvent.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.events

import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import uk.gov.hmrc.nisp.models.enums.Scenario.Scenario
import uk.gov.hmrc.http.HeaderCarrier

object AccountAccessEvent {
  def apply(nino: String, statePensionAge: LocalDate, statePensionAmount: BigDecimal,
            statePensionForecast: BigDecimal, dateOfBirth: LocalDate, name: String,
            contractedOutFlag: Boolean = false, forecastScenario: Scenario, copeAmount: BigDecimal,
            authenticationProvider: String)(implicit hc: HeaderCarrier): AccountAccessEvent =
    new AccountAccessEvent(
      nino,
      statePensionAge,
      statePensionAmount,
      statePensionForecast,
      dateOfBirth,
      name,
      contractedOutFlag,
      forecastScenario,
      copeAmount,
      authenticationProvider
    )
}
class AccountAccessEvent(nino: String, statePensionAge: LocalDate, statePensionAmount: BigDecimal,
                         statePensionForecast: BigDecimal, dateOfBirth: LocalDate, name: String, contractedOutFlag: Boolean, forecastScenario: Scenario,
                         copeAmount: BigDecimal, authenticationProvider: String)(implicit hc: HeaderCarrier)
  extends NispBusinessEvent("AccountPage",
    Map(
      "nino" -> nino,
      "StatePensionAge" -> DateTimeFormat.forPattern("dd/MM/yyyy").print(statePensionAge),
      "StatePensionAmount" -> statePensionAmount.toString(),
      "StatePensionForecast" -> statePensionForecast.toString(),
      "DateOfBirth" -> DateTimeFormat.forPattern("dd/MM/yyyy").print(dateOfBirth),
      "Name" -> name,
      "ContractedOut" -> contractedOutFlag.toString,
      "ForecastScenario" -> forecastScenario.toString,
      "COPEAmount" -> copeAmount.toString(),
      "AuthenticationProvider" -> authenticationProvider
    )
) 
Example 43
Source File: DateDto.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package models.dto

import org.joda.time.LocalDate
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.json.Json
import uk.gov.hmrc.play.mappers.DateTuple._
import play.api.libs.json.JodaWrites._
import play.api.libs.json.JodaReads._

case class DateDto(
  startDate: LocalDate
)

object DateDto {

  implicit val formats = Json.format[DateDto]

  def build(day: Int, month: Int, year: Int) = DateDto(new LocalDate(year, month, day))

  def form(today: LocalDate) = Form(
    mapping(
      "startDate" -> mandatoryDateTuple("error.enter_a_date")
        .verifying("error.date_in_future", !_.isAfter(today))
        .verifying("error.enter_valid_date", !_.isBefore(new LocalDate("1000-01-01")))
    )(DateDto.apply)(DateDto.unapply)
  )
} 
Example 44
Source File: CalculateSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.utils

import org.joda.time.LocalDate
import uk.gov.hmrc.nisp.models.StatePensionAmountRegular
import uk.gov.hmrc.play.test.UnitSpec

class CalculateSpec extends UnitSpec {

  "calculate chart widths" should {
    def calculateCharts(currentAmount: BigDecimal, forecastAmount: BigDecimal, personalMax: BigDecimal) =
      Calculate.calculateChartWidths(StatePensionAmountRegular(currentAmount, 0, 0), StatePensionAmountRegular(forecastAmount, 0, 0), StatePensionAmountRegular(personalMax, 0, 0))

    "current chart is 100 when current amount is higher" in {
      val (currentChart, forecastChart, personalMaxChart) = calculateCharts(70, 30, 0)
      currentChart.width shouldBe 100
    }

    "forecast chart is 100 when forecast amount is higher" in {
      val (currentChart, forecastChart, personalMaxChart) = calculateCharts(70, 80, 80)
      forecastChart.width shouldBe 100
      personalMaxChart.width shouldBe 100
    }

    "current chart and forecast chart are 100 when amounts are equal" in {
      val (currentChart, forecastChart, personalMaxChart) = calculateCharts(70, 70, 70)
      currentChart.width shouldBe 100
      forecastChart.width shouldBe 100
      personalMaxChart.width shouldBe 100
    }

    "current chart is 66 when current amount is 2 and forecast is 3" in {
      val (currentChart, forecastChart, personalMaxChart) = calculateCharts(2, 3, 4)
      currentChart.width shouldBe 50
      forecastChart.width shouldBe 75
      personalMaxChart.width shouldBe 100
    }

    "forecast chart is 30 when forecast amount is 4 and current is 13" in {
      val (currentChart, forecastChart, personalMaxChart) = calculateCharts(13, 4, 20)
      forecastChart.width shouldBe 31
      currentChart.width shouldBe 65
      personalMaxChart.width shouldBe 100
    }
  }

  "calculateAge" should {
    "return 30 when the currentDate is 2016-11-2 their dateOfBirth is 1986-10-28" in {
      Calculate.calculateAge(new LocalDate(1986, 10, 28), new LocalDate(2016, 11, 2)) shouldBe 30
    }
    "return 30 when the currentDate is 2016-11-2 their dateOfBirth is 1986-11-2" in {
      Calculate.calculateAge(new LocalDate(1986, 11, 2), new LocalDate(2016, 11, 2)) shouldBe 30

    }
    "return 29 when the currentDate is 2016-11-2 their dateOfBirth is 1986-11-3" in {
      Calculate.calculateAge(new LocalDate(1986, 11, 3), new LocalDate(2016, 11, 2)) shouldBe 29
    }
  }

} 
Example 45
Source File: NationalInsuranceTaxYearSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import uk.gov.hmrc.play.test.UnitSpec

class NationalInsuranceTaxYearSpec extends UnitSpec {
  "currentDateAfterCutOff" when {

    "the current date is before the payableBy date" should {
      "return false" in {
        val taxYear = NationalInsuranceTaxYear("", false, 0, 0, 0, 0, 123.45, Some(new LocalDate(2019, 4, 5)), Some(new LocalDate(2023, 4, 5)), true, false)
        taxYear.currentDateAfterCutOff(new LocalDate(2019, 4, 4)) shouldBe false
      }
    }

    "the current date is equal to the payableBy date" should {
      "return false" in {
        val taxYear = NationalInsuranceTaxYear("", false, 0, 0, 0, 0, 123.45, Some(new LocalDate(2019, 4, 5)), Some(new LocalDate(2023, 4, 5)), true, false)
        taxYear.currentDateAfterCutOff(new LocalDate(2019, 4, 5)) shouldBe false
      }
    }

    "the current date is after to the payableBy date" should {
      "return true" in {
        val taxYear = NationalInsuranceTaxYear("", false, 0, 0, 0, 0, 123.45, Some(new LocalDate(2019, 4, 5)), Some(new LocalDate(2023, 4, 5)), true, false)
        taxYear.currentDateAfterCutOff(new LocalDate(2019, 4, 6)) shouldBe true
      }
    }

    "the payable date is missing and the year is not payable" should {
      "return false" in {
        val taxYear = NationalInsuranceTaxYear("", false, 0, 0, 0, 0, 123.45, None, None, false, false)
        taxYear.currentDateAfterCutOff(new LocalDate(2019, 4, 6)) shouldBe false
      }
    }

    "the payable date is missing and the year is payable" should {
      "return true" in {
        val taxYear = NationalInsuranceTaxYear("", false, 0, 0, 0, 0, 123.45, None, Some(new LocalDate(2023, 4, 5)), true, false)
        taxYear.currentDateAfterCutOff(new LocalDate(2020, 4, 6)) shouldBe true
      }
    }
  }
} 
Example 46
Source File: StatePensionExclusionSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import uk.gov.hmrc.nisp.models.enums.Exclusion
import uk.gov.hmrc.play.test.UnitSpec


class StatePensionExclusionSpec extends UnitSpec {

  "finalRelevantStartYear" when {
    "there is no pension date" should {
      "be none" in {
        StatePensionExclusion(List(Exclusion.Dead), None, None).finalRelevantStartYear shouldBe None
      }
    }

    "the pensionDate is 5th April 2020" should {
      "be 2018" in {
        StatePensionExclusion(List(Exclusion.AmountDissonance), Some(67), Some(new LocalDate(2020, 4, 5))).finalRelevantStartYear shouldBe Some(2018)
      }
    }

    "the pensionDate is 6th April 2020" should {
      "be 2019" in {
        StatePensionExclusion(List(Exclusion.AmountDissonance), Some(67), Some(new LocalDate(2020, 4, 6))).finalRelevantStartYear shouldBe Some(2019)
      }
    }

    "the pensionDate is 6th April 2000" should {
      "be 1999" in {
        StatePensionExclusion(List(Exclusion.AmountDissonance, Exclusion.PostStatePensionAge), Some(65), Some(new LocalDate(2000, 4, 6))).finalRelevantStartYear shouldBe Some(1999)
      }
    }

    "the pensionDate is 5th April 2020 and there is no flag for state pension age under consideration" should {
      "be 2018" in {
        StatePensionExclusion(List(Exclusion.AmountDissonance), Some(67), Some(new LocalDate(2020, 4, 5))).finalRelevantStartYear shouldBe Some(2018)
      }
    }

    "the pensionDate is 5th April 2020 and there is a true flag for state pension age under consideration" should {
      "be 2018" in {
        StatePensionExclusion(List(Exclusion.AmountDissonance), Some(67), Some(new LocalDate(2020, 4, 5)), Some(true)).finalRelevantStartYear shouldBe Some(2018)
      }
    }

    "the pensionDate is 5th April 2020 and there is a false flag for state pension age under consideration" should {
      "be 2018" in {
        StatePensionExclusion(List(Exclusion.AmountDissonance), Some(67), Some(new LocalDate(2020, 4, 5)), Some(false)).finalRelevantStartYear shouldBe Some(2018)
      }
    }


  }

} 
Example 47
Source File: CitizenDetailsResponseSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import play.api.libs.json.Json
import uk.gov.hmrc.nisp.helpers.TestAccountBuilder
import uk.gov.hmrc.nisp.models.citizen.{Address, Citizen, CitizenDetailsResponse}
import uk.gov.hmrc.play.test.UnitSpec


class CitizenDetailsResponseSpec extends UnitSpec {
    "Citizen" should {

      val nino = TestAccountBuilder.regularNino
      val citizenDetailsResponse = CitizenDetailsResponse(
        Citizen(
          nino,
          Some("AHMED"),
          Some("BRENNAN"),
          new LocalDate(1954, 3, 9)
        ),
        Some(Address(
          country = Some("USA")
        ))
      )

      "parse correctly when date of birth is a date" in {
        Json.parse(
          s"""
            |{
            |  "etag":"1",
            |  "person":{
            |    "sex":"M",
            |    "dateOfBirth":-499132800000,
            |    "nino":"$nino",
            |    "firstName":"AHMED",
            |    "middleName":"",
            |    "lastName":"BRENNAN",
            |    "title":"Mrs",
            |    "honours":null
            |  },
            |  "address":{
            |    "line1":"108 SAI ROAD",
            |    "line2":"",
            |    "line3":"",
            |    "line4":null,
            |    "postcode":"12345",
            |    "country":"USA",
            |    "startDate":1223510400000,
            |    "type":"Residential"
            |  }
            |}
          """.stripMargin
        ).as[CitizenDetailsResponse] shouldBe citizenDetailsResponse
      }

      "parse correctly when date of birth is a long" in {
        Json.parse(
          s"""
             |{
             |  "etag":"1",
             |  "person":{
             |    "sex":"M",
             |    "dateOfBirth":"1954-03-09",
             |    "nino":"$nino",
             |    "firstName":"AHMED",
             |    "middleName":"",
             |    "lastName":"BRENNAN",
             |    "title":"Mrs",
             |    "honours":null
             |  },
             |  "address":{
             |    "line1":"108 SAI ROAD",
             |    "line2":"",
             |    "line3":"",
             |    "line4":null,
             |    "postcode":"12345",
             |    "country":"USA",
             |    "startDate":1223510400000,
             |    "type":"Residential"
             |  }
             |}
          """.stripMargin
        ).as[CitizenDetailsResponse] shouldBe citizenDetailsResponse
      }
    }
} 
Example 48
Source File: NpsDateSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.models

import org.joda.time.LocalDate
import play.api.libs.json.{JsNull, JsString, Json}
import uk.gov.hmrc.nisp.utils.Constants
import uk.gov.hmrc.play.test.UnitSpec

class NpsDateSpec extends UnitSpec {
  "NpsDate" when {
    "JSON parsing" should {
      "return a JSError for null date" in {
        JsNull.validate[NpsDate].isError shouldBe true
      }
    }

    "JSON serialisation" should {
      "return JSString in correct format" in {
        Json.toJson(NpsDate(new LocalDate(2015,1,1))) shouldBe JsString("01/01/2015")
      }
      "deserialise works" in {
        Json.fromJson[NpsDate](JsString("01/01/2015")).get shouldBe NpsDate(new LocalDate(2015,1,1))
      }
    }

    "taxYearEndDate" should {
      "return tax year end date" in {
        NpsDate.taxYearEndDate(2015) shouldBe NpsDate(2016, Constants.taxYearsStartEndMonth, Constants.taxYearEndDay)
      }
    }

    "taxYearStartDate" should {
      "return tax year start date" in {
        NpsDate.taxYearStartDate(2015) shouldBe NpsDate(2015, Constants.taxYearsStartEndMonth, Constants.taxYearStartDay)
      }
    }
  }
} 
Example 49
Source File: CitizenDetailsServiceSpec.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.services

import org.joda.time.LocalDate
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.OneAppPerSuite
import uk.gov.hmrc.domain.Nino
import uk.gov.hmrc.http.{HeaderCarrier, Upstream5xxResponse}
import uk.gov.hmrc.nisp.helpers.{MockCitizenDetailsService, TestAccountBuilder}
import uk.gov.hmrc.nisp.models.citizen.{Address, Citizen, CitizenDetailsError, CitizenDetailsResponse}
import uk.gov.hmrc.play.test.UnitSpec

import scala.concurrent.Future

class CitizenDetailsServiceSpec extends UnitSpec with MockitoSugar with BeforeAndAfter with ScalaFutures with OneAppPerSuite {
  val nino: Nino = TestAccountBuilder.regularNino
  val noNameNino: Nino = TestAccountBuilder.noNameNino
  val nonExistentNino: Nino = TestAccountBuilder.nonExistentNino
  val badRequestNino: Nino = TestAccountBuilder.blankNino

  "CitizenDetailsService" should {
    "return something for valid NINO" in {
      val person: Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = MockCitizenDetailsService.retrievePerson(nino)(new HeaderCarrier())
      whenReady(person) {p =>
        p.isRight shouldBe true
      }
    }

    "return None for bad NINO" in {
      val person: Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = MockCitizenDetailsService.retrievePerson(nonExistentNino)(new HeaderCarrier())
      whenReady(person) {p =>
        p.isLeft shouldBe true
      }
    }

    "return None for bad request" in {
      val person: Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = MockCitizenDetailsService.retrievePerson(badRequestNino)(new HeaderCarrier())
      whenReady(person) {p =>
        p.isLeft shouldBe true
      }
    }

    "return a Failed Future for a 5XX error" in {
      val person: Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = MockCitizenDetailsService.retrievePerson(TestAccountBuilder.internalServerError)(new HeaderCarrier())
      whenReady(person.failed) { ex =>
        ex shouldBe a [Upstream5xxResponse]
      }
    }

    "return correct name and Date of Birth for NINO" in {
      val person: Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = MockCitizenDetailsService.retrievePerson(nino)(new HeaderCarrier())
      whenReady(person) {p =>
        p.right.map(_.person.copy(nino = nino)) shouldBe Right(Citizen(nino, Some("AHMED"), Some("BRENNAN"), new LocalDate(1954, 3, 9)))
        p.right.get.person.getNameFormatted shouldBe Some("AHMED BRENNAN")
      }
    }

    "return formatted name of None if Citizen returns without a name" in {
      val person: Future[Either[CitizenDetailsError, CitizenDetailsResponse]] = MockCitizenDetailsService.retrievePerson(noNameNino)(new HeaderCarrier())
      whenReady(person) {p =>
        p shouldBe Right(CitizenDetailsResponse(Citizen(noNameNino, None, None, new LocalDate(1954, 3, 9)), Some(Address(Some("GREAT BRITAIN")))))
        p.right.get.person.getNameFormatted shouldBe None
      }
    }
  }
} 
Example 50
Source File: NationalInsuranceTaxYearBuilder.scala    From nisp-frontend   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.nisp.builders

import org.joda.time.LocalDate
import uk.gov.hmrc.nisp.models.NationalInsuranceTaxYear


object NationalInsuranceTaxYearBuilder {
  def apply(taxYear: String, qualifying: Boolean = true, payable: Boolean = false ,underInvestigation :Boolean): NationalInsuranceTaxYear = {
    if(qualifying) {
      NationalInsuranceTaxYear(
        taxYear,
        true,
        classOneContributions = 12345.67,
        classTwoCredits = 10,
        classThreeCredits = 8,
        otherCredits = 12,
        0,
        None,
        None,
        false,
        underInvestigation = underInvestigation
      )
    } else {
      NationalInsuranceTaxYear(
        taxYear,
        false,
        classOneContributions = 1,
        classTwoCredits = 1,
        classThreeCredits = 1,
        otherCredits = 1,
        classThreePayable = 755.56,
        classThreePayableBy = Some( new LocalDate(2019, 4, 5)),
        classThreePayableByPenalty = Some( new LocalDate(2023, 4, 5)),
        payable = payable,
        underInvestigation = underInvestigation
      )
    }
  }
} 
Example 51
Source File: DictionaryFunctions.scala    From clickhouse-scala-client   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.crobox.clickhouse.dsl.column

import java.util.UUID

import com.crobox.clickhouse.dsl._
import org.joda.time.{DateTime, LocalDate}

trait DictionaryFunctions { self: Magnets =>

  sealed abstract class DictionaryGetFuncColumn[V](val dictName: StringColMagnet[_], val attrName: StringColMagnet[_], val id: ConstOrColMagnet[_], val default: Option[Magnet[V]] = None) extends
    DictionaryFuncColumn[V]

  sealed abstract class DictionaryFuncColumn[V] extends
    ExpressionColumn[V](EmptyColumn)

  case class DictGetUInt8(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetUInt16(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetUInt32(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetUInt64(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetInt8(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetInt16(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetInt32(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetInt64(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Long]] = None)
    extends DictionaryGetFuncColumn[Long](_dictName,_attrName,_id,_default)
  case class DictGetFloat32(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Float]] = None)
    extends DictionaryGetFuncColumn[Float](_dictName,_attrName,_id,_default)
  case class DictGetFloat64(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[Float]] = None)
    extends DictionaryGetFuncColumn[Float](_dictName,_attrName,_id,_default)
  case class DictGetDate(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[LocalDate]] = None)
    extends DictionaryGetFuncColumn[LocalDate](_dictName,_attrName,_id,_default)
  case class DictGetDateTime(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[DateTime]] = None)
    extends DictionaryGetFuncColumn[DateTime](_dictName,_attrName,_id,_default)
  case class DictGetUUID(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[UUID]] = None)
    extends DictionaryGetFuncColumn[UUID](_dictName,_attrName,_id,_default)
  case class DictGetString(_dictName: StringColMagnet[_], _attrName: StringColMagnet[_], _id: ConstOrColMagnet[_], _default: Option[Magnet[String]] = None)
    extends DictionaryGetFuncColumn[String](_dictName,_attrName,_id,_default)

  case class DictIsIn(dictName: StringColMagnet[_], childId: ConstOrColMagnet[_], ancestorId: ConstOrColMagnet[_]) extends DictionaryFuncColumn[Boolean]
  case class DictGetHierarchy(dictName: StringColMagnet[_], id: ConstOrColMagnet[_]) extends DictionaryFuncColumn[String]
  case class DictHas(dictName: StringColMagnet[_], id: ConstOrColMagnet[_]) extends DictionaryFuncColumn[Boolean]

  def dictGetUInt8 (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetUInt8(dictName, attrName, id)
  def dictGetUInt16(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetUInt16(dictName, attrName, id)
  def dictGetUInt32(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetUInt32(dictName, attrName, id)
  def dictGetUInt64(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetUInt64(dictName, attrName, id)
  def dictGetInt8  (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetInt8(dictName, attrName, id)
  def dictGetInt16 (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetInt16(dictName, attrName, id)
  def dictGetInt32 (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetInt32(dictName, attrName, id)
  def dictGetInt64 (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetInt64(dictName, attrName, id)
  def dictGetFloat32(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetFloat32(dictName, attrName, id)
  def dictGetFloat64(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetFloat64(dictName, attrName, id)
  def dictGetDate  (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetDate(dictName, attrName, id)
  def dictGetDateTime(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetDateTime(dictName, attrName, id)
  def dictGetUUID  (dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetUUID(dictName, attrName, id)
  def dictGetString(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetString(dictName, attrName, id)
  def dictIsIn     (dictName: StringColMagnet[_], childId: ConstOrColMagnet[_], id: ConstOrColMagnet[_]) = DictIsIn(dictName, childId, id)
  def dictGetHierarchy(dictName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictGetHierarchy(dictName, id)
  def dictHas      (dictName: StringColMagnet[_], id: ConstOrColMagnet[_]) = DictHas(dictName, id)

  def dictGetUInt8OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =    DictGetUInt8(dictName, attrName, id, Some(default))
  def dictGetUInt16OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =   DictGetUInt16(dictName, attrName, id, Some(default))
  def dictGetUInt32OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =   DictGetUInt32(dictName, attrName, id, Some(default))
  def dictGetUInt64OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =   DictGetUInt64(dictName, attrName, id, Some(default))
  def dictGetInt8OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =     DictGetInt8(dictName, attrName, id, Some(default))
  def dictGetInt16OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =    DictGetInt16(dictName, attrName, id, Some(default))
  def dictGetInt32OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =    DictGetInt32(dictName, attrName, id, Some(default))
  def dictGetInt64OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Long]) =    DictGetInt64(dictName, attrName, id, Some(default))
  def dictGetFloat32OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Float]) =  DictGetFloat32(dictName, attrName, id, Some(default))
  def dictGetFloat64OrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[Float]) =  DictGetFloat64(dictName, attrName, id, Some(default))
  def dictGetDateOrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[LocalDate]) =     DictGetDate(dictName, attrName, id, Some(default))
  def dictGetDateTimeOrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[DateTime]) = DictGetDateTime(dictName, attrName, id, Some(default))
  def dictGetUUIDOrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[UUID]) =      DictGetUUID(dictName, attrName, id, Some(default))
  def dictGetStringOrDefault(dictName: StringColMagnet[_], attrName: StringColMagnet[_], id: ConstOrColMagnet[_], default: Magnet[String]) =   DictGetString(dictName, attrName, id, Some(default))
} 
Example 52
Source File: DateTimeFunctions.scala    From clickhouse-scala-client   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.crobox.clickhouse.dsl.column

import com.crobox.clickhouse.dsl._
import org.joda.time.{DateTime, LocalDate}

trait DateTimeFunctions { self: Magnets =>
  sealed trait DateTimeFunction

  abstract class DateTimeFunctionCol[V](val ddt: DateOrDateTime[_])
      extends ExpressionColumn(ddt.column)
      with DateTimeFunction

  abstract class DateTimeConst[V]()                                    extends ExpressionColumn[V](EmptyColumn) with DateTimeFunction
  case class Year(d: DateOrDateTime[_])                                extends DateTimeFunctionCol[Int](d)
  case class YYYYMM(d: DateOrDateTime[_])                              extends DateTimeFunctionCol[String](d)
  case class Month(d: DateOrDateTime[_])                               extends DateTimeFunctionCol[Int](d)
  case class DayOfMonth(d: DateOrDateTime[_])                          extends DateTimeFunctionCol[Int](d)
  case class DayOfWeek(d: DateOrDateTime[_])                           extends DateTimeFunctionCol[Int](d)
  case class Hour(d: DateOrDateTime[_])                                extends DateTimeFunctionCol[Int](d)
  case class Minute(d: DateOrDateTime[_])                              extends DateTimeFunctionCol[Int](d)
  case class Second(d: DateOrDateTime[_])                              extends DateTimeFunctionCol[Int](d)
  case class Monday[V](d: DateOrDateTime[_])                           extends DateTimeFunctionCol[V](d)
  case class AddSeconds(d: DateOrDateTime[_], seconds: NumericCol[_])  extends DateTimeFunctionCol[DateTime](d)
  case class AddMinutes(d: DateOrDateTime[_], minutes: NumericCol[_])  extends DateTimeFunctionCol[DateTime](d)
  case class AddHours(d: DateOrDateTime[_], hours: NumericCol[_])      extends DateTimeFunctionCol[DateTime](d)
  case class AddDays[V](d: DateOrDateTime[V], days: NumericCol[_])     extends DateTimeFunctionCol[V](d)
  case class AddWeeks[V](d: DateOrDateTime[V], weeks: NumericCol[_])   extends DateTimeFunctionCol[V](d)
  case class AddMonths[V](d: DateOrDateTime[V], months: NumericCol[_]) extends DateTimeFunctionCol[V](d)
  case class AddYears[V](d: DateOrDateTime[V], years: NumericCol[_])   extends DateTimeFunctionCol[V](d)
  case class StartOfMonth[V](d: DateOrDateTime[_])                     extends DateTimeFunctionCol[V](d)
  case class StartOfQuarter[V](d: DateOrDateTime[_])                   extends DateTimeFunctionCol[V](d)
  case class StartOfYear[V](d: DateOrDateTime[_])                      extends DateTimeFunctionCol[V](d)
  case class StartOfMinute[V](d: DateOrDateTime[_])                    extends DateTimeFunctionCol[V](d)
  case class StartOfFiveMinute[V](d: DateOrDateTime[_])                extends DateTimeFunctionCol[V](d)
  case class StartOfFifteenMinutes[V](d: DateOrDateTime[_])            extends DateTimeFunctionCol[V](d)
  case class StartOfHour[V](d: DateOrDateTime[_])                      extends DateTimeFunctionCol[V](d)
  case class StartOfDay[V](d: DateOrDateTime[_])                       extends DateTimeFunctionCol[V](d)
  case class Time(d: DateOrDateTime[_])                                extends DateTimeFunctionCol[DateTime](d)
  case class RelativeYearNum[V](d: DateOrDateTime[_])                  extends DateTimeFunctionCol[V](d)
  case class RelativeQuarterNum[V](d: DateOrDateTime[_])               extends DateTimeFunctionCol[V](d)
  case class RelativeMonthNum[V](d: DateOrDateTime[_])                 extends DateTimeFunctionCol[V](d)
  case class RelativeWeekNum[V](d: DateOrDateTime[_])                  extends DateTimeFunctionCol[V](d)
  case class RelativeDayNum[V](d: DateOrDateTime[_])                   extends DateTimeFunctionCol[V](d)
  case class RelativeHourNum[V](d: DateOrDateTime[_])                  extends DateTimeFunctionCol[V](d)
  case class RelativeMinuteNum[V](d: DateOrDateTime[_])                extends DateTimeFunctionCol[V](d)
  case class RelativeSecondNum[V](d: DateOrDateTime[_])                extends DateTimeFunctionCol[V](d)
  case class Now()                                                     extends DateTimeConst[DateTime]()
  case class Today()                                                   extends DateTimeConst[LocalDate]()
  case class Yesterday()                                               extends DateTimeConst[LocalDate]()
  case class TimeSlot(d: DateOrDateTime[_])                            extends DateTimeFunctionCol[DateTime](d)
  case class TimeSlots(d: DateOrDateTime[_], duration: NumericCol[_])  extends DateTimeFunctionCol[DateTime](d)
  case class ISOYear(d: DateOrDateTime[_])                             extends DateTimeFunctionCol[Int](d)
  case class ISOWeek(d: DateOrDateTime[_])                             extends DateTimeFunctionCol[Int](d)
  case class Week(d: DateOrDateTime[_], mode: Int)                     extends DateTimeFunctionCol[Int](d)

  def toYear(col: DateOrDateTime[_])                              = Year(col)
  def toYYYYMM(col: DateOrDateTime[_])                            = YYYYMM(col)
  def toMonth(col: DateOrDateTime[_])                             = Month(col)
  def toDayOfMonth(col: DateOrDateTime[_])                        = DayOfMonth(col)
  def toDayOfWeek(col: DateOrDateTime[_])                         = DayOfWeek(col)
  def toHour(col: DateOrDateTime[_])                              = Hour(col)
  def toMinute(col: DateOrDateTime[_])                            = Minute(col)
  def toSecond(col: DateOrDateTime[_])                            = Second(col)
  def toMonday[T](col: DateOrDateTime[T])                         = Monday[T](col)
  def addSeconds(col: DateOrDateTime[_], seconds: NumericCol[_])  = AddSeconds(col, seconds)
  def addMinutes(col: DateOrDateTime[_], minutes: NumericCol[_])  = AddMinutes(col, minutes)
  def addHours(col: DateOrDateTime[_], hours: NumericCol[_])      = AddHours(col, hours)
  def addDays[T](col: DateOrDateTime[T], days: NumericCol[_])     = AddDays[T](col, days)
  def addWeeks[T](col: DateOrDateTime[T], weeks: NumericCol[_])   = AddWeeks[T](col, weeks)
  def addMonths[T](col: DateOrDateTime[T], months: NumericCol[_]) = AddMonths[T](col, months)
  def addYears[T](col: DateOrDateTime[T], years: NumericCol[_])   = AddYears[T](col, years)
  def toStartOfMonth[T](col: DateOrDateTime[T])                   = StartOfMonth[T](col)
  def toStartOfQuarter[T](col: DateOrDateTime[T])                 = StartOfQuarter[T](col)
  def toStartOfYear[T](col: DateOrDateTime[T])                    = StartOfYear[T](col)
  def toStartOfMinute[T](col: DateOrDateTime[T])                  = StartOfMinute[T](col)
  def toStartOfFiveMinute[T](col: DateOrDateTime[T])              = StartOfFiveMinute[T](col)
  def toStartOfFifteenMinutes[T](col: DateOrDateTime[T])          = StartOfFifteenMinutes[T](col)
  def toStartOfHour[T](col: DateOrDateTime[T])                    = StartOfHour[T](col)
  def toStartOfDay[T](col: DateOrDateTime[T])                     = StartOfDay[T](col)
  def toTime(col: DateOrDateTime[_])                              = Time(col)
  def toRelativeYearNum[T](col: DateOrDateTime[T])                = RelativeYearNum[T](col)
  def toRelativeQuarterNum[T](col: DateOrDateTime[T])             = RelativeQuarterNum[T](col)
  def toRelativeMonthNum[T](col: DateOrDateTime[T])               = RelativeMonthNum[T](col)
  def toRelativeWeekNum[T](col: DateOrDateTime[T])                = RelativeWeekNum[T](col)
  def toRelativeDayNum[T](col: DateOrDateTime[T])                 = RelativeDayNum[T](col)
  def toRelativeHourNum[T](col: DateOrDateTime[T])                = RelativeHourNum[T](col)
  def toRelativeMinuteNum[T](col: DateOrDateTime[T])              = RelativeMinuteNum[T](col)
  def toRelativeSecondNum[T](col: DateOrDateTime[T])              = RelativeSecondNum[T](col)
  def chNow()                                                     = Now()
  def chYesterday()                                               = Yesterday()
  def chToday()                                                   = Today()
  def timeSlot(col: DateOrDateTime[_])                            = TimeSlot(col)
  def timeSlots(col: DateOrDateTime[_], duration: NumericCol[_])  = TimeSlots(col, duration)
  def toISOWeek(col: DateOrDateTime[_])                           = ISOWeek(col)
  def toISOYear(col: DateOrDateTime[_])                           = ISOYear(col)
  def toWeek(col: DateOrDateTime[_], mode: Int = 0)               = Week(col, mode)
} 
Example 53
Source File: IdentityData.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.nrs.request

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json.{Format, Json, OFormat}
import uk.gov.hmrc.auth.core.retrieve._
import uk.gov.hmrc.auth.core.{AffinityGroup, ConfidenceLevel, CredentialRole}
import utils.DateUtils

case class IdentityData(internalId: Option[String] = None,
                        externalId: Option[String] = None,
                        agentCode: Option[String] = None,
                        credentials: Option[Credentials] = None,
                        confidenceLevel: ConfidenceLevel,
                        nino: Option[String] = None,
                        saUtr: Option[String] = None,
                        name: Option[Name] = None,
                        dateOfBirth: Option[LocalDate] = None,
                        email: Option[String] = None,
                        agentInformation: AgentInformation,
                        groupIdentifier: Option[String] = None,
                        credentialRole: Option[CredentialRole],
                        mdtpInformation: Option[MdtpInformation] = None,
                        itmpName: ItmpName,
                        itmpDateOfBirth: Option[LocalDate] = None,
                        itmpAddress: ItmpAddress,
                        affinityGroup: Option[AffinityGroup],
                        credentialStrength: Option[String] = None,
                        loginTimes: LoginTimes)

object IdentityData {
  implicit val localDateFormats: Format[LocalDate] = DateUtils.dateFormat
  implicit val credFormat: OFormat[Credentials] = Json.format[Credentials]
  implicit val nameFormat: OFormat[Name] = Json.format[Name]
  implicit val agentInfoFormat: OFormat[AgentInformation] = Json.format[AgentInformation]
  implicit val mdtpInfoFormat: OFormat[MdtpInformation] = Json.format[MdtpInformation]
  implicit val itmpNameFormat: OFormat[ItmpName] = Json.format[ItmpName]
  implicit val itmpAddressFormat: OFormat[ItmpAddress] = Json.format[ItmpAddress]
  implicit val dateTimeFormats: Format[DateTime] = DateUtils.isoInstantDateFormat
  implicit val loginTimesFormat: OFormat[LoginTimes] = Json.format[LoginTimes]
  implicit val format: OFormat[IdentityData] = Json.format[IdentityData]
} 
Example 54
Source File: DateUtils.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package utils

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json.{Format, JodaReads, JodaWrites}

object DateUtils {

  val isoInstantDatePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"
  val isoInstantDateRegex = """(\d){4}-(\d){2}-(\d){2}T(\d){2}:(\d){2}:(\d){2}Z"""
  val dateTimePattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  val datePattern = "yyyy-MM-dd"

  val dateTimeFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(dateTimePattern),
    JodaWrites.jodaDateWrites(dateTimePattern)
  )

  val isoInstantDateFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(isoInstantDatePattern),
    JodaWrites.jodaDateWrites(isoInstantDatePattern)
  )

  val defaultDateTimeFormat: Format[DateTime] = Format[DateTime](
    JodaReads.jodaDateReads(isoInstantDatePattern),
    JodaWrites.jodaDateWrites(dateTimePattern)
  )

  val dateFormat: Format[LocalDate] = Format[LocalDate](
    JodaReads.jodaLocalDateReads(datePattern),
    JodaWrites.jodaLocalDateWrites(datePattern)
  )
} 
Example 55
Source File: Binders.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.resources

import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import play.api.mvc.{PathBindable, QueryStringBindable}
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.vatapi.models.{FinancialDataQueryParams, ObligationsQueryParams, OptEither}

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

object Binders {

  implicit def vrnBinder(implicit stringBinder: PathBindable[String]) = new PathBindable[Vrn] {
    val vrnRegex = """^\d{9}$"""

    def unbind(key: String, vrn: Vrn): String = stringBinder.unbind(key, vrn.value)

    def bind(key: String, value: String): Either[String, Vrn] = {
      if (value.matches(vrnRegex)) {
        Right(Vrn(value))
      } else {
        Left("ERROR_VRN_INVALID")
      }
    }
  }

  implicit def obligationsQueryParamsBinder(implicit stringBinder: QueryStringBindable[String]) = new QueryStringBindable[ObligationsQueryParams] {

    override def bind(key: String, params: Map[String, Seq[String]]): OptEither[ObligationsQueryParams] = {
      val from = stringBinder.bind("from", params)
      val to = stringBinder.bind("to", params)
      val status = stringBinder.bind("status", params)

      val query = ObligationsQueryParams.from(from, to, status)
      if (query.isRight)
        Some(Right(query.right.get))
      else
        Some(Left(query.left.get))
    }

    override def unbind(key: String, value: ObligationsQueryParams): String = stringBinder.unbind(key, value.map(key).toString)

  }

  implicit def financialDataQueryParamsBinder(implicit stringBinder: QueryStringBindable[String]) = new QueryStringBindable[FinancialDataQueryParams] {
    override def bind(key: String, params: Map[String, Seq[String]]): OptEither[FinancialDataQueryParams] = {
      val from = stringBinder.bind("from", params)
      val to = stringBinder.bind("to", params)

      val query = FinancialDataQueryParams.from(from, to)
      if (query.isRight)
        Some(Right(query.right.get))
      else
        Some(Left(query.left.get))
    }

    override def unbind(key: String, value: FinancialDataQueryParams): String = stringBinder.unbind(key, value.map(key).toString)
  }

  val format: String = "yyy-MM-dd"

  implicit val dateQueryParamsBinder = new QueryStringBindable[LocalDate] {

    override def unbind(key: String, date: LocalDate): String = date.toString

    override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, LocalDate]] =
      for {
        dates <- params.get(key)
      } yield
        Try {
          DateTimeFormat.forPattern(format).parseLocalDate(dates(0))
        } match {
          case Success(v) => Right(v)
          case Failure(_) => Left("ERROR_INVALID_DATE")
        }

  }
}