play.api.libs.json.JsResult Scala Examples

The following examples show how to use play.api.libs.json.JsResult. 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: SelfAssessmentUserType.scala    From pertax-frontend   with Apache License 2.0 5 votes vote down vote up
package models

import play.api.libs.json.{JsDefined, JsError, JsResult, JsString, JsSuccess, JsValue, Json, Reads, Writes}
import uk.gov.hmrc.domain.SaUtr

sealed trait SelfAssessmentUserType

sealed trait SelfAssessmentUser extends SelfAssessmentUserType {
  def saUtr: SaUtr
}

object SelfAssessmentUserType {
  val cacheId = "SelfAssessmentUser"

  val activatedSa = ActivatedOnlineFilerSelfAssessmentUser.toString
  val notActivatedSa = NotYetActivatedOnlineFilerSelfAssessmentUser.toString
  val wrongCredsSa = WrongCredentialsSelfAssessmentUser.toString
  val notEnrolledSa = NotEnrolledSelfAssessmentUser.toString
  val nonFilerSa = NonFilerSelfAssessmentUser.toString

  implicit val writes = new Writes[SelfAssessmentUserType] {
    override def writes(o: SelfAssessmentUserType): JsValue = o match {
      case ActivatedOnlineFilerSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(activatedSa), "utr" -> JsString(utr.toString))
      case NotYetActivatedOnlineFilerSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(notActivatedSa), "utr" -> JsString(utr.toString))
      case WrongCredentialsSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(wrongCredsSa), "utr" -> JsString(utr.toString))
      case NotEnrolledSelfAssessmentUser(utr) =>
        Json.obj("_type" -> JsString(notEnrolledSa), "utr" -> JsString(utr.toString))
      case NonFilerSelfAssessmentUser =>
        Json.obj("_type" -> JsString(nonFilerSa))
    }
  }

  implicit val reads = new Reads[SelfAssessmentUserType] {
    override def reads(json: JsValue): JsResult[SelfAssessmentUserType] =
      (json \ "_type", json \ "utr") match {

        case (JsDefined(JsString(`activatedSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(ActivatedOnlineFilerSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`notActivatedSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(NotYetActivatedOnlineFilerSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`wrongCredsSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(WrongCredentialsSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`notEnrolledSa`)), JsDefined(JsString(utr))) =>
          JsSuccess(NotEnrolledSelfAssessmentUser(SaUtr(utr)))
        case (JsDefined(JsString(`nonFilerSa`)), _) =>
          JsSuccess(NonFilerSelfAssessmentUser)
        case _ => JsError("Could not read SelfAssessmentUserType")
      }
  }
}

case class ActivatedOnlineFilerSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case class NotYetActivatedOnlineFilerSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case class WrongCredentialsSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case class NotEnrolledSelfAssessmentUser(saUtr: SaUtr) extends SelfAssessmentUser
case object NonFilerSelfAssessmentUser extends SelfAssessmentUserType 
Example 2
Source File: CkanRepositoryComponent.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.repository.ckan

import catalog_manager.yaml.{AutocompRes, Credentials, User}
import play.api.libs.json.JsValue

import scala.concurrent.Future


trait CkanRepository {

  def getMongoUser(name:String,callingUserid :MetadataCat): JsResult[User]
  def verifyCredentials(credentials: Credentials):Boolean
  def updateOrganization(orgId: String, jsonOrg: JsValue,callingUserid :MetadataCat): Future[String]
  def patchOrganization(orgId: String, jsonOrg: JsValue,callingUserid :MetadataCat): Future[String]
  def createUser(jsonUser: JsValue,callingUserid :MetadataCat): Future[String]
  def getUserOrganizations(userName :String,callingUserid :MetadataCat) : Future[JsResult[Seq[Organization]]]
  def createDataset(jsonDataset: JsValue,callingUserid :MetadataCat): Future[String]
  def createOrganization(jsonDataset: JsValue,callingUserid :MetadataCat): Future[String]
  def dataset(datasetId: String,callingUserid :MetadataCat): JsValue
  def getOrganization(orgId :String,callingUserid :MetadataCat) : Future[JsResult[Organization]]
  def getOrganizations(callingUserid :MetadataCat) : Future[JsValue]
  def getDatasets(callingUserid :MetadataCat) : Future[JsValue]
  def searchDatasets( input: (MetadataCat, MetadataCat, ResourceSize, ResourceSize), callingUserid :MetadataCat ) : Future[JsResult[Seq[Dataset]]]
  def autocompleteDatasets( input: (MetadataCat, ResourceSize), callingUserid :MetadataCat) : Future[JsResult[Seq[AutocompRes]]]
  def getDatasetsWithRes( input: (ResourceSize, ResourceSize), callingUserid :MetadataCat ) : Future[JsResult[Seq[Dataset]]]
  def testDataset(datasetId :String, callingUserid :MetadataCat) : Future[JsResult[Dataset]]

}

object CkanRepository {
  def apply(config: String): CkanRepository = config match {
    case "dev" => new CkanRepositoryDev
    case "prod" => new CkanRepositoryProd
  }
}

trait CkanRepositoryComponent {
  val ckanRepository :CkanRepository
} 
Example 3
Source File: TestJson.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.repository.voc

import java.io.FileInputStream

import catalog_manager.yaml.KeyValue
import play.api.libs.json.{JsArray, JsValue}

object TestJson extends App {
  import play.api.libs.json.{JsError, JsResult, JsSuccess, Json}

  val stream = new FileInputStream("data/voc/cv_theme-subtheme_bk.json")
  val json = try { (Json.parse(stream) \ "voc").asOpt[JsArray]} finally {stream.close()}
  val dcatapitThemeId = "AGRI"
  val subthemeId = "policy"
  print {
    json match {
      case Some(s) => s.value.map(x => ((x \ "theme_code").as[String],
        (x \ "subthemes").as[List[JsValue]])).map{ x=>

        x._2.map{ y=> //subthemes

          (x._1, (y \ "subthemes_ita").as[List[List[String]]])
        }
      }.flatten
        .filter(x=>x._1.equals(dcatapitThemeId))
        .map{x=>
          println(x)
          x._2.map{y=>
            println(y)
            println(y.length)
            //println(y(0))
            //println(y(1))
            KeyValue(y(0), y(1))
          }
        }.flatMap(x=>x)
      case None =>
        println("VocRepositoryFile - Error occurred with Json")
        Seq()
    }
  }

} 
Example 4
Source File: CkanService.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.service



trait CkanServiceComponent {
  this: CkanRepositoryComponent =>
  val ckanService: CkanService

  class CkanService {

    def getMongoUser(name:String, callingUserid :MetadataCat ): JsResult[User]  = {
      ckanRepository.getMongoUser(name, callingUserid)
    }

    def verifyCredentials(credentials: Credentials):Boolean = {
      ckanRepository.verifyCredentials(credentials: Credentials)
    }
    def updateOrganization(orgId: String, jsonOrg: JsValue, callingUserid :MetadataCat ): Future[String] = {
      ckanRepository.updateOrganization(orgId,jsonOrg, callingUserid)
    }
    def patchOrganization(orgId: String, jsonOrg: JsValue, callingUserid :MetadataCat ): Future[String] = {
      ckanRepository.patchOrganization(orgId,jsonOrg, callingUserid)
    }

    def createUser(jsonUser: JsValue, callingUserid :MetadataCat): Future[String] = {
      ckanRepository.createUser(jsonUser, callingUserid)
    }
    def getUserOrganizations(userName :String, callingUserid :MetadataCat) : Future[JsResult[Seq[Organization]]] = {
      ckanRepository.getUserOrganizations(userName, callingUserid)
    }

    def createDataset(jsonDataset: JsValue, callingUserid :MetadataCat): Future[String] = {
      ckanRepository.createDataset(jsonDataset,callingUserid)
    }
    def createOrganization(jsonDataset: JsValue, callingUserid :MetadataCat): Future[String] = {
      ckanRepository.createOrganization(jsonDataset,callingUserid)
    }
    def dataset(datasetId: String, callingUserid :MetadataCat): JsValue = {
      ckanRepository.dataset(datasetId,callingUserid)
    }

    def getOrganization(orgId :String, callingUserid :MetadataCat) : Future[JsResult[Organization]] = {
      ckanRepository.getOrganization(orgId,callingUserid)
    }

    def getOrganizations(callingUserid :MetadataCat) : Future[JsValue] = {
      ckanRepository.getOrganizations(callingUserid)
    }

    def getDatasets(callingUserid :MetadataCat) : Future[JsValue] = {
      ckanRepository.getDatasets(callingUserid)
    }

    def searchDatasets( input: (MetadataCat, MetadataCat, ResourceSize, ResourceSize), callingUserid :MetadataCat) : Future[JsResult[Seq[Dataset]]] = {
      ckanRepository.searchDatasets(input, callingUserid)
    }
    def autocompleteDatasets( input: (MetadataCat, ResourceSize), callingUserid :MetadataCat) : Future[JsResult[Seq[AutocompRes]]] = {
      ckanRepository.autocompleteDatasets(input, callingUserid)
    }

    def getDatasetsWithRes( input: (ResourceSize, ResourceSize),callingUserid :MetadataCat ) : Future[JsResult[Seq[Dataset]]] = {
      ckanRepository.getDatasetsWithRes(input, callingUserid)
    }

    def testDataset(datasetId :String, callingUserid :MetadataCat) : Future[JsResult[Dataset]] = {
      ckanRepository.testDataset(datasetId, callingUserid)
    }

  }
}


object CkanRegistry extends
  CkanServiceComponent with
  CkanRepositoryComponent {
  val conf = Configuration.load(Environment.simple())
  val app: String = conf.getString("app.type").getOrElse("dev")
  val ckanRepository =  CkanRepository(app)
  val ckanService = new CkanService
} 
Example 5
Source File: ReadsKey.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import java.util.UUID

import play.api.libs.json.{JsError, JsResult, JsSuccess}

trait ReadsKey[A] { self =>

  
  private[ops] abstract class AlwaysReadsKey[A] extends ReadsKey[A] {
    def readSafe(key: String): A
    final override def read(key: String): JsResult[A] = JsSuccess(readSafe(key))
  }

  implicit val readKeyString: ReadsKey[String] = new AlwaysReadsKey[String] {
    final override def readSafe(key: String): String = key
  }

  implicit val readKeySymbol: ReadsKey[Symbol] = new AlwaysReadsKey[Symbol] {
    final override def readSafe(key: String): Symbol = Symbol(key)
  }

  implicit val readKeyUUID: ReadsKey[UUID] = new ReadsKey[UUID] {
    final override def read(key: String): JsResult[UUID] = {
      if (key.length == 36) {
        try JsSuccess(UUID.fromString(key)) catch {
          case _: IllegalArgumentException => JsError("Invalid UUID format")
        }
      } else JsError("Invalid UUID length")
    }
  }

  implicit val readKeyByte: ReadsKey[Byte] = readsKeyNumber(java.lang.Byte.parseByte)
  implicit val readKeyShort: ReadsKey[Short] = readsKeyNumber(java.lang.Short.parseShort)
  implicit val readKeyInt: ReadsKey[Int] = readsKeyNumber(java.lang.Integer.parseInt)
  implicit val readKeyLong: ReadsKey[Long] = readsKeyNumber(java.lang.Long.parseLong)
} 
Example 6
Source File: ReadsKey.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import java.util.UUID

import play.api.libs.json.{JsError, JsResult, JsSuccess}

trait ReadsKey[A] { self =>

  
  private[ops] abstract class AlwaysReadsKey[A] extends ReadsKey[A] {
    def readSafe(key: String): A
    final override def read(key: String): JsResult[A] = JsSuccess(readSafe(key))
  }

  implicit val readKeyString: ReadsKey[String] = new AlwaysReadsKey[String] {
    final override def readSafe(key: String): String = key
  }

  implicit val readKeySymbol: ReadsKey[Symbol] = new AlwaysReadsKey[Symbol] {
    final override def readSafe(key: String): Symbol = Symbol(key)
  }

  implicit val readKeyUUID: ReadsKey[UUID] = new ReadsKey[UUID] {
    final override def read(key: String): JsResult[UUID] = {
      if (key.length == 36) {
        try JsSuccess(UUID.fromString(key)) catch {
          case _: IllegalArgumentException => JsError("Invalid UUID format")
        }
      } else JsError("Invalid UUID length")
    }
  }

  implicit val readKeyByte: ReadsKey[Byte] = readsKeyNumber(java.lang.Byte.parseByte)
  implicit val readKeyShort: ReadsKey[Short] = readsKeyNumber(java.lang.Short.parseShort)
  implicit val readKeyInt: ReadsKey[Int] = readsKeyNumber(java.lang.Integer.parseInt)
  implicit val readKeyLong: ReadsKey[Long] = readsKeyNumber(java.lang.Long.parseLong)
} 
Example 7
Source File: ThingType.scala    From swagger-check   with MIT License 5 votes vote down vote up
package models

import play.api.libs.json.{Format, JsResult, JsString, JsValue}
import play.api.mvc.QueryStringBindable.Parsing

object ThingType extends Enumeration {
  type Type = Value
  val Primary, Secondary, Other = Value

  implicit val jsonFormat = new Format[Type] {
    override def reads(json: JsValue): JsResult[Type] =
      json.validate[String].map(ThingType.withName)

    override def writes(o: Type): JsValue = JsString(o.toString)
  }

  implicit val queryBinder = new Parsing[Type](
    parse = ThingType.withName,
    serialize = v => v.toString,
    error = (key: String, e: Exception) => "Cannot parse parameter %s as ThingType: %s".format(key, e.getMessage)
  )
} 
Example 8
Source File: RecordMetadataTest.scala    From kafka-journal   with MIT License 5 votes vote down vote up
package com.evolutiongaming.kafka.journal

import cats.implicits._
import com.evolutiongaming.kafka.journal.ExpireAfter.implicits._
import com.evolutiongaming.kafka.journal.util.PlayJsonHelper._
import org.scalatest.FunSuite
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{JsResult, Json}

import scala.concurrent.duration._

class RecordMetadataTest extends FunSuite with Matchers {

  for {
    (metadata, json) <- List(
      (
        RecordMetadata.empty,
        Json.obj(
          ("header", Json.obj()),
          ("payload", Json.obj()))),
      (
        RecordMetadata(
          HeaderMetadata(Json.obj(("key0", "value0")).some),
          PayloadMetadata(1.day.toExpireAfter.some, Json.obj(("key1", "value1")).some)),
        Json.obj(
          ("header", Json.obj(
            ("data", Json.obj(("key0", "value0"))))),
          ("payload", Json.obj(
            ("expireAfter", "1 day"),
            ("data", Json.obj(("key1", "value1"))))),
          ("data", Json.obj(("key0", "value0"))))),
      (
        RecordMetadata(
          HeaderMetadata(Json.obj(("key0", "value0")).some),
          PayloadMetadata(none, Json.obj(("key1", "value1")).some)),
        Json.obj(
          ("header", Json.obj(
            ("data", Json.obj(("key0", "value0"))))),
          ("payload", Json.obj(
            ("data", Json.obj(("key1", "value1"))))),
          ("data", Json.obj(("key0", "value0"))))),
      (
        RecordMetadata(
          HeaderMetadata.empty,
          PayloadMetadata(1.day.toExpireAfter.some, Json.obj(("key1", "value1")).some)),
        Json.obj(
          ("header", Json.obj()),
          ("payload", Json.obj(
            ("expireAfter", "1 day"),
            ("data", Json.obj(("key1", "value1"))))))),
      (
        RecordMetadata(
          HeaderMetadata(Json.obj(("key0", "value0")).some),
          PayloadMetadata.empty),
        Json.obj(
          ("header", Json.obj(
            ("data", Json.obj(("key0", "value0"))))),
          ("payload", Json.obj()),
          ("data", Json.obj(("key0", "value0"))))))
  } {
    test(s"formatRecordMetadata reads & writes $json") {
      Json.toJson(metadata) shouldEqual json
      json.validate[RecordMetadata] shouldEqual metadata.pure[JsResult]
    }
  }

  for {
    (metadata, json) <- List(
      (
        RecordMetadata.empty,
        Json.obj()),
      (
        RecordMetadata(
          HeaderMetadata(Json.obj(("key0", "value0")).some),
          PayloadMetadata.empty),
        Json.obj(
          ("data", Json.obj(("key0", "value0"))))),
      (
        RecordMetadata(
          HeaderMetadata(Json.obj(("key0", "value0")).some),
          PayloadMetadata(none, Json.obj(("key1", "value1")).some)),
        Json.obj(
          ("header", Json.obj(
            ("data", Json.obj(("key0", "value0"))))),
          ("payload", Json.obj(
            ("data", Json.obj(("key1", "value1"))))))))
  } {
    test(s"formatRecordMetadata reads $json") {
      json.validate[RecordMetadata] shouldEqual metadata.pure[JsResult]
    }
  }
} 
Example 9
Source File: SpotifyMappers.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.she.mappers

import java.util.UUID

import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, PropertyQuery }
import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemMedia, DataFeedItemTitle }
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsError, JsNumber, JsObject, JsResult, JsSuccess, JsValue, __ }

import scala.util.Try

class SpotifyFeedMapper extends DataEndpointMapper {
  def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(EndpointQuery("spotify/feed", None,
        dateFilter(fromDate, untilDate).map(f ⇒ Seq(EndpointQueryFilter("played_at", None, f))), None)), Some("played_at"), Some("descending"), None))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = {
    for {
      durationSeconds ← Try((content \ "track" \ "duration_ms").as[Int] / 1000)
      title ← Try(
        DataFeedItemTitle("You listened", None, Some(s"${"%02d".format(durationSeconds / 60)}:${"%02d".format(durationSeconds % 60)}")))
      itemContent ← Try(DataFeedItemContent(
        Some(
          s"""${(content \ "track" \ "name").as[String]},
             |${(content \ "track" \ "artists").as[Seq[JsObject]].map(a ⇒ (a \ "name").as[String]).mkString(", ")},
             |${(content \ "track" \ "album" \ "name").as[String]}""".stripMargin),
        None,
        Some(
          Seq(DataFeedItemMedia((content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String], (content \ "track" \ "album" \ "images" \ 0 \ "url").asOpt[String]))),
        None))
      date ← Try((content \ "played_at").as[DateTime])
    } yield DataFeedItem("spotify", date, Seq(), Some(title), Some(itemContent), None)
  }
}

class SpotifyProfileStaticDataMapper extends StaticDataEndpointMapper {
  def dataQueries(): Seq[PropertyQuery] = {
    Seq(PropertyQuery(
      List(
        EndpointQuery("spotify/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1)))
  }

  def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = {
    val eventualData = content.validate[JsObject]
    eventualData match {
      case JsSuccess(value, _) =>

        val lastPartOfEndpointString = endpoint.split("/").last
        val maybeTransformedData = transformData(value).flatMap(item => item.validate[Map[String, JsValue]])
        maybeTransformedData match {
          case JsSuccess(data, _) =>

            Seq(StaticDataValues(lastPartOfEndpointString, (data - "images" - "external_urls")))
          case e: JsError =>

            logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
            Seq()
        }
      case e: JsError =>
        logger.error(s"Couldn't validate static data JSON for $endpoint. $e")
        Seq()
    }
  }

  private def transformData(rawData: JsObject): JsResult[JsValue] = {
    val transformation = __.json.update(
      __.read[JsObject].map(profile => {
        val followers = (profile \ "followers" \ "total").asOpt[JsNumber].getOrElse(JsNumber(0))

        profile ++ JsObject(Map(
          "followers" -> followers))
      }))

    rawData.transform(transformation)
  }
} 
Example 10
Source File: zio.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package libs.ziohelper
import cats.data.NonEmptyList
import play.api.libs.json.{JsError, JsPath, JsResult, JsSuccess, JsonValidationError}
import domains.errors.{IzanamiErrors, ValidationError}
import zio._
import libs.logs.ZLogger

object JsResults {

  def handleJsError[C <: ZLogger, T](err: Seq[(JsPath, Seq[JsonValidationError])]): ZIO[C, IzanamiErrors, T] =
    ZLogger.error(s"Error parsing json $err") *>
    IO.fail(NonEmptyList.of(ValidationError.error("error.json.parsing")))

  def jsResultToError[C <: ZLogger, T](jsResult: JsResult[T]): ZIO[C, IzanamiErrors, T] =
    fromJsResult(jsResult) { handleJsError }

  def jsResultToHttpResponse[T](jsResult: JsResult[T]) =
    liftJsResult(jsResult)(err => play.api.mvc.Results.BadRequest(ValidationError.fromJsError(err).toJson))

  def liftJsResult[T, E](jsResult: JsResult[T])(onError: Seq[(JsPath, Seq[JsonValidationError])] => E): IO[E, T] =
    jsResult match {
      case JsSuccess(value, _) => IO.succeed(value)
      case JsError(errors)     => IO.fail(onError(errors.toSeq.map(t => t.copy(_2 = t._2.toSeq))))
    }

  def fromJsResult[C <: ZLogger, T, E](
      jsResult: JsResult[T]
  )(onError: Seq[(JsPath, Seq[JsonValidationError])] => ZIO[C, E, T]): ZIO[C, E, T] =
    jsResult match {
      case JsSuccess(value, _) => ZIO.succeed(value)
      case JsError(errors)     => onError(errors.toSeq.map(t => t.copy(_2 = t._2.toSeq)))
    }

}