play.api.libs.json.JsSuccess Scala Examples
The following examples show how to use play.api.libs.json.JsSuccess.
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: LinkSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.{Markdown, TODO} import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class LinkSpec extends BaseSpec { describe("Link") { it("should parse and serialize") { val json = Json.parse(LinkSpec.jsonStr) json.validate[Link] shouldBe JsSuccess(LinkSpec.value) Json.toJson(LinkSpec.value) shouldBe json } } } object LinkSpec { val jsonStr: String = s"""{ | "operationId": "id", | "description": "desc", | "server": ${ServerSpec.jsonStr} |}""".stripMargin val value: Link = Link( operationId = Some("id"), operationRef = None, description = Some(Markdown("desc")), parameters = Option.empty[Map[String, TODO]], requestBody = Option.empty[TODO], server = Some(ServerSpec.value)) }
Example 2
Source File: UpdateGitRepo.scala From graphcool-framework with Apache License 2.0 | 5 votes |
import play.api.libs.json.{JsSuccess, JsValue, Json} import scalaj.http.{Base64, Http, HttpRequest} object GithubClient { def apply(): GithubClient = GithubClient(Env.read("GITHUB_ACCESS_TOKEN")) } case class GithubClient(accessToken: String) { import JsonFormatting._ val host = "https://api.github.com" val authHeader = "Authorization" -> s"token $accessToken" def updateFile(owner: String, repo: String, filePath: String, newContent: String, branch: String): Unit = { getCurrentSha(owner, repo, filePath, branch) match { case Some(currentSha) => updateContentsOfFile(owner, repo, filePath, currentSha, newContent, branch) println(s"Updated file $filePath in other repo successfully.") case None => println(s"Branch $branch in other repo does not seem to exist. Won't update file.") } } def getCurrentSha(owner: String, repo: String, filePath: String, branch: String): Option[String] = { val request = baseRequest(urlPath(owner, repo, filePath, branch)) request.asJson(200, 404).validate[GetContentResponse](getContentReads) match { case JsSuccess(parsed, _) => Some(parsed.sha) case _ => None } } def updateContentsOfFile(owner: String, repo: String, filePath: String, sha: String, newContent: String, branch: String): JsValue = { val request = baseRequest(urlPath(owner, repo, filePath)) val payload = UpdateContentsRequest( message = s"Updated by the SBT Task in the open source repo to: $newContent", content = Base64.encodeString(newContent), sha = sha, branch = branch ) request.put(Json.toJson(payload)(updateContentsWrites).toString).asJson(200) } def urlPath(owner: String, repo: String, filePath: String, branch: String): String = urlPath(owner, repo, filePath) + s"?ref=$branch" def urlPath(owner: String, repo: String, filePath: String): String = s"/repos/$owner/$repo/contents/$filePath" def baseRequest(path: String) = Http(s"$host$path").headers(authHeader).header("content-type", "application/json") implicit class HttpRequestExtensions(httpRequest: HttpRequest) { def asJson(allowedStatusCodes: Int*): JsValue = { val response = httpRequest.asString val isAllowedResponse = allowedStatusCodes.contains(response.code) require(isAllowedResponse, s"The request did not result in an expected status code. Allowed status are $allowedStatusCodes. The response was: $response") Json.parse(response.body) } } } object JsonFormatting { import play.api.libs.json._ case class GetContentResponse(sha: String) case class UpdateContentsRequest(message: String, content: String, sha: String, branch: String) implicit val getContentReads = Json.reads[GetContentResponse] implicit val updateContentsWrites = Json.writes[UpdateContentsRequest] } object Env { def read(name: String) = sys.env.getOrElse(name, sys.error(s"Env var $name must be set")) }
Example 3
Source File: Converters.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.singleserver import cool.graph.messagebus.Conversions.Converter import cool.graph.subscriptions.protocol.SubscriptionRequest import cool.graph.webhook.Webhook import cool.graph.websockets.protocol.Request import cool.graph.worker.payloads.{LogItem, Webhook => WorkerWebhook} import play.api.libs.json.{JsError, JsSuccess, Json} object Converters { import cool.graph.worker.payloads.JsonConversions.logItemFormat val apiWebhook2WorkerWebhook: Converter[Webhook, WorkerWebhook] = { wh: Webhook => WorkerWebhook(wh.projectId, wh.functionId, wh.requestId, wh.url, wh.payload, wh.id, wh.headers) } val string2LogItem = { str: String => Json.parse(str).validate[LogItem] match { case JsSuccess(logItem, _) => logItem case JsError(e) => sys.error(s"Invalid log item $str, ignoring message.") } } val websocketRequest2SubscriptionRequest = { req: Request => SubscriptionRequest(req.sessionId, req.projectId, req.body) } }
Example 4
Source File: SubscriptionsMain.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.subscriptions import akka.actor.{ActorSystem, Props} import akka.stream.ActorMaterializer import cool.graph.akkautil.http.{Routes, Server, ServerExecutor} import cool.graph.messagebus.pubsub.Only import cool.graph.subscriptions.protocol.SubscriptionProtocolV05.Requests.SubscriptionSessionRequestV05 import cool.graph.subscriptions.protocol.SubscriptionProtocolV07.Requests.SubscriptionSessionRequest import cool.graph.subscriptions.protocol.SubscriptionProtocolV07.Responses.GqlError import cool.graph.subscriptions.protocol.SubscriptionSessionManager.Requests.{EnrichedSubscriptionRequest, EnrichedSubscriptionRequestV05, StopSession} import cool.graph.subscriptions.protocol.{StringOrInt, SubscriptionRequest, SubscriptionSessionManager} import cool.graph.subscriptions.resolving.SubscriptionsManager import cool.graph.subscriptions.util.PlayJson import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport import play.api.libs.json.{JsError, JsSuccess} import scala.concurrent.Future object SubscriptionsMain extends App { implicit val system = ActorSystem("graphql-subscriptions") implicit val materializer = ActorMaterializer() implicit val injector = new SimpleSubscriptionInjectorImpl() ServerExecutor(port = 8086, SimpleSubscriptionsServer()).startBlocking() } case class SimpleSubscriptionsServer(prefix: String = "")( implicit subscriptionInjector: SimpleSubscriptionInjector, system: ActorSystem, materializer: ActorMaterializer ) extends Server with PlayJsonSupport { import system.dispatcher implicit val bugSnag = subscriptionInjector.bugsnagger implicit val response05Publisher = subscriptionInjector.responsePubSubPublisherV05 implicit val response07Publisher = subscriptionInjector.responsePubSubPublisherV07 val innerRoutes = Routes.emptyRoute val subscriptionsManager = system.actorOf(Props(new SubscriptionsManager(bugSnag)), "subscriptions-manager") val requestsConsumer = subscriptionInjector.requestsQueueConsumer val consumerRef = requestsConsumer.withConsumer { req: SubscriptionRequest => Future(if (req.body == "STOP") subscriptionSessionManager ! StopSession(req.sessionId) else handleProtocolMessage(req.projectId, req.sessionId, req.body)) } val subscriptionSessionManager = system.actorOf( Props(new SubscriptionSessionManager(subscriptionsManager, bugSnag)), "subscriptions-sessions-manager" ) def handleProtocolMessage(projectId: String, sessionId: String, messageBody: String) = { import cool.graph.subscriptions.protocol.ProtocolV05.SubscriptionRequestReaders._ import cool.graph.subscriptions.protocol.ProtocolV07.SubscriptionRequestReaders._ val currentProtocol = PlayJson.parse(messageBody).flatMap(_.validate[SubscriptionSessionRequest]) lazy val oldProtocol = PlayJson.parse(messageBody).flatMap(_.validate[SubscriptionSessionRequestV05]) currentProtocol match { case JsSuccess(request, _) => subscriptionSessionManager ! EnrichedSubscriptionRequest(sessionId = sessionId, projectId = projectId, request) case JsError(newError) => oldProtocol match { case JsSuccess(request, _) => subscriptionSessionManager ! EnrichedSubscriptionRequestV05(sessionId = sessionId, projectId = projectId, request) case JsError(oldError) => response07Publisher.publish(Only(sessionId), GqlError(StringOrInt(string = Some(""), int = None), "The message can't be parsed")) } } } override def onStop = Future { consumerRef.stop // subscriptionInjector.projectSchemaInvalidationSubscriber.shutdown } }
Example 5
Source File: PathItemSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.Markdown import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class PathItemSpec extends BaseSpec { describe("PathItem") { it("should parse and serialize") { val json = Json.parse(PathItemSpec.jsonStr) json.validate[PathItem] shouldBe JsSuccess(PathItemSpec.value) Json.toJson(PathItemSpec.value) shouldBe json } } } object PathItemSpec { val jsonStr: String = """{ | "summary": "s", | "description": "d", | "get": { | "responses": {} | } |}""".stripMargin val value: PathItem = PathItem( summary = Some("s"), description = Some(Markdown("d")), parameters = None, servers = None, get = Some(PathItem.Operation(None, None, None, None, None, None, None, None, Map(), None, None, None, None)), put = None, post = None, delete = None, options = None, head = None, patch = None, trace = None, extensions = None) }
Example 6
Source File: InfoSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils._ import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class InfoSpec extends BaseSpec { describe("Info") { it("should parse and serialize") { val json = Json.parse(InfoSpec.jsonStr) json.validate[Info] shouldBe JsSuccess(InfoSpec.value) Json.toJson(InfoSpec.value) shouldBe json } } } object InfoSpec { val jsonStr: String = """{ | "title": "My api", | "description": "desc", | "termsOfService": "https://gospeak.io/tos", | "contact": {"name": "Support", "url": "https://gospeak.io/support", "email": "[email protected]"}, | "license": {"name": "Apache 2.0", "url": "https://gospeak.io/license"}, | "version": "1.0.0" |}""".stripMargin val value: Info = Info( title = "My api", description = Some(Markdown("desc")), termsOfService = Some(Url("https://gospeak.io/tos")), contact = Some(Info.Contact(Some("Support"), Some(Url("https://gospeak.io/support")), Some(Email("[email protected]")), Option.empty[TODO])), license = Some(Info.License("Apache 2.0", Some(Url("https://gospeak.io/license")), Option.empty[TODO])), version = Version(1), extensions = Option.empty[TODO]) }
Example 7
Source File: RequestBodySpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.{Markdown, TODO} import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class RequestBodySpec extends BaseSpec { describe("RequestBody") { it("should parse and serialize") { val json = Json.parse(RequestBodySpec.jsonStr) json.validate[RequestBody] shouldBe JsSuccess(RequestBodySpec.value) Json.toJson(RequestBodySpec.value) shouldBe json } } } object RequestBodySpec { val jsonStr: String = """{ | "description": "desc", | "content": {} |}""".stripMargin val value: RequestBody = RequestBody( description = Some(Markdown("desc")), content = Map(), required = None, extensions = Option.empty[TODO]) }
Example 8
Source File: TagSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.{Markdown, TODO} import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class TagSpec extends BaseSpec { describe("Tag") { it("should parse and serialize") { val json = Json.parse(TagSpec.jsonStr) json.validate[Tag] shouldBe JsSuccess(TagSpec.value) Json.toJson(TagSpec.value) shouldBe json } } } object TagSpec { val jsonStr: String = s"""{ | "name": "public", | "description": "Public API", | "externalDocs": ${ExternalDocSpec.jsonStr} |}""".stripMargin val value: Tag = Tag( name = "public", description = Some(Markdown("Public API")), externalDocs = Some(ExternalDocSpec.value), extensions = Option.empty[TODO]) }
Example 9
Source File: HeaderSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.Markdown import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class HeaderSpec extends BaseSpec { describe("Header") { it("should parse and serialize") { val json = Json.parse(HeaderSpec.jsonStr) json.validate[Header] shouldBe JsSuccess(HeaderSpec.value) Json.toJson(HeaderSpec.value) shouldBe json } } } object HeaderSpec { val jsonStr: String = s"""{ | "description": "Header desc", | "schema": ${SchemaSpec.jsonStr} |}""".stripMargin val value: Header = Header( description = Some(Markdown("Header desc")), schema = Some(SchemaSpec.value)) }
Example 10
Source File: ServerSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.error.OpenApiError import gospeak.libs.openapi.models.utils.{Markdown, TODO, Url} import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class ServerSpec extends BaseSpec { describe("Server") { it("should parse and serialize") { val json = Json.parse(ServerSpec.jsonStr) json.validate[Server] shouldBe JsSuccess(ServerSpec.value) Json.toJson(ServerSpec.value) shouldBe json } it("should extract variables from an Url") { Server.extractVariables(Url("https://gospeak.io/api")) shouldBe Seq() Server.extractVariables(Url("https://{user}:{pass}@gospeak.io:{port}/api")) shouldBe Seq("user", "pass", "port") } it("should check if all variables are referenced") { val s = Schemas() Server(Url("https://gospeak.io/api"), None, None, None).getErrors(s) shouldBe List() Server(Url("https://gospeak.io/api"), None, Some(Map("port" -> Server.Variable("9000", None, None, None))), None).getErrors(s) shouldBe List() Server(Url("https://gospeak.io:{port}/api"), None, Some(Map("port" -> Server.Variable("9000", None, None, None))), None).getErrors(s) shouldBe List() Server(Url("https://gospeak.io:{port}/api"), None, None, None).getErrors(s) shouldBe List(OpenApiError.missingVariable("port").atPath(".url")) } it("should replace variables") { Server(Url("https://gospeak.io/api"), None, None, None).expandedUrl shouldBe Url("https://gospeak.io/api") Server(Url("https://gospeak.io:{port}/api"), None, Some(Map("port" -> Server.Variable("9000", None, None, None))), None).expandedUrl shouldBe Url("https://gospeak.io:9000/api") } } } object ServerSpec { val jsonStr: String = """{ | "url": "https://gospeak.io:{port}/api", | "description": "Prod", | "variables": { | "port": { | "default": "8443", | "enum": ["8443", "443"], | "description": "The port to use" | } | } |}""".stripMargin val value: Server = Server( Url("https://gospeak.io:{port}/api"), Some(Markdown("Prod")), Some(Map("port" -> Server.Variable("8443", Some(List("8443", "443")), Some(Markdown("The port to use")), Option.empty[TODO]))), Option.empty[TODO]) }
Example 11
Source File: ResponseSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.{Markdown, TODO} import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class ResponseSpec extends BaseSpec { describe("Response") { it("should parse and serialize") { val json = Json.parse(ResponseSpec.jsonStr) json.validate[Response] shouldBe JsSuccess(ResponseSpec.value) Json.toJson(ResponseSpec.value) shouldBe json } } } object ResponseSpec { val jsonStr: String = s"""{ | "description": "desc", | "headers": { | "custom": ${HeaderSpec.jsonStr} | }, | "content": { | "application/json": ${MediaTypeSpec.jsonStr} | }, | "links": { | "ref": ${LinkSpec.jsonStr} | } |}""".stripMargin val value: Response = Response( description = Markdown("desc"), headers = Some(Map("custom" -> HeaderSpec.value)), content = Some(Map("application/json" -> MediaTypeSpec.value)), links = Some(Map("ref" -> LinkSpec.value)), extensions = Option.empty[TODO]) }
Example 12
Source File: SpotifyMappers.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
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 13
Source File: ParameterSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.Markdown import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class ParameterSpec extends BaseSpec { describe("Parameter") { it("should parse and serialize") { val json = Json.parse(ParameterSpec.jsonStr) json.validate[Parameter] shouldBe JsSuccess(ParameterSpec.value) Json.toJson(ParameterSpec.value) shouldBe json } } } object ParameterSpec { val jsonStr: String = s"""{ | "name": "id", | "in": "path", | "description": "an id", | "required": true, | "schema": ${SchemaSpec.jsonStr} |}""".stripMargin val value: Parameter = Parameter( name = "id", in = Parameter.Location.Path, deprecated = None, description = Some(Markdown("an id")), required = Some(true), allowEmptyValue = None, style = None, explode = None, allowReserved = None, schema = Some(SchemaSpec.value), example = None) }
Example 14
Source File: ComponentsSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.TODO import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class ComponentsSpec extends BaseSpec { describe("Components") { it("should parse and serialize") { val json = Json.parse(ExternalDocSpec.jsonStr) json.validate[ExternalDoc] shouldBe JsSuccess(ExternalDocSpec.value) Json.toJson(ExternalDocSpec.value) shouldBe json } } } object ComponentsSpec { val jsonStr: String = s"""{ | "schemas": { | "User": ${SchemaSpec.jsonStr} | } |}""".stripMargin val value: Components = Components( schemas = Some(Schemas("User" -> SchemaSpec.value)), responses = Option.empty[TODO], parameters = Option.empty[TODO], examples = Option.empty[TODO], requestBodies = Option.empty[TODO], headers = Option.empty[TODO], securitySchemes = Option.empty[TODO], links = Option.empty[TODO], callbacks = Option.empty[TODO], extensions = Option.empty[TODO]) }
Example 15
Source File: ExternalDocSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.{Markdown, TODO, Url} import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class ExternalDocSpec extends BaseSpec { describe("ExternalDoc") { it("should parse and serialize") { val json = Json.parse(ExternalDocSpec.jsonStr) json.validate[ExternalDoc] shouldBe JsSuccess(ExternalDocSpec.value) Json.toJson(ExternalDocSpec.value) shouldBe json } } } object ExternalDocSpec { val jsonStr: String = """{ | "url": "https://gospeak.io/docs", | "description": "More doc on API" |}""".stripMargin val value: ExternalDoc = ExternalDoc( url = Url("https://gospeak.io/docs"), description = Some(Markdown("More doc on API")), extensions = Option.empty[TODO]) }
Example 16
Source File: MediaTypeSpec.scala From gospeak with Apache License 2.0 | 5 votes |
package gospeak.libs.openapi.models import gospeak.libs.openapi.OpenApiFactory.Formats._ import gospeak.libs.openapi.models.utils.TODO import gospeak.libs.testingutils.BaseSpec import play.api.libs.json.{JsSuccess, Json} class MediaTypeSpec extends BaseSpec { describe("MediaType") { it("should parse and serialize") { val json = Json.parse(MediaTypeSpec.jsonStr) json.validate[MediaType] shouldBe JsSuccess(MediaTypeSpec.value) Json.toJson(MediaTypeSpec.value) shouldBe json } } } object MediaTypeSpec { val jsonStr: String = s"""{ | "schema": ${SchemaSpec.jsonStr} |}""".stripMargin val value: MediaType = MediaType( schema = Some(SchemaSpec.value), example = None, examples = Option.empty[Map[String, TODO]], encoding = Option.empty[TODO], extensions = Option.empty[TODO]) }
Example 17
Source File: BytesToWatchEventSource.scala From skuber with Apache License 2.0 | 5 votes |
package skuber.api.watch import akka.stream.scaladsl.{JsonFraming, Source} import akka.util.ByteString import play.api.libs.json.{Format, JsError, JsSuccess, Json} import skuber.ObjectResource import skuber.api.client.{K8SException, Status, WatchEvent} import scala.concurrent.ExecutionContext private[api] object BytesToWatchEventSource { def apply[O <: ObjectResource](bytesSource: Source[ByteString, _], bufSize: Int)(implicit ec: ExecutionContext, format: Format[O]): Source[WatchEvent[O], _] = { import skuber.json.format.apiobj.watchEventFormat bytesSource.via( JsonFraming.objectScanner(bufSize) ).map { singleEventBytes => Json.parse(singleEventBytes.utf8String).validate(watchEventFormat[O]) match { case JsSuccess(value, _) => value case JsError(e) => throw new K8SException(Status(message = Some("Error parsing watched object"), details = Some(e.toString))) } } } }
Example 18
Source File: PodDisruptionBudgetSpec.scala From skuber with Apache License 2.0 | 5 votes |
package skuber.policy.v1beta1 import org.specs2.mutable.Specification import play.api.libs.json.{JsSuccess, Json} import skuber.LabelSelector.dsl._ class PodDisruptionBudgetSpec extends Specification { import PodDisruptionBudget._ "A PodDisruptionBudget can" >> { "decoded from json" >> { val pdb = PodDisruptionBudget("someName") .withMaxUnavailable(Left(2)) .withMinAvailable(Left(1)) .withLabelSelector("application" is "someApplicationName") Json.parse(createJson("/examplePodDisruptionBudget.json")).validate[PodDisruptionBudget] mustEqual JsSuccess(pdb) } "encode to json" >> { Json.toJson( PodDisruptionBudget("someName") .withMaxUnavailable(Left(2)) .withMinAvailable(Left(1)) .withLabelSelector("application" is "someApplicationName") ) mustEqual Json.parse(createJson("/examplePodDisruptionBudget.json")) } } private def createJson(file: String): String = { val source = scala.io.Source.fromURL(getClass.getResource(file)) try source.mkString finally source.close() } }
Example 19
Source File: CopyingFormatsTest.scala From courscala with Apache License 2.0 | 5 votes |
package org.coursera.common.jsonformat import org.junit.Test import org.scalatest.junit.AssertionsForJUnit import play.api.libs.json.JsSuccess import play.api.libs.json.Json import play.api.libs.json.Reads class CopyingFormatsTest extends AssertionsForJUnit { import CopyingFormatsTest._ @Test def readNew(): Unit = { assertResult(JsSuccess(NewType("hi", "", 1))) { Json.fromJson[NewType](Json.obj("newField" -> "hi", "oldField" -> "", "unrelated" -> 1)) } } @Test def readOld(): Unit = { assertResult(JsSuccess(NewType("", "", 1))) { Json.fromJson[NewType](Json.obj("oldField" -> "", "unrelated" -> 1)) } } } object CopyingFormatsTest { case class NewType(newField: String, oldField: String, unrelated: Int) implicit val copyingReads: Reads[NewType] = CopyingFormats.copyingReads( Json.reads[NewType], "oldField" -> "newField") }
Example 20
Source File: JsonFormatsTest.scala From courscala with Apache License 2.0 | 5 votes |
package org.coursera.common.jsonformat import org.coursera.common.collection.Enum import org.coursera.common.collection.EnumSymbol import org.coursera.common.stringkey.StringKey import org.coursera.common.stringkey.StringKeyFormat import org.joda.time.DateTime import org.joda.time.DateTimeZone import org.joda.time.Duration import org.joda.time.Instant import org.junit.Test import org.scalatest.junit.AssertionsForJUnit import play.api.libs.json.Format import play.api.libs.json.JsNumber import play.api.libs.json.JsString import play.api.libs.json.JsSuccess import play.api.libs.json.Json class JsonFormatsTest extends AssertionsForJUnit { import JsonFormatsTest._ @Test def stringKey(): Unit = { val id = TestId(2, "test") val idString = StringKey.stringify(id) assert(JsString(idString) === Json.toJson(id)) assert(JsSuccess(id) === Json.fromJson[TestId](JsString(idString))) assert(JsString(s"invalid stuff $idString").validate[TestId].isError) } @Test def enums(): Unit = { assertResult(Color.Amber)(JsString("Amber").as[Color]) assertResult(JsString("Green"))(Json.toJson(Color.Green)) } @Test def instant(): Unit = { import JsonFormats.Implicits.instantFormat val testInstant = new Instant(137) assertResult(JsNumber(137))(Json.toJson(testInstant)) assertResult(Some(testInstant))(Json.parse("137").asOpt[Instant]) } @Test def duration(): Unit = { import JsonFormats.Implicits.durationFormat val testDuration = Duration.millis(137L) assertResult(JsNumber(137))(Json.toJson(testDuration)) assertResult(Some(testDuration))(Json.parse("137").asOpt[Duration]) } @Test def dateTime(): Unit = { import JsonFormats.Implicits.dateTimeFormat val testDatetime = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC) assertResult(JsNumber(1262304000000L))(Json.toJson(testDatetime)) assertResult(Some(testDatetime))(Json.parse("1262304000000").asOpt[DateTime].map(_.withZone(DateTimeZone.UTC))) } } object JsonFormatsTest { case class TestId(part1: Int, part2: String) object TestId { implicit val stringKeyFormat: StringKeyFormat[TestId] = StringKeyFormat.caseClassFormat((apply _).tupled, unapply) implicit val format: Format[TestId] = JsonFormats.stringKeyFormat[TestId] } sealed trait Color extends EnumSymbol object Color extends Enum[Color] { case object Red extends Color case object Amber extends Color case object Green extends Color implicit val format: Format[Color] = JsonFormats.enumFormat(Color) } }
Example 21
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))) } }
Example 22
Source File: KeyTest.scala From izanami with Apache License 2.0 | 5 votes |
package domains import play.api.libs.json.{JsError, JsString, JsSuccess, Json} import store.{EmptyPattern, StringPattern} import test.IzanamiSpec class KeyTest extends IzanamiSpec { "Key deserialization" must { "should be valid" in { val result = JsString("ragnar:lodbrok:730").validate[Key] result mustBe an[JsSuccess[_]] result.get must be(Key("ragnar:lodbrok:730")) } "should be invalid" in { val result = JsString("björn:ironside").validate[Key] result mustBe an[JsError] } } "Key serialization" must { "should be valid" in { Json.toJson(Key("ragnar:lodbrok:730")) must be(JsString("ragnar:lodbrok:730")) } } "Test patterns" must { "match" in { Key("test2:ab:scenario:B:8:displayed").matchPattern("test2:ab:scenario:*") must be(true) } "not match" in { Key("test1:ab:scenario:B:8:displayed").matchPattern("test2:ab:scenario:*") must be(false) } "match all is true" in { Key("test2:ab:scenario:B:8:displayed").matchAllPatterns("test2:ab:scenario:*", "test2:ab:*") must be(true) } "match all is false" in { Key("test1:ab:scenario:B:8:displayed").matchAllPatterns("test2:ab:scenario:*", "test1:ab:*") must be(false) } "match one str is true" in { Key("test1:ab:scenario:B:8:displayed").matchOneStrPatterns("test2:ab:scenario:*", "test1:ab:*") must be(true) } "match one is false" in { Key("test1:ab:scenario:B:8:displayed").matchOneStrPatterns("test2:ab:scenario:*", "test2:ab:*") must be(false) } "match one pattern is true" in { Key("test1:ab:scenario:B:8:displayed").matchOnePatterns(StringPattern("test2:ab:scenario:*"), StringPattern("test1:ab:*")) must be(true) } "match one pattern with empty is false" in { Key("test1:ab:scenario:B:8:displayed") .matchOnePatterns(StringPattern("test2:ab:scenario:*"), EmptyPattern) must be(false) } } }
Example 23
Source File: DefinitionFormatsSpec.scala From swagger-check with MIT License | 5 votes |
package de.leanovate.swaggercheck.schema.play import de.leanovate.swaggercheck.schema.model.{Definition, ObjectDefinition, StringDefinition} import org.scalatest.{MustMatchers, WordSpec} import play.api.libs.json.{JsSuccess, Json} import de.leanovate.swaggercheck.schema.play.Implicits._ class DefinitionFormatsSpec extends WordSpec with MustMatchers { "DefinitionFormats" should { "deserialize object_definition" in { val json = Json.parse(getClass.getClassLoader.getResourceAsStream("object_definition.json")) val JsSuccess(definition, _) = json.validate[Definition] val ObjectDefinition(required, properties, additionalProperties) = definition required mustBe Some(Set("field1")) properties mustBe Some(Map("field1" -> StringDefinition(None, None, None, None, None))) additionalProperties mustBe Left(true) } } }
Example 24
Source File: EitherReads.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.utils import play.api.libs.json.{JsError, JsSuccess, Reads} object EitherReads { implicit def eitherReads[A, B](implicit A: Reads[A], B: Reads[B]): Reads[Either[A, B]] = Reads[Either[A, B]] { json => A.reads(json) match { case JsSuccess(value, path) => JsSuccess(Left(value), path) case JsError(e1) => B.reads(json) match { case JsSuccess(value, path) => JsSuccess(Right(value), path) case JsError(e2) => JsError(JsError.merge(e1, e2)) } } } }
Example 25
Source File: TestJson.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 26
Source File: JsonBodyReadablesSpec.scala From play-ws with Apache License 2.0 | 5 votes |
package play.api.libs.ws import java.nio.charset.Charset import java.nio.charset.StandardCharsets._ import akka.stream.scaladsl.Source import akka.util.ByteString import org.specs2.matcher.MustMatchers import org.specs2.mutable.Specification import play.api.libs.json.JsSuccess import play.api.libs.json.JsValue class JsonBodyReadablesSpec extends Specification with MustMatchers { class StubResponse(byteArray: Array[Byte], charset: Charset = UTF_8) extends StandaloneWSResponse { override def uri: java.net.URI = ??? override def headers: Map[String, Seq[String]] = ??? override def underlying[T]: T = ??? override def status: Int = ??? override def statusText: String = ??? override def cookies: Seq[WSCookie] = ??? override def cookie(name: String): Option[WSCookie] = ??? override def body: String = new String(byteArray, charset) override def bodyAsBytes: ByteString = ByteString.fromArray(byteArray) override def bodyAsSource: Source[ByteString, _] = ??? } "decode encodings correctly" should { "read an encoding of UTF-32BE" in { val readables = new JsonBodyReadables() {} val json = """{"menu": {"id": "file", "value": "File"} }""" val charsetName = "UTF-32BE" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charsetName), Charset.forName(charsetName))) (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) } "read an encoding of UTF-32LE" in { val readables = new JsonBodyReadables() {} val json = """{"menu": {"id": "file", "value": "File"} }""" val charsetName = "UTF-32LE" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charsetName), Charset.forName(charsetName))) (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) } "read an encoding of UTF-16BE" in { val readables = new JsonBodyReadables() {} val json = """{"menu": {"id": "file", "value": "File"} }""" val charset = UTF_16BE val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charset), charset)) (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) } "read an encoding of UTF-16LE" in { val readables = new JsonBodyReadables() {} val json = """{"menu": {"id": "file", "value": "File"} }""" val charset = UTF_16LE val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charset), charset)) (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) } "read an encoding of UTF-8" in { val readables = new JsonBodyReadables() {} val json = """{"menu": {"id": "file", "value": "File"} }""" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(UTF_8))) (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) } "read an encoding of UTF-8 with empty object" in { val readables = new JsonBodyReadables() {} val json = "{}" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(UTF_8))) value.toString() must beEqualTo("{}") } "read an encoding of UTF-8 with empty array" in { val readables = new JsonBodyReadables() {} val json = "[]" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(UTF_8))) value.toString() must beEqualTo("[]") } } }
Example 27
Source File: ReadsKey.scala From play-json-ops with MIT License | 5 votes |
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 28
Source File: ReadsKey.scala From play-json-ops with MIT License | 5 votes |
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 29
Source File: WsParser.scala From vat-api with Apache License 2.0 | 5 votes |
package v1.connectors.httpparsers import play.api.Logger import play.api.libs.json.{JsError, JsSuccess, JsValue, Reads} import play.api.libs.ws.WSResponse import scala.util.{Success, Try} trait WsParser { implicit class KnownJsonResponse(response: WSResponse) { def validateJson[T](implicit reads: Reads[T]): Option[T] = { Try(response.json) match { case Success(json: JsValue) => parseResult(json) case _ => Logger.warn("[KnownJsonResponse][validateJson - NRS] No JSON was returned") None } } def parseResult[T](json: JsValue)(implicit reads: Reads[T]): Option[T] = json.validate[T] match { case JsSuccess(value, _) => Some(value) case JsError(error) => Logger.warn(s"[KnownJsonResponse][validateJson - NRS] Unable to parse JSON: $error") None } } }
Example 30
Source File: FinancialDataResponse.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.http.Status import play.api.libs.json.{JsError, JsSuccess, JsValue} import uk.gov.hmrc.domain.Vrn import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.models.des.DesErrorCode._ import uk.gov.hmrc.vatapi.models.{DesTransformError, DesTransformValidator, Errors, Liabilities, Payments, des} import uk.gov.hmrc.vatapi.resources.VatResult case class FinancialDataResponse(underlying: HttpResponse) extends Response { def getLiabilities(vrn: Vrn): Either[DesTransformError, Liabilities] = { def deserialise(js: JsValue) = js.validate[des.FinancialData] match { case JsError(errors) => Left(ParseError(s"[FinancialDataResponse][getLiabilities - deserialise] Json format from DES doesn't match the FinancialData model: $errors")) case JsSuccess(financialData, _) => DesTransformValidator[des.FinancialData, Liabilities].from(financialData) } jsonOrError match { case Right(js) => logger.debug(s"[FinancialDataResponse][getLiabilities - jsonOrError] Json response body from DES : ${js}") deserialise(js) case Left(e) => logger.error(s"[FinancialDataResponse][getLiabilities - jsonOrError] Non json response from DES : ${e.getMessage}") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) } } def getPayments(vrn: Vrn): Either[DesTransformError, Payments] = { def deserialise(js: JsValue) = js.validate[des.FinancialData] match { case JsError(errors) => Left(ParseError(s"[FinancialDataResponse][getPayments - deserialise] Json format from DES doesn't match the FinancialData model: $errors")) case JsSuccess(financialData, _) => DesTransformValidator[des.FinancialData, Payments].from(financialData) } jsonOrError match { case Right(js) => logger.debug(s"[FinancialDataResponse][getPayments - jsonOrError] Json response body from DES : ${js}") deserialise(js) case Left(e) => logger.error(s"[FinancialDataResponse][getPayments - jsonOrError] Non json response from DES : ${e.getMessage}") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) } } override def errorMappings: PartialFunction[Int, VatResult] = { case 400 if errorCodeIsOneOf(INVALID_IDNUMBER) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid) case 400 if errorCodeIsOneOf(INVALID_DATEFROM) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidDateFrom) case 400 if errorCodeIsOneOf(INVALID_DATETO) => VatResult.Failure(Status.BAD_REQUEST,Errors.InvalidDateTo) case 400 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND, Errors.NotFound) case 400 if errorCodeIsOneOf(INVALID_IDTYPE, INVALID_ONLYOPENITEMS, INVALID_REGIMETYPE, INVALID_INCLUDELOCKS, INVALID_CALCULATEACCRUEDINTEREST, INVALID_CUSTOMERPAYMENTINFORMATION ) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 404 if errorCodeIsOneOf(NOT_FOUND) => VatResult.Failure(Status.NOT_FOUND,Errors.NotFound) case 422 if errorCodeIsOneOf(INVALID_DATA) => VatResult.Failure(Status.BAD_REQUEST,Errors.InvalidData) } }
Example 31
Source File: VatReturnResponse.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources.wrappers import play.api.http.Status import play.api.libs.json.{JsError, JsSuccess, JsValue} import uk.gov.hmrc.http.HttpResponse import uk.gov.hmrc.vatapi.httpparsers.NRSData import uk.gov.hmrc.vatapi.models.des.DesErrorCode._ import uk.gov.hmrc.vatapi.models.{DesTransformError, DesTransformValidator, Errors, VatReturn, des} import uk.gov.hmrc.vatapi.resources.VatResult case class VatReturnResponse(underlying: HttpResponse) extends Response { var nrsData: NRSData = _ def vatReturnOrError: Either[DesTransformError, VatReturn] = { def deserialise(js: JsValue) = js.validate[des.VatReturn] match { case JsError(errors) => Left(ParseError(s"Json format from DES doesn't match the VatReturn model: $errors")) case JsSuccess(vatReturn, _) => DesTransformValidator[des.VatReturn, VatReturn].from(vatReturn) } jsonOrError match { case Left(e) => logger.error(s"[VatReturnResponse][vatReturnOrError] Non json response from DES : $e") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) case Right(js) => deserialise(js) } } def vatSubmissionReturnOrError: Either[DesTransformError, JsValue] = { jsonOrError match { case Left(e) => logger.error(s"[VatReturnResponse][vatReturnOrError] Non json response from DES : $e") Left(ParseError(s"Unable to parse the response from DES as Json: $e")) case Right(js) => Right(js) } } def withNrsData(data: NRSData): VatReturnResponse = { nrsData = data; this } override def errorMappings: PartialFunction[Int, VatResult] = { case 400 if errorCodeIsOneOf(INVALID_VRN) => VatResult.Failure(Status.BAD_REQUEST, Errors.VrnInvalid) case 400 if errorCodeIsOneOf(INVALID_ARN) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 400 if errorCodeIsOneOf(INVALID_ORIGINATOR_ID) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 400 if errorCodeIsOneOf(INVALID_PAYLOAD) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidRequest) case 400 if errorCodeIsOneOf(INVALID_PERIODKEY) => VatResult.Failure(Status.BAD_REQUEST, Errors.InvalidPeriodKey) case 400 if errorCodeIsOneOf(INVALID_SUBMISSION) => logger.info(s"[VatReturnResponse][errorMappings] Des returned error with status 400 and errorCode INVALID_SUBMISSION") VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 403 if errorCodeIsOneOf(DATE_RANGE_TOO_LARGE) => VatResult.Failure(Status.FORBIDDEN, Errors.businessError(Errors.DateRangeTooLarge)) case 403 if errorCodeIsOneOf(VRN_NOT_FOUND, NOT_FOUND_VRN) => VatResult.Failure(Status.INTERNAL_SERVER_ERROR, Errors.InternalServerError) case 403 if errorCodeIsOneOf(INVALID_IDENTIFIER) => VatResult.Failure(Status.NOT_FOUND, Errors.InvalidPeriodKey) case 403 if errorCodeIsOneOf(INVALID_INPUTDATA) => VatResult.Failure(Status.FORBIDDEN, Errors.InvalidRequest) case 403 if errorCodeIsOneOf(TAX_PERIOD_NOT_ENDED) => VatResult.Failure(Status.FORBIDDEN, Errors.TaxPeriodNotEnded) case 409 if errorCodeIsOneOf(DUPLICATE_SUBMISSION) => VatResult.Failure(Status.FORBIDDEN, Errors.businessError(Errors.DuplicateVatSubmission)) } } case class ParseError(msg: String) extends DesTransformError
Example 32
Source File: RoomController.scala From Aton with GNU General Public License v3.0 | 5 votes |
package controllers.admin import com.google.inject.Inject import controllers.{routes => normalroutes} import model.Room import model.json.ResultMessage import play.Logger import play.api.Environment import play.api.i18n.MessagesApi import play.api.libs.json.{JsError, JsSuccess, Json} import services.{LaboratoryService, RoomService, UserService, state} import scala.concurrent.{ExecutionContext, Future} class RoomController @Inject()(roomService: RoomService, laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired { def add = AuthRequiredAction { implicit request => implicit val username = Some(loggedIn.username) Logger.debug("Adding room... ") request.body.asJson match { case Some(json) => json.validate[Room] match { case JsSuccess(room, _) => roomService.add(room).map { case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room added"))) case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that room"))) } case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors)))) } case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson))) } } def update = AuthRequiredAction { implicit request => implicit val username = Some(loggedIn.username) Logger.debug("Updating room... ") request.body.asJson match { case Some(json) => json.validate[Room] match { case JsSuccess(room, _) => roomService.update(room).map { case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Room updated"))) case state.NotFound => NotFound(Json.toJson( ResultMessage("Room not found", Seq(("id", room.id.toString))))) case _ => BadRequest(Json.toJson(new ResultMessage("Could not update that room"))) } case JsError(errors) => Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors)))) } case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson))) } } def delete(roomId: Long) = AuthRequiredAction { implicit request => roomService.delete(roomId).map { case state.ActionCompleted => Redirect(normalroutes.HomeController.home()) case state.NotFound => NotFound case _ => BadRequest } } def blockUser(roomId: Long) = AuthRequiredAction { implicit request => // TODO: Processing Not Yet Implemented val results = for { roomResult <- roomService.get(roomId) } yield roomResult results.map { result: Option[Room] => if (result.isDefined) Redirect(normalroutes.LaboratoryController.get(result.get.laboratoryID)) else NotFound } } }
Example 33
Source File: LaboratoryController.scala From Aton with GNU General Public License v3.0 | 5 votes |
package controllers.admin import com.google.inject.Inject import controllers.{routes => normalroutes} import model.json.{LaboratoryJson, ResultMessage} import model.{Laboratory, Role} import play.Logger import play.api.Environment import play.api.i18n.MessagesApi import play.api.libs.json.{JsError, JsSuccess, Json} import services.{LaboratoryService, UserService, state} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.{ExecutionContext, Future} class LaboratoryController @Inject()(laboratoryService: LaboratoryService, val messagesApi: MessagesApi)(implicit userService: UserService, executionContext: ExecutionContext, environment: Environment) extends ControllerWithAuthRequired { def update = AuthRequiredAction { implicit request => implicit val username = Some(loggedIn.username) implicit val isAdmin = loggedIn.role == Role.Administrator // TODO: Get id from json request.body.asJson match { case Some(json) => json.validate[Laboratory] match { case JsSuccess(laboratory, _) => laboratoryService.update(laboratory).map { case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory updated"))) case state.NotFound => NotFound(Json.toJson(ResultMessage("Laboratory not found",Seq(("id", laboratory.id.toString))))) case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory"))) } case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors)))) } case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson))) } } def add = AuthRequiredAction { implicit request => Logger.debug("Adding laboratory... ") implicit val username = Some(loggedIn.username) implicit val isAdmin = loggedIn.role == Role.Administrator request.body.asJson match { case Some(json) => json.validate[LaboratoryJson] match { case JsSuccess(laboratory, _) => val newLaboratory = Laboratory(0, laboratory.name, laboratory.location, laboratory.administration) laboratoryService.add(newLaboratory).map { case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory added"))) case _ => BadRequest(Json.toJson(new ResultMessage("Could not add that laboratory"))) } case JsError(errors) =>Future.successful(BadRequest(Json.toJson(ResultMessage.wrongJsonFormat(errors)))) } case _ => Future.successful(BadRequest(Json.toJson(ResultMessage.inputWasNotAJson))) } } def delete(id: Long) = AuthRequiredAction { implicit request => laboratoryService.delete(id) map { case state.ActionCompleted => Ok(Json.toJson(new ResultMessage("Laboratory deleted successfully"))) case state.NotFound => NotFound(Json.toJson(new ResultMessage("Laboratory not found"))) case _ => BadRequest(Json.toJson(new ResultMessage("A server problem occurred while trying to delete the laboratory"))) } } }
Example 34
Source File: SelfAssessmentUserType.scala From pertax-frontend with Apache License 2.0 | 5 votes |
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 35
Source File: ThingSpec.scala From swagger-check with MIT License | 5 votes |
package models import de.leanovate.swaggercheck.schema.model.ValidationResult import de.leanovate.swaggercheck.shrinkable.CheckJsValue import org.scalacheck.Arbitrary import org.specs2.ScalaCheck import org.specs2.matcher.MustMatchers import org.specs2.mutable.Specification import play.api.libs.json.{JsSuccess, Json} import support.{Arbitraries, ThingApi} class ThingSpec extends Specification with ScalaCheck with MustMatchers with Arbitraries with ThingApi { "Thing" should { "be receivable" in { implicit val arbitraryJson = Arbitrary[CheckJsValue](swaggerCheck.jsonGenerator("Thing")) prop { json: CheckJsValue => val JsSuccess(thing, path) = Json.parse(json.minified).validate[Thing] path.toString() must be equalTo "" } } "be sendable" in { val verifier = swaggerCheck.jsonVerifier("Thing") prop { thing: Thing => verifier.verify(Json.stringify(Json.toJson(thing))) must be equalTo ValidationResult.success } } } }
Example 36
Source File: KeyFormatTest.scala From naptime with Apache License 2.0 | 5 votes |
package org.coursera.naptime.model import org.coursera.common.jsonformat.JsonFormats import org.coursera.naptime.model.KeyFormatTest.MembershipId import org.junit.Test import org.scalatest.junit.AssertionsForJUnit import play.api.libs.json.JsString import play.api.libs.json.JsSuccess import play.api.libs.json.Json import play.api.libs.json.Reads import org.coursera.common.jsonformat.OrFormats.OrReads import org.coursera.common.stringkey.StringKeyFormat object KeyFormatTest { case class MembershipId(userId: Long, courseId: String) object MembershipId { implicit val stringKeyFormat: StringKeyFormat[MembershipId] = { StringKeyFormat.caseClassFormat((apply _).tupled, unapply) } val reads: Reads[MembershipId] = Json.reads[MembershipId].orReads(JsonFormats.stringKeyFormat[MembershipId]) val keyFormat = KeyFormat.withFallbackReads(reads)(KeyFormat.idAsStringWithFields(Json.format[MembershipId])) } } class KeyFormatTest extends AssertionsForJUnit { @Test def testWithComplexReads(): Unit = { val oldSerialization = Json.obj("userId" -> 12345L, "courseId" -> "machine-learning") val newSerialization = JsString("12345~machine-learning") val expected = JsSuccess(MembershipId(12345L, "machine-learning")) assert(expected === MembershipId.keyFormat.reads(oldSerialization)) assert(expected === MembershipId.keyFormat.reads(newSerialization)) } }
Example 37
Source File: AttributesProvider.scala From naptime with Apache License 2.0 | 5 votes |
package org.coursera.naptime.router2 import com.typesafe.scalalogging.StrictLogging import org.coursera.courier.templates.DataTemplates.DataConversion import org.coursera.naptime.courier.CourierFormats import org.coursera.naptime.schema.Attribute import org.coursera.naptime.schema.JsValue import play.api.libs.json.JsError import play.api.libs.json.JsObject import play.api.libs.json.JsSuccess import play.api.libs.json.Json import scala.util.control.NonFatal object AttributesProvider extends StrictLogging { val SCALADOC_ATTRIBUTE_NAME = "scaladocs" lazy val scaladocs: Map[String, JsObject] = { val scaladocPath = "/naptime.scaladoc.json" (for { stream <- Option(getClass.getResourceAsStream(scaladocPath)) json <- try { Some(Json.parse(stream)) } catch { case NonFatal(exception) => logger.warn( s"Could not parse contents of file " + s"$scaladocPath as JSON") None } finally { stream.close() } scaladocCollection <- json.validate[Map[String, JsObject]] match { case JsSuccess(deserialized, _) => Some(deserialized) case JsError(_) => logger.warn( s"Could not deserialize contents of file " + s"$scaladocPath as `Map[String, JsObject]`") None } } yield { scaladocCollection }).getOrElse(Map.empty) } def getResourceAttributes(className: String): Seq[Attribute] = { scaladocs .get(className) .map(value => Attribute(SCALADOC_ATTRIBUTE_NAME, Some(jsObjToJsValue(value)))) .toList } def getMethodAttributes(className: String, methodName: String): Seq[Attribute] = { scaladocs .get(s"$className.$methodName") .map(value => Attribute(SCALADOC_ATTRIBUTE_NAME, Some(jsObjToJsValue(value)))) .toList } private[this] def jsObjToJsValue(jsObj: JsObject): JsValue = { JsValue.build(CourierFormats.objToDataMap(jsObj), DataConversion.SetReadOnly) } }
Example 38
Source File: BitcoinerLiveFeeRateProvider.scala From bitcoin-s with MIT License | 5 votes |
package org.bitcoins.feeprovider import akka.actor.ActorSystem import akka.http.scaladsl.model.Uri import org.bitcoins.commons.jsonmodels.wallet.BitcoinerLiveResult import org.bitcoins.commons.serializers.JsonSerializers._ import org.bitcoins.core.wallet.fee.SatoshisPerVirtualByte import play.api.libs.json.{JsError, JsSuccess, Json} import scala.util.{Failure, Success, Try} case class BitcoinerLiveFeeRateProvider(minutes: Int)(implicit override val system: ActorSystem) extends CachedHttpFeeRateProvider { private val bitcoinerLiveValidMinutes = Vector(30, 60, 120, 180, 360, 720, 1440) require( bitcoinerLiveValidMinutes.contains(minutes), s"$minutes is not a valid selection, must be from $bitcoinerLiveValidMinutes") override val uri: Uri = Uri("https://bitcoiner.live/api/fees/estimates/latest") override def converter(str: String): Try[SatoshisPerVirtualByte] = { val json = Json.parse(str) json.validate[BitcoinerLiveResult] match { case JsSuccess(response, _) => Success(response.estimates(minutes).sat_per_vbyte) case JsError(error) => Failure( new RuntimeException( s"Unexpected error when parsing response: $error")) } } }
Example 39
Source File: PersistentJsonSpec.scala From kafka-journal with MIT License | 5 votes |
package akka.persistence.kafka.journal import cats.implicits._ import com.evolutiongaming.kafka.journal.PayloadType import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import play.api.libs.json.{JsSuccess, Json} class PersistentJsonSpec extends AnyFunSuite with Matchers { for { payloadType <- List(PayloadType.Json.some, PayloadType.Text.some, none) manifest <- List(none, "manifest".some, "".some) } { test(s"toJson & fromJson, payloadType: $payloadType, manifest: $manifest") { val persistent = PersistentJson( manifest = manifest, writerUuid = "writerUuid", payloadType = payloadType, payload = "payload") val json = Json.toJson(persistent) json.validate[PersistentJson[String]] shouldEqual JsSuccess(persistent) } } }
Example 40
Source File: NonBlankStringSpec.scala From play-ui with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.binders import org.scalatest.{Matchers, WordSpecLike} import play.api.libs.json.{JsError, JsString, JsSuccess, Json} class NonBlankStringSpec extends WordSpecLike with Matchers { "Creating a NonBlankString" should { "throw an exception for a blank string" in { an[IllegalArgumentException] should be thrownBy NonBlankString("") } "give an error for a null string" in { an[IllegalArgumentException] should be thrownBy NonBlankString(null) } "give a success for a non-blank string" in { NonBlankString("x") } } "Reading a NonBlankString" should { "give an error for a blank string" in { validating("") shouldBe a[JsError] } "give an error for a null string" in { validating(null) shouldBe a[JsError] } "give a success for a non-blank string" in { validating("x") should be(JsSuccess(NonBlankString("x"))) } def validating(s: String) = JsString(s).validate[NonBlankString] } "Writing a NonBlankString" should { "just include the value" in { Json.toJson(NonBlankString("x")) should be(JsString("x")) } } "Binding from a query string" should { "give an error for a blank string" in { binding("") shouldBe Some(Left("String was blank")) } "give an error for a null string" in { binding(null) shouldBe Some(Left("String was blank")) } "give a success for a non-blank string" in { binding("x") shouldBe Some(Right(NonBlankString("x"))) } def binding(s: String) = NonBlankString.stringToNonBlankString.bind("v", Map("v" -> Seq(s))) } "Unbinding to a query string" should { "extract the value" in { unbinding(NonBlankString("something")) shouldBe "something" } def unbinding(n: NonBlankString) = NonBlankString.stringToNonBlankString.unbind("v", n) } }
Example 41
Source File: RestFormatsSpec.scala From http-verbs with Apache License 2.0 | 5 votes |
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 42
Source File: MillinerHatSignup.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.resourceManagement import org.hatdex.hat.resourceManagement.models.HatSignup import play.api.cache.AsyncCacheApi import play.api.http.Status._ import play.api.libs.json.{ JsError, JsSuccess } import play.api.libs.ws.{ WSClient, WSRequest, WSResponse } import play.api.{ Configuration, Logger } import scala.concurrent.duration._ import scala.concurrent.{ ExecutionContext, Future } trait MillinerHatSignup { val logger: Logger val ws: WSClient val configuration: Configuration val schema: String = configuration.get[String]("resourceManagement.millinerAddress") match { case address if address.startsWith("https") => "https://" case address if address.startsWith("http") => "http://" case _ => "https://" } val millinerAddress: String = configuration.get[String]("resourceManagement.millinerAddress") .stripPrefix("http://") .stripPrefix("https://") val hatSharedSecret: String = configuration.get[String]("resourceManagement.hatSharedSecret") val cache: AsyncCacheApi def getHatSignup(hatAddress: String)(implicit ec: ExecutionContext): Future[HatSignup] = { // Cache the signup information for subsequent calls (For private/public key and database details) cache.getOrElseUpdate[HatSignup](s"configuration:$hatAddress") { val request: WSRequest = ws.url(s"$schema$millinerAddress/api/manage/configuration/$hatAddress") .withVirtualHost(millinerAddress) .withHttpHeaders("Accept" -> "application/json", "X-Auth-Token" -> hatSharedSecret) val futureResponse: Future[WSResponse] = request.get() futureResponse.map { response => response.status match { case OK => response.json.validate[HatSignup] match { case signup: JsSuccess[HatSignup] => logger.debug(s"Got back configuration: ${signup.value}") cache.set(s"configuration:$hatAddress", signup.value, 1.minute) signup.value case e: JsError => logger.error(s"Parsing HAT configuration failed: $e") throw new HatServerDiscoveryException("Fetching HAT configuration failed") } case _ => logger.error(s"Fetching HAT configuration failed: ${response.body}") throw new HatServerDiscoveryException("Fetching HAT configuration failed") } } } } }
Example 43
Source File: UberMappers.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.she.mappers import java.util.UUID import org.hatdex.hat.api.models.{ EndpointQuery, EndpointQueryFilter, FilterOperator, PropertyQuery } import org.hatdex.hat.api.models.applications.{ DataFeedItem, DataFeedItemContent, DataFeedItemLocation, DataFeedItemTitle, LocationGeo } import org.hatdex.hat.she.models.StaticDataValues import org.joda.time.DateTime import play.api.libs.json.{ JsError, JsSuccess, JsValue, Json } import scala.util.Try class UberRidesMapper extends DataEndpointMapper { override protected val dataDeduplicationField: Option[String] = Some("request_id") def dataQueries(fromDate: Option[DateTime], untilDate: Option[DateTime]): Seq[PropertyQuery] = { val unixDateFilter = fromDate.flatMap { _ => Some(FilterOperator.Between(Json.toJson(fromDate.map(t => t.getMillis / 1000)), Json.toJson(untilDate.map(t => t.getMillis / 1000)))) } Seq(PropertyQuery( List(EndpointQuery("uber/rides", None, unixDateFilter.map(f ⇒ Seq(EndpointQueryFilter("start_time", None, f))), None)), Some("start_time"), Some("descending"), None)) } def mapDataRecord(recordId: UUID, content: JsValue, tailRecordId: Option[UUID] = None, tailContent: Option[JsValue] = None): Try[DataFeedItem] = { logger.debug(s"uber content: $content") for { distance <- Try((content \ "distance").asOpt[Double].getOrElse(0.doubleValue()).toString) startDate <- Try(new DateTime((content \ "start_time").as[Long] * 1000.longValue())) durationSeconds ← Try((content \ "end_time").asOpt[Int].getOrElse(0) - (content \ "start_time").asOpt[Int].getOrElse(0)) duration <- Try { val m = (durationSeconds / 60) % 60 val h = (durationSeconds / 60 / 60) % 24 "%02d h %02d min".format(h, m) } title ← Try(DataFeedItemTitle(s"Your trip on ${startDate.toString("dd/MM/YYYY")}", None, None)) itemContent ← Try(DataFeedItemContent( Some( s"""${(content \ "start_city" \ "display_name").asOpt[String].getOrElse("Unknown City")}, |${BigDecimal.decimal(distance.toFloat).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble} miles, |${duration}""".stripMargin), None, None, None)) latitude <- Try((content \ "start_city" \ "latitude").asOpt[Double].getOrElse(0.doubleValue())) longitude <- Try((content \ "start_city" \ "longitude").asOpt[Double].getOrElse(0.doubleValue())) location <- Try(DataFeedItemLocation(Some(LocationGeo(longitude, latitude)), None, None)) } yield DataFeedItem("uber", startDate, Seq(), Some(title), Some(itemContent), Some(location)) } } class UberProfileStaticDataMapper extends StaticDataEndpointMapper { def dataQueries(): Seq[PropertyQuery] = { Seq(PropertyQuery( List( EndpointQuery("uber/profile", None, None, None)), Some("dateCreated"), Some("descending"), Some(1))) } def mapDataRecord(recordId: UUID, content: JsValue, endpoint: String): Seq[StaticDataValues] = { val eventualData = content.validate[Map[String, JsValue]] eventualData match { case JsSuccess(value, _) => val lastPartOfEndpointString = endpoint.split("/").last Seq(StaticDataValues(lastPartOfEndpointString, value)) case e: JsError => logger.error(s"Couldn't validate static data JSON for $endpoint. $e") Seq() } } }