play.api.libs.json.JsNull Scala Examples

The following examples show how to use play.api.libs.json.JsNull. 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: 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 2
Source File: Migration.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.models

import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success

import play.api.Logger
import play.api.libs.json.{JsNull, JsNumber, JsString, JsValue, Json}

import org.thp.cortex.services.{OrganizationSrv, UserSrv, WorkerSrv}

import org.elastic4play.controllers.Fields
import org.elastic4play.services.Operation._
import org.elastic4play.services.{DatabaseState, IndexType, MigrationOperations, Operation}
import org.elastic4play.utils.Hasher

@Singleton
class Migration @Inject()(userSrv: UserSrv, organizationSrv: OrganizationSrv, workerSrv: WorkerSrv, implicit val ec: ExecutionContext)
    extends MigrationOperations {

  lazy val logger                                = Logger(getClass)
  def beginMigration(version: Int): Future[Unit] = Future.successful(())

  def endMigration(version: Int): Future[Unit] =
    userSrv.inInitAuthContext { implicit authContext ⇒
      organizationSrv
        .create(Fields(Json.obj("name" → "cortex", "description" → "Default organization", "status" → "Active")))
        .transform(_ ⇒ Success(())) // ignore errors (already exist)
    }

  override def indexType(version: Int): IndexType.Value = if (version > 3) IndexType.indexWithoutMappingTypes else IndexType.indexWithMappingTypes

  val operations: PartialFunction[DatabaseState, Seq[Operation]] = {
    case DatabaseState(1) ⇒
      val hasher = Hasher("MD5")
      Seq(
        // add type to analyzer
        addAttribute("analyzer", "type" → JsString("analyzer")),
        renameAttribute("job", "workerDefinitionId", "analyzerDefinitionId"),
        renameAttribute("job", "workerId", "analyzerId"),
        renameAttribute("job", "workerName", "analyzerName"),
        addAttribute("job", "type"          → JsString(WorkerType.analyzer.toString)),
        addAttribute("report", "operations" → JsString("[]")),
        renameEntity("analyzer", "worker"),
        renameAttribute("worker", "workerDefinitionId", "analyzerDefinitionId"),
        addAttribute("worker", "type" → JsString(WorkerType.analyzer.toString)),
        mapEntity("worker") { worker ⇒
          val id = for {
            organizationId ← (worker \ "_parent").asOpt[String]
            name           ← (worker \ "name").asOpt[String]
            tpe            ← (worker \ "type").asOpt[String]
          } yield hasher.fromString(s"${organizationId}_${name}_$tpe").head.toString
          worker + ("_id" → JsString(id.getOrElse("<null>")))
        },
        renameEntity("analyzerConfig", "workerConfig"),
        addAttribute("workerConfig", "type" → JsString(WorkerType.analyzer.toString))
      )

    case DatabaseState(2) ⇒
      Seq(mapEntity("worker") { worker ⇒
        val definitionId = (worker \ "workerDefinitionId").asOpt[String]
        definitionId
          .flatMap(workerSrv.getDefinition(_).toOption)
          .fold {
            logger.warn(s"no definition found for worker ${definitionId.getOrElse(worker)}. You should probably have to disable and re-enable it")
            worker
          } { definition ⇒
            worker +
              ("version"     → JsString(definition.version)) +
              ("author"      → JsString(definition.author)) +
              ("url"         → JsString(definition.url)) +
              ("license"     → JsString(definition.license)) +
              ("command"     → definition.command.fold[JsValue](JsNull)(c ⇒ JsString(c.toString))) +
              ("dockerImage" → definition.dockerImage.fold[JsValue](JsNull)(JsString.apply)) +
              ("baseConfig"  → definition.baseConfiguration.fold[JsValue](JsNull)(JsString.apply))
          }
      })

    case DatabaseState(3) ⇒
      Seq(
        mapEntity("sequence") { seq ⇒
          val oldId   = (seq \ "_id").as[String]
          val counter = (seq \ "counter").as[JsNumber]
          seq - "counter" - "_routing" +
            ("_id"             → JsString("sequence_" + oldId)) +
            ("sequenceCounter" → counter)
        }
      )
  }
} 
Example 3
Source File: CrystallisationResource.scala    From self-assessment-api   with Apache License 2.0 5 votes vote down vote up
package router.resources

