本文整理汇总了Scala中play.api.libs.json.JsSuccess类的典型用法代码示例。如果您正苦于以下问题:Scala JsSuccess类的具体用法?Scala JsSuccess怎么用?Scala JsSuccess使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsSuccess类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: PermissionsViaHttpAuthorizer
//设置package包名称以及导入依赖的类
package auth.http.service.impl.authorization.impl
import auth.core.model.core.{Permission, PermissionToUser, User}
import auth.core.service.authorization.{PermissionAuthorization, PermissionsAuthorizer}
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import play.api.Configuration
import play.api.libs.json.{JsError, JsSuccess}
import play.api.libs.ws.WSClient
import play.api.mvc.Request
import scala.concurrent.{ExecutionContext, Future}
import play.api.Logger
class PermissionsViaHttpAuthorizer(configuration: Configuration, ws: WSClient)(
implicit ec: ExecutionContext)
extends PermissionsAuthorizer {
import auth.core.formatting.core.Rest._
private val logger = Logger(this.getClass)
private val endpoint = configuration.underlying.getString("auth.http.user-service.url")
private def uri(uuid: String): String = s"$endpoint/users/$uuid/permissions"
override def require(required: Permission): PermissionAuthorization[JWTAuthenticator] =
new PermissionAuthorization[JWTAuthenticator] {
override def isAuthorized[B](identity: User, authenticator: JWTAuthenticator)(
implicit request: Request[B]): Future[Boolean] = {
val endpoint = uri(identity.uuid.toString)
val f = ws.url(endpoint).get().map { resp ?
val permissions = resp.json.validate[Seq[PermissionToUser]]
permissions match {
case JsSuccess(ps, _) ?
ps.map(_.permission).contains(required)
case JsError(e) ?
logger.error(e.mkString("\n"))
false
}
}
logError(f, endpoint)
f
}
}
@inline private def logError[A](f: Future[_], endpoint: String): Unit =
f.onFailure {
case e: Throwable ?
logger.error(s"Error during request to $endpoint", e)
}
}
示例2: Status
//设置package包名称以及导入依赖的类
package domain
import play.api.libs.json.{Format, JsString, JsSuccess, JsValue}
object Status extends Enumeration {
type Status = Value
val Inactive = Value(1, "Inactive")
val Active = Value(2, "Active")
val Deleted = Value(3, "Deleted")
implicit val myEnumFormat = new Format[Status] {
def reads(json: JsValue) = JsSuccess(Status.withName(json.as[String]))
def writes(myEnum: Status) = JsString(myEnum.toString)
}
}
示例3: EstadoPedido
//设置package包名称以及导入依赖的类
package domain
import play.api.libs.json.{Format, JsString, JsSuccess, JsValue}
object EstadoPedido extends Enumeration {
type EstadoPedido = Value
val Generado = Value(1, "Generado")
val Pendiente = Value(2, "Pendiente")
val Confeccionado = Value(3, "Confeccionado")
val Entregado = Value(4, "Entregado")
val Cancelado = Value(5, "Cancelado")
implicit val myEnumFormat = new Format[EstadoPedido] {
def reads(json: JsValue) = JsSuccess(EstadoPedido.withName(json.as[String]))
def writes(myEnum: EstadoPedido) = JsString(myEnum.toString)
}
}
示例4: Categoria
//设置package包名称以及导入依赖的类
package domain
import play.api.libs.json.{Format, JsString, JsSuccess, JsValue}
object Categoria extends Enumeration {
type Categoria = Value
val Entradas = Value(1, "Entradas")
val PlatosPrincipales = Value(2, "PlatosPrincipales")
val Postres = Value(3, "Postres")
val Bebidas = Value(4, "Bebidas")
val Cafeteria = Value(5, "Cafeteria")
implicit val myEnumFormat = new Format[Categoria] {
def reads(json: JsValue) = JsSuccess(Categoria.withName(json.as[String]))
def writes(myEnum: Categoria) = JsString(myEnum.toString)
}
}
示例5: AuthenticatedRequest
//设置package包名称以及导入依赖的类
package controllers
import java.util.UUID
import javax.inject.Inject
import models.Account
import pdi.jwt.{JwtAlgorithm, JwtJson}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc._
import repositories.AccountRepository
import utils.{Conf, Log}
import scala.concurrent.Future
import scala.util.{Failure, Success}
case class AuthenticatedRequest[A](account: Account, request: Request[A]) extends WrappedRequest[A](request)
class AuthenticationActionService @Inject()(conf: Conf, accountRepository: AccountRepository) extends Log {
val key = conf.cryptoKey
object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] {
override def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
val errorResponse = Json.obj("error" -> "Unauthorized")
request.headers.get("Authorization")
.orElse(request.getQueryString("token"))
.orElse(request.cookies.get("token").map(_.value))
.orElse(request.session.get("token")) match {
case Some(token) =>
logger.debug(s"${request.toString()} Authorization=$token")
JwtJson.decodeJson(token, key, Seq(JwtAlgorithm.HS256)) match {
case Success(json) =>
(json \ "user_id").validate[UUID] match {
case s: JsSuccess[UUID] =>
accountRepository.getByUUID(s.get) match {
case Some(user) =>
logger.debug(s"${request.toString()} user=$user")
block(AuthenticatedRequest(user, request))
case None =>
logger.error(s"Unauthorized: User not found with id=${s.get}")
Future.successful(Results.Unauthorized(errorResponse))
}
case e: JsError =>
logger.error(s"Unauthorized: Jwt decode Json error $e")
Future.successful(Results.Unauthorized(errorResponse))
}
case Failure(e) =>
logger.error(s"Unauthorized: Jwt decode Json error", e)
Future.successful(Results.Unauthorized(errorResponse))
}
case None =>
logger.error(s"Unauthorized: Missing token in Authorization header | cookies | session | query string")
Future.successful(Results.Unauthorized(errorResponse))
}
}
}
}
示例6: ReceivedMessageConverters
//设置package包名称以及导入依赖的类
package infrastructures.common
import com.amazonaws.services.sqs.model.Message
import domain.common.{ MessageToken, ProcessableMessage, ReceivedMessage, UnprocessableMessage }
import play.api.libs.json.{ JsError, JsSuccess, Json, Reads }
object ReceivedMessageConverters {
def toReceivedMessage[T](message: Message)(implicit reads: Reads[T]): ReceivedMessage[T] = {
val json = Json.parse(message.getBody)
val result = Json.fromJson(json)
val token = MessageToken(message.getReceiptHandle)
result match {
case JsSuccess(t, _) => ProcessableMessage(t, token)
case JsError(e) =>
val errorMessage = s"messageId: ${ message.getMessageId }, reason: ${ Json.stringify(JsError.toJson(e)) }"
UnprocessableMessage(new IllegalArgumentException(errorMessage), token)
}
}
}
示例7: OAuth2Success
//设置package包名称以及导入依赖的类
package org.zalando.hutmann.authentication
import play.api.Logger
import play.api.libs.json.{ JsError, JsSuccess, JsValue }
trait OAuth2Response
final case class OAuth2Success[T <: OAuth2User](user: T) extends OAuth2Response
final case class OAuth2Failure[T <: OAuth2Error](failure: T) extends OAuth2Response
object OAuth2Response {
implicit val userFormat = User.app2AppUserReader
implicit val errorFormat = AuthError.format
def fromJson(json: JsValue): OAuth2Response = {
json.validate[User] match {
case JsSuccess(user, _) => OAuth2Success(user)
case JsError(error) =>
json.validate[AuthError] match {
case JsSuccess(failure, _) => OAuth2Failure(failure)
case JsError(fail) =>
Logger.warn("Failed to parse oauth response from auth server")
OAuth2Failure(AuthError("Parser failed", "Failed to parse response from OAuth server."))
}
}
}
}
示例8: SprayHttpResponse
//设置package包名称以及导入依赖的类
package mesosphere.marathon.integration.setup
import play.api.libs.json.{ JsError, JsSuccess, Json, Reads }
import spray.http.HttpResponse
import scala.reflect.ClassTag
object SprayHttpResponse {
def read[T](implicit reads: Reads[T], classTag: ClassTag[T]): HttpResponse => RestResult[T] = responseResult.andThen { result =>
result.map(_ => Json.fromJson(result.entityJson)).map {
case JsSuccess(value, _) => value
case JsError(errors) =>
throw new IllegalArgumentException(
s"could not parse as $classTag:\n${Json.prettyPrint(result.entityJson)}\nErrors:\n${errors.mkString("\n")}")
}
}
def responseResult: HttpResponse => RestResult[HttpResponse] = response => RestResult(response)
}
示例9: OwnersEndpoint
//设置package包名称以及导入依赖的类
package com.github.mszarlinski.playframework.petclinic.owners.port.adapters.rest
import javax.inject.{Inject, Singleton}
import com.github.mszarlinski.playframework.petclinic.owners.domain.{Owner, OwnerRepository}
import play.api.libs.json.JsSuccess
import play.api.libs.json.Json._
import play.api.mvc.{Action, BodyParsers, Controller}
@Singleton
class OwnersEndpoint @Inject()(ownerRepository: OwnerRepository)(implicit ownerFormatter: OwnerFormatter) extends Controller {
def getOwners = Action {
val owners = ownerRepository.findAll()
Ok(toJson(owners))
}
def saveOwner = Action(BodyParsers.parse.json) { req =>
req.body.validate[Owner] match {// TODO: fold
case owner: JsSuccess[Owner] =>
val saved = ownerRepository.save(owner.get)
Ok(toJson(saved))
case _ => BadRequest
}
}
}
示例10: GoogleRequest
//设置package包名称以及导入依赖的类
package google4s.request
import http.client.method.HttpMethod
import http.client.request._
import http.client.response.{HttpHeader, HttpResponse}
import play.api.libs.json.JsSuccess
case class GoogleRequest(
override val baseUrl: String,
override val relativeUrl: String,
override val method: HttpMethod,
override val headers: Seq[HttpHeader] = Seq.empty,
_queryString: Map[String, Seq[String]] = Map.empty,
override val body: Option[Array[Byte]] = None,
accessToken: String,
paginated: Boolean = false,
customCompletionEvaluator: Option[CompletionEvaluation] = None)
extends PaginatedHttpRequest[GoogleRequest] {
// TODO: make accessToken an option
override val queryString = if (accessToken.isEmpty) _queryString else _queryString + ("access_token" ? Seq(accessToken))
override def toJson(extraQueryStringParams: Map[String, Seq[String]]): String = "{}"
override val completionEvaluator = if (paginated) {
customCompletionEvaluator match {
case Some(c) ? OrElseCompletionEvaluation(customCompletionEvaluator.get, TrueCompletionEvaluation)
case _ ? GoogleEmptyNextLinkCompletionEvaluation
}
} else TrueCompletionEvaluation
override def nextRequest(response: HttpResponse): GoogleRequest = {
(response.json \ "nextLink").validate[String] match {
case s: JsSuccess[String] ?
copy(_queryString =
s.get
.split("\\?")
.last.split("&")
.map { x ?
val keyVal = x.split("=")
(keyVal.head, keyVal.tail.toSeq)
}.toMap ++ Map("access_token" ? Seq(accessToken)))
case _ ?
println(s"OH NO! Could not find nextLink in ${response.json.toString}")
???
}
}
}
示例11: Application
//设置package包名称以及导入依赖的类
package controllers
import com.google.inject.Inject
import dao._
import models.{Cat, Dog}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc._
import scala.concurrent.Future
class Application @Inject() (catDao: CatDAO, dogDao: DogDAO) extends Controller {
def info = Action { implicit request =>
???
}
def findAllAnimals = Action.async { implicit request =>
catDao.all().zip(dogDao.all()).map {
case (cats, dogs) =>
val catsJson = Json.toJson(cats)
val dogsJson = Json.toJson(dogs)
Ok(Json.obj(
"cats" -> catsJson,
"dogs" -> dogsJson
))
}
}
def insertCat = Action.async(parse.json) { implicit request =>
request.body.validate[Cat] match {
case JsSuccess(cat, path) =>
catDao.insert(cat).map(_ => Ok(Json.obj("msg" -> "Cat was inserted")))
case JsError(err) =>
Future.successful(BadRequest(Json.obj("msg" -> err.mkString("\n"))))
}
}
def insertDog = Action.async(parse.json) { implicit request =>
request.body.validate[Dog] match {
case JsSuccess(dog, path) =>
dogDao.insert(dog).map(_ => Ok(Json.obj("msg" -> "Dog was inserted")))
case JsError(err) =>
Future.successful(BadRequest(Json.obj("msg" -> err.mkString("\n"))))
}
}
}
示例12: allPlaylists
//设置package包名称以及导入依赖的类
package services
import com.google.inject.{Inject, Singleton}
import play.api.libs.json.{JsError, JsSuccess}
import services.spotify.SpotifyClient
import services.spotify.response.{SpotifyPlaylists, SpotifyTrack, SpotifyTrackList}
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext
trait PlaylistService {
def allPlaylists(accessToken: String): Future[Option[SpotifyPlaylists]]
def getPlaylistDiff(accessToken: String, userId: String, playlistIds: List[String]): Future[SpotifyTrackList]
}
@Singleton
class Playlists @Inject()(client: SpotifyClient) extends PlaylistService {
override def allPlaylists(accessToken: String): Future[Option[SpotifyPlaylists]] = {
client.fetchUsersPlaylist(accessToken).map {
case JsSuccess(playlist, _) => Some(playlist)
case JsError(_) => None
}
}
override def getPlaylistDiff(accessToken: String,
userId: String,
playlistIds: List[String]): Future[SpotifyTrackList] = {
val fetchTracks = client.fetchPlaylistTracks(accessToken, userId, _: String)
val futures = playlistIds.map(fetchTracks)
Future
.sequence(futures)
.map(list => list.map(trackList => trackList.items.toSet))
.map(items => items.reduce((a, b) => a.intersect(b)))
.map(tracks => SpotifyTrackList(tracks.toList))
}
}
示例13: EventDao
//设置package包名称以及导入依赖的类
package dao
import akka.NotUsed
import akka.stream.{Materializer, OverflowStrategy, QueueOfferResult}
import akka.stream.scaladsl.{Flow, Keep, Sink, Source, SourceQueueWithComplete}
import org.reactivestreams.Publisher
import play.api.libs.json.{Format, JsSuccess, Json}
import scala.concurrent.Future
abstract class EventDao[Event](
implicit val mat: Materializer,
format: Format[Event]) {
def store(str: Event): Future[QueueOfferResult] =
in.offer(str)
val (
in: SourceQueueWithComplete[Event],
out: Publisher[Event]
) =
Source
.queue[Event](3, OverflowStrategy.backpressure)
.map(Json.toJson(_))
.map(Json.stringify)
.via(eventStore)
.map(Json.parse)
.map(Json.fromJson[Event])
.collect { case JsSuccess(event, _) => event }
.toMat(Sink.asPublisher(fanout = true))(Keep.both)
.run()
protected def eventStore: Flow[String, String, NotUsed]
}
示例14: WateringListener
//设置package包名称以及导入依赖的类
package mqtt.watering
import java.time.Clock
import akka.actor.Actor
import model._
import model.sensor.{BooleanMeasurementAggregationStrategy, IdentityMeasurementAggregationStrategy, Measurement, SensorRepository}
import mqtt.MqttListenerMessage.{ConsumeMessage, Ping}
import play.api.Logger
import play.api.libs.json.{JsError, JsSuccess, Json}
class WateringListener(
locationRepository: LocationRepository,
sensorRepository: SensorRepository,
clock: Clock
) extends Actor {
val topic = "home/watering/ibisek/telemetry".r
override def receive(): Receive = {
case Ping => ()
case ConsumeMessage(receivedTopic: String, message: String) => receivedTopic match {
case topic() => Json.fromJson(Json.parse(message))(WateringMessage.wmReads) match {
case JsSuccess(value, _) =>
val locationAddress = "watering-ibiscus"
val location = locationRepository.findOrCreateLocation(locationAddress)
val foundSensor = sensorRepository.findOrCreateSensor(
location = location,
name = "watering"
)
foundSensor.addMeasurement(
Measurement(
measureTimestamp = clock.instant(),
value = value.telemetry.humidity.actual
),
foundSensor.findOrCreatePhenomenon("humidity", "", IdentityMeasurementAggregationStrategy)
)
foundSensor.addMeasurement(
Measurement(
measureTimestamp = clock.instant(),
value = if(value.telemetry.watering.inProgress) 10.0 else 0.0
),
foundSensor.findOrCreatePhenomenon("watering", "", BooleanMeasurementAggregationStrategy)
)
foundSensor.addMeasurement(
Measurement(
measureTimestamp = clock.instant(),
value = value.telemetry.humidity.baseLine
),
foundSensor.findOrCreatePhenomenon("baseLine", "", IdentityMeasurementAggregationStrategy)
)
case JsError(_) => Logger.error(s"Parsing $message failed");
}
case _ =>
}
}
}
示例15: QuestionService
//设置package包名称以及导入依赖的类
package fi.kajstrom.efpscala.E57
import fi.kajstrom.efpscala.Util.FilePath
import play.api.libs.json.{JsError, JsSuccess, Json}
import scala.io.Source
class QuestionService(filename: String) {
def getQuestions: Seq[Question] = {
val pathString = FilePath.makeResourcePath(filename)
val jsonString = Source.fromFile(pathString).mkString
val json = Json.parse(jsonString)
json.validate[Seq[Question]] match {
case s: JsSuccess[Seq[Question]] => s.get
case e: JsError => Seq()
}
}
}