import javax.inject.Inject
import play.api.libs.json.{JsNull, JsValue}
import play.api.mvc.{Action, AnyContent, BodyParser, ControllerComponents}
import router.constants.Versions
import router.constants.Versions._
import router.services.{CrystallisationService, Service}
import uk.gov.hmrc.auth.core.AuthConnector
import scala.concurrent.ExecutionContext.Implicits.global

class CrystallisationResource @Inject()(service: CrystallisationService,
                                        val cc: ControllerComponents,
                                        val authConnector: AuthConnector) extends BaseResource(cc, authConnector) with Service {

  def post(param: Any*): Action[JsValue] = AuthAction.async(parse.json) {
    implicit request =>
      withJsonBody[JsValue] {
        service.post(_).map {
          case Left(error) => buildErrorResponse(error)
          case Right(apiResponse) => buildResponse(apiResponse)
        }
      }
  }

  // Note that intent V1 requires empty JSON (i.e. {}) whereas V2 requires completely empty body. So we need to parse
  // accordingly these with the empty body parsed to JsNull
  private val jsonOrEmptyParser: BodyParser[JsValue] = parse.using { request =>

    if (Versions.getFromRequest(request).contains(VERSION_1))
      parse.json
    else
      parse.empty.map(_ => JsNull)
  }

  def intent(param: Any*): Action[JsValue] = AuthAction.async(jsonOrEmptyParser) { implicit request =>
    withJsonBody[JsValue] { body =>
      val serviceOutcome = body match {
        case JsNull => service.postEmpty
        case json => service.post(json)
      }

      serviceOutcome.map {
        case Left(error) => buildErrorResponse(error)
        case Right(apiResponse) => buildResponse(apiResponse)
      }
    }
  }

  def get(param: Any*): Action[AnyContent] = {
    AuthAction.async {
      implicit request =>
        service.get().map{
          case Left(error) => buildErrorResponse(error)
          case Right(apiResponse) => buildResponse(apiResponse)
        }
    }
  }
} 
Example 4
Source File: HttpReadsLegacyInstances.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.http

import com.github.ghik.silencer.silent
import play.api.libs.json
import play.api.libs.json.{JsNull, JsValue}


trait HttpReadsLegacyInstances extends HttpReadsLegacyOption with HttpReadsLegacyJson

trait HttpReadsLegacyRawReads extends HttpErrorFunctions {
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  implicit val readRaw: HttpReads[HttpResponse] = new HttpReads[HttpResponse] {
    @silent("deprecated")
    def read(method: String, url: String, response: HttpResponse) = handleResponse(method, url)(response)
  }
}

object HttpReadsLegacyRawReads extends HttpReadsLegacyRawReads

trait HttpReadsLegacyOption extends HttpErrorFunctions {
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  implicit def readOptionOf[P](implicit rds: HttpReads[P]): HttpReads[Option[P]] = new HttpReads[Option[P]] {
    def read(method: String, url: String, response: HttpResponse) = response.status match {
      case 204 | 404 => None
      case _         => Some(rds.read(method, url, response))
    }
  }
}

trait HttpReadsLegacyJson extends HttpErrorFunctions {
  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  implicit def readFromJson[O](implicit rds: json.Reads[O], mf: Manifest[O]): HttpReads[O] = new HttpReads[O] {
    def read(method: String, url: String, response: HttpResponse) =
      readJson(method, url, handleResponse(method, url)(response).json)
  }

  @deprecated("Use uk.gov.hmrc.http.HttpReads.Implicits instead. See README for differences.", "11.0.0")
  def readSeqFromJsonProperty[O](name: String)(implicit rds: json.Reads[O], mf: Manifest[O]) = new HttpReads[Seq[O]] {
    def read(method: String, url: String, response: HttpResponse) = response.status match {
      case 204 | 404 => Seq.empty
      case _ =>
        readJson[Seq[O]](method, url, (handleResponse(method, url)(response).json \ name).getOrElse(JsNull)) //Added JsNull here to force validate to fail - replicates existing behaviour
    }
  }

  private def readJson[A](method: String, url: String, jsValue: JsValue)(implicit rds: json.Reads[A], mf: Manifest[A]) =
    jsValue
      .validate[A]
      .fold(
        errs => throw new JsValidationException(method, url, mf.runtimeClass, errs.toString()),
        valid => valid
      )
} 
Example 5
Source File: JSONBuilder.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.util;

import mimir.algebra.{PrimitiveValue,StringPrimitive,TypePrimitive};
import play.api.libs.json.JsString
import play.api.libs.json.JsArray
import play.api.libs.json.JsObject
import play.api.libs.json.JsValue
import play.api.libs.json.JsNumber
import play.api.libs.json.JsNull
import play.api.libs.json.JsBoolean
import mimir.algebra.NullPrimitive
import mimir.algebra.RowIdPrimitive
import mimir.algebra.IntPrimitive
import mimir.algebra.FloatPrimitive
import mimir.algebra.BoolPrimitive
import mimir.algebra.TimestampPrimitive
import mimir.algebra.DatePrimitive


object JSONBuilder {
	
	def list(content: Seq[Any]): String =
		listJs(content).toString()

  private def listJs(content: Seq[Any]): JsArray =
		JsArray(content.map { el => value(el) })
		
	def dict(content: Map[String,Any]): String =
		dictJs(content).toString()

	def dict(content: Seq[(String,Any)]): String =
		JsObject(content.map( (x) => x._1.toLowerCase() -> value(x._2))).toString()

  private def dictJs(content: Map[String,Any]): JsObject =
		JsObject(content.map { el => el._1 -> value(el._2) } )
		
	def string(content: String): String = {
		value(content).toString()
	}

	def int(content: Int): String = {
		value(content).toString()
	}

	def double(content: Double): String = {
		value(content).toString()
	}
	
	def boolean(content: Boolean): String = {
		value(content).toString()
	}

	def prim(content: PrimitiveValue) = {
		primJs(content).toString()
	}
	
	private def primJs(content: PrimitiveValue) = {
		content match {
			case StringPrimitive(s) => JsString(s)
			case TypePrimitive(t) => JsString(t.toString())
			case NullPrimitive() => JsNull
      case RowIdPrimitive(s) => JsString(s)
      case IntPrimitive(i) => JsNumber(i)
      case FloatPrimitive(f) => JsNumber(f)
      case BoolPrimitive(b) => JsBoolean(b)
      case TimestampPrimitive(_,_,_,_,_,_,_) => JsString(content.asString)
      case DatePrimitive(_,_,_) => JsString(content.asString)
      case _ =>  JsString(content.toString())
		}
	}
	
	private def value(content: Any): JsValue = {
		content match {
		  case s:String => {
		    try {
		      play.api.libs.json.Json.parse(s)
		    } catch {
		      case t: Throwable => JsString(s)
		    }
		  }
			case null => JsNull
      case i:Int => JsNumber(i)
      case f:Float => JsNumber(f)
      case l:Long => JsNumber(l)
      case d:Double => JsNumber(d)
      case b:Boolean => JsBoolean(b)
      case seq:Seq[Any] => listJs(seq)
      case map:Map[_,_] => dictJs(map.asInstanceOf[Map[String,Any]])
      case jsval:JsValue => jsval
      case prim:PrimitiveValue => primJs(prim)
			case _ =>  JsString(content.toString())
		}
	}
} 
Example 6
Source File: Duration.scala    From quick-plan   with Apache License 2.0 5 votes vote down vote up
package com.github.mgifos.workouts.model

import com.github.mgifos.workouts.model.DistanceUnits.DistanceUnit
import play.api.libs.json.{JsNull, JsObject, Json}

sealed trait Duration {
  def json: JsObject
}

case class DistanceDuration(distance: Float, unit: DistanceUnit) extends Duration {
  override def json: JsObject =
    Json.obj(
      "endCondition" -> Json.obj("conditionTypeKey" -> "distance", "conditionTypeId" -> 3),
      "preferredEndConditionUnit" -> Json.obj("unitKey" -> unit.fullName),
      "endConditionValue" -> unit.toMeters(distance),
      "endConditionCompare" -> JsNull,
      "endConditionZone" -> JsNull
    )
}

case class TimeDuration(minutes: Int = 0, seconds: Int = 0) extends Duration {
  override def json: JsObject =
    Json.obj(
      "endCondition" -> Json.obj("conditionTypeKey" -> "time", "conditionTypeId" -> 2),
      "preferredEndConditionUnit" -> JsNull,
      "endConditionValue" -> (minutes * 60 + seconds),
      "endConditionCompare" -> JsNull,
      "endConditionZone" -> JsNull
    )
}

object LapButtonPressed extends Duration {
  override def json: JsObject =
    Json.obj(
      "endCondition" -> Json.obj("conditionTypeKey" -> "lap.button", "conditionTypeId" -> 1),
      "preferredEndConditionUnit" -> JsNull,
      "endConditionValue" -> JsNull,
      "endConditionCompare" -> JsNull,
      "endConditionZone" -> JsNull
    )
}

object Duration {

  private val DistanceRx = """^(\d+([\.]\d+)?)\s*(km|mi|m)$""".r
  private val MinutesRx = """^(\d{1,3}):(\d{2})$""".r

  def parse(x: String): Duration = x match {
    case DistanceRx(quantity, _, uom) => DistanceDuration(quantity.toFloat, DistanceUnits.named(uom))
    case MinutesRx(minutes, seconds)  => TimeDuration(minutes = minutes.toInt, seconds = seconds.toInt)
    case "lap-button"                 => LapButtonPressed
    case _                            => throw new IllegalArgumentException(s"Duration cannot be parsed $x")
  }
} 
Example 7
Source File: TargetSpec.scala    From quick-plan   with Apache License 2.0 5 votes vote down vote up
package com.github.mgifos.workouts.model

import org.scalatest.{FlatSpec, Matchers}
import com.github.mgifos.workouts.model.DistanceUnits._
import play.api.libs.json.{JsNull, Json}

class TargetSpec extends FlatSpec with Matchers {

  implicit val msys = MeasurementSystems.metric

  "Target" should "parse correctly" in {

    a[IllegalArgumentException] should be thrownBy Target.parse("")

    Target.parse("z1") should be(HrZoneTarget(1))
    Target.parse("z2") should be(HrZoneTarget(2))

    val paceTarget = Target.parse("5:20-04:30").asInstanceOf[PaceTarget]
    paceTarget.from.minutes should be(5)
    paceTarget.to.seconds should be(30)
    paceTarget should be(PaceTarget(Pace(msys.distance, "5:20"), Pace(msys.distance, "04:30")))
  }

  "Target" should "parse pace UOMs correctly" in {
    val mpk = Target.parse("5:20-04:30 mpk").asInstanceOf[PaceTarget]
    mpk should be(PaceTarget(Pace(km, "5:20"), Pace(km, "04:30")))

    val mpm = Target.parse("4:20-05:30 mpm").asInstanceOf[PaceTarget]
    mpm should be(PaceTarget(Pace(mi, "4:20"), Pace(mi, "05:30")))
    mpm.from.speed should be(6.189784592848557D)

    a[IllegalArgumentException] should be thrownBy Target.parse("5:20-04:30 unknownUOM")
  }

  "Target" should "handle custom HR specification correctly" in {
    val hrcTarget = Target.parse("130-150 bpm").asInstanceOf[HrCustomTarget]
    hrcTarget should be(HrCustomTarget(130, 150))
    hrcTarget.json should be(
      Json.obj(
        "targetType" -> Json.obj("workoutTargetTypeId" -> 4, "workoutTargetTypeKey" -> "heart.rate.zone"),
        "targetValueOne" -> 130,
        "targetValueTwo" -> 150,
        "zoneNumber" -> JsNull
      ))
  }

  "Target" should "handle custom POWER specification correctly" in {
    val powTarget = Target.parse("230-250 W").asInstanceOf[PowerCustomTarget]
    powTarget should be(PowerCustomTarget(230, 250))
    powTarget.json should be(
      Json.obj(
        "targetType" -> Json.obj("workoutTargetTypeId" -> 2, "workoutTargetTypeKey" -> "power.zone"),
        "targetValueOne" -> 230,
        "targetValueTwo" -> 250,
        "zoneNumber" -> JsNull
      ))
  }

  "Target" should "handle custom CADENCE specification correctly" in {
    val cadenceTarget = Target.parse("80-90 rpm").asInstanceOf[CadenceCustomTarget]
    cadenceTarget should be(CadenceCustomTarget(80, 90))
    cadenceTarget.json should be(
      Json.obj(
        "targetType" -> Json.obj("workoutTargetTypeId" -> 3, "workoutTargetTypeKey" -> "cadence.zone"),
        "targetValueOne" -> 80,
        "targetValueTwo" -> 90,
        "zoneNumber" -> JsNull
      ))
  }
}