• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala JsSuccess类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.libs.json.JsSuccess的典型用法代码示例。如果您正苦于以下问题:Scala JsSuccess类的具体用法?Scala JsSuccess怎么用?Scala JsSuccess使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了JsSuccess类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
    }
} 
开发者ID:KadekM,项目名称:play-slick-silhouette-auth-api,代码行数:51,代码来源:PermissionsViaHttpAuthorizer.scala


示例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)
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:17,代码来源:Status.scala


示例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)
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:19,代码来源:EstadoPedido.scala


示例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)
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:19,代码来源:Categoria.scala


示例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))
      }
    }
  }
} 
开发者ID:Cumulus-Cloud,项目名称:cumulus,代码行数:57,代码来源:AuthenticationActionService.scala


示例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)
    }
  }
} 
开发者ID:cm-wada-yusuke,项目名称:ecn-news,代码行数:21,代码来源:ReceivedMessageConverters.scala


示例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."))
        }
    }
  }
} 
开发者ID:zalando-incubator,项目名称:hutmann,代码行数:28,代码来源:OAuth2Response.scala


示例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)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:19,代码来源:SprayHttpResponse.scala


示例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
    }
  }
} 
开发者ID:mszarlinski,项目名称:play-clinic,代码行数:28,代码来源:OwnersEndpoint.scala


示例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}")
        ???
    }
  }
} 
开发者ID:SocialOrra,项目名称:social4s,代码行数:48,代码来源:GoogleRequest.scala


示例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"))))
    }
  }

} 
开发者ID:kpmeen,项目名称:play-slick-pgsql,代码行数:51,代码来源:Application.scala


示例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))

  }
} 
开发者ID:sytakeris,项目名称:magic-suite,代码行数:39,代码来源:Playlists.scala


示例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]
} 
开发者ID:leanovate,项目名称:contoso-conference-manager,代码行数:35,代码来源:EventDao.scala


示例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 _ =>
    }
  }
} 
开发者ID:vavravl1,项目名称:home_center,代码行数:58,代码来源:WateringListener.scala


示例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()
    }
  }
} 
开发者ID:kajstrom,项目名称:EFP-Scala,代码行数:21,代码来源:QuestionService.scala


示例16: channelByPath

//设置package包名称以及导入依赖的类
package de.welt.contentapi.client.services.configuration

import javax.inject.{Inject, Singleton}

import de.welt.contentapi.core.models.config
import de.welt.contentapi.core.models.config.{Channel, ChannelData, ChannelId, Env}
import de.welt.contentapi.client.services.contentapi.LegacySectionService
import de.welt.contentapi.client.services.s3.S3
import de.welt.contentapi.core.traits.Loggable
import play.api.cache.CacheApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.{Environment, Mode}

import scala.concurrent.duration._

trait SectionConfigurationService {

  def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel]

}

@Singleton
class SectionConfigurationServiceImpl @Inject()(funkConfig: ContentClientConfig,
                                                s3: S3,
                                                environment: Environment,
                                                legacySectionService: LegacySectionService,
                                                cache: CacheApi)
  extends SectionConfigurationService with Loggable {

  override def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel] = {
    root.findByPath(id.path)
  }

  private def objectKeyForEnv(env: Env) = environment.mode match {
    case Mode.Prod ? s"janus2/prod/${env.toString}/config.json"
    case _ ? s"janus2/dev/${env.toString}/config.json"
  }

  private[configuration] def root(implicit env: Env): Channel = cache.getOrElse(env.toString, 10.minutes) {
    import config.WithChildrenReads._

    val maybeData: Option[String] = s3.get(funkConfig.aws.s3.janus.bucket, objectKeyForEnv(env))

    maybeData
      .map { data ? Json.parse(data).validate[Channel] }
      .flatMap {
        case JsSuccess(v, _) ?
          Some(v)
        case [email protected](_) ?
          log.warn(err.toString)
          None
      }.getOrElse {
      log.warn("No data found in s3 bucket.")
      throw new IllegalStateException("no channel data")
    }

  }
} 
开发者ID:WeltN24-public,项目名称:WeltContentApiClient,代码行数:59,代码来源:SectionConfigurationService.scala


示例17: channelByPath

//设置package包名称以及导入依赖的类
package de.welt.services.configuration

import javax.inject.{Inject, Singleton}

import de.welt.models.config
import de.welt.models.config.{Channel, ChannelData, ChannelId, Env}
import de.welt.services.contentapi.LegacySectionService
import de.welt.services.s3.S3
import de.welt.traits.Loggable
import play.api.cache.CacheApi
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.{Environment, Mode}

import scala.concurrent.duration._

trait SectionConfigurationService {

  def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel]

}

@Singleton
class SectionConfigurationServiceImpl @Inject()(funkConfig: ContentClientConfig,
                                                s3: S3,
                                                environment: Environment,
                                                legacySectionService: LegacySectionService,
                                                cache: CacheApi)
  extends SectionConfigurationService with Loggable {

  override def channelByPath(id: ChannelId)(implicit env: Env): Option[Channel] = {
    root.findByPath(id.path)
  }

  private def objectKeyForEnv(env: Env) = environment.mode match {
    case Mode.Prod ? s"janus2/prod/${env.toString}/config.json"
    case _ ? s"janus2/dev/${env.toString}/config.json"
  }

  private[configuration] def root(implicit env: Env): Channel = cache.getOrElse(env.toString, 10.minutes) {
    import config.WithChildrenReads._

    val maybeData: Option[String] = s3.get(funkConfig.aws.s3.janus.bucket, objectKeyForEnv(env))

    maybeData
      .map { data ? Json.parse(data).validate[Channel] }
      .flatMap {
        case JsSuccess(v, _) ?
          Some(v)
        case [email protected](_) ?
          log.warn(err.toString)
          None
      }.getOrElse {
      log.warn("No data found in s3 bucket.")
      throw new IllegalStateException("no channel data")
    }

  }
} 
开发者ID:WeltN24-public,项目名称:WeltContentApiClient,代码行数:59,代码来源:SectionConfigurationService.scala


示例18: UserController

//设置package包名称以及导入依赖的类
package entrypoint

import javax.inject.Inject

import access.{AuthenticatedActionCreator, JWTAlgorithmProvider, JWTPublicKeyProvider}
import com.eigenroute.time.TimeProvider
import play.api.Configuration
import play.api.libs.json.{JsSuccess, Json}
import play.api.mvc.{Action, Controller, Result}
import user.ChangePasswordMessage

class UserController @Inject()(
    override val authenticationAPI: AuthenticationAPI,
    override val jWTAlgorithmProvider: JWTAlgorithmProvider,
    override val jWTPublicKeyProvider: JWTPublicKeyProvider,
    override val timeProvider: TimeProvider,
    override val configuration: Configuration,
    userAPI:UserAPI
  )
  extends Controller
  with AuthenticatedActionCreator {

  def changePassword() = AuthenticatedAction(parse.json) { request =>
    request.body.validate[ChangePasswordMessage] match {
      case successChangePasswordMessage:JsSuccess[ChangePasswordMessage] =>
        userAPI.changePassword(request.userId, successChangePasswordMessage.get)
        .toOption.fold[Result](Ok(Json.obj("status" -> "password change failed")))( user =>
          Ok(Json.obj("status" -> "success"))
        )
      case _ =>
        Ok(Json.obj("status" -> "invalid data"))
    }
  }

  def unauthorized = Action {
    Unauthorized
  }

} 
开发者ID:shafiquejamal,项目名称:api-gateway-template,代码行数:40,代码来源:UserController.scala


示例19: Project

//设置package包名称以及导入依赖的类
package models

import javax.inject.Inject

import akka.actor.ActorRef
import akka.stream.scaladsl.Source
import akka.util.Timeout
import com.github.jeroenr.bson.BsonDocument
import com.github.jeroenr.bson.BsonDsl._
import helpers.BsonDocumentHelper._
import play.api.libs.json.{JsResult, JsSuccess, Json}
import play.api.modules.tepkinmongo.TepkinMongoApi

import scala.concurrent.Future
import scala.concurrent.duration._

case class Project(_id: String, name: String)

object Project {
  implicit val projectFormatter = Json.format[Project]
  def apply(bson: BsonDocument): JsResult[Project] = {
    Json.fromJson[Project](bson)
  }

  def toBsonDocument(project: Project): BsonDocument =
    ("_id" := project._id) ~
      ("name" := project.name)
}


class ProjectRepo @Inject() (tepkinMongoApi: TepkinMongoApi) {
  implicit val ec = tepkinMongoApi.client.ec
  implicit val timeout: Timeout = 5.seconds

  val projects = tepkinMongoApi.client("tepkin")("projects")

  def create(name: String): Future[Boolean] = {
    val project = "name" := name
    projects.insert(project).map(_.ok)
  }

  def all: Source[List[Project], ActorRef] = {
    projects.find(new BsonDocument()).map(l => l.map(Project(_)).collect {
      case JsSuccess(p, _ ) => p
    })
  }

  def insert(ps: List[Project]) =
    projects.insert(ps.map(Project.toBsonDocument))

  def findByName(name: String): Future[Option[Project]] = {
    val byId = "name" := name
    projects.findOne(byId).map(_.flatMap(Project(_).asOpt))
  }


} 
开发者ID:jonasanso,项目名称:play-tepkin-mongo,代码行数:58,代码来源:Project.scala


示例20: Application

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import akka.stream.scaladsl.Flow
import akka.util.ByteString
import models.{Project, ProjectRepo}
import play.api.http.HttpEntity.Streamed
import play.api.http.MimeTypes
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsSuccess, Json}
import play.api.mvc.WebSocket.MessageFlowTransformer
import play.api.mvc._

import scala.concurrent.duration._

class Application @Inject()(projectRepo: ProjectRepo) extends Controller {

  implicit val mt: MessageFlowTransformer[Project, String] = {
    MessageFlowTransformer.stringMessageFlowTransformer.map { s =>
      Json.fromJson[Project](Json.parse(s)) match {
        case JsSuccess(project, _) => project
      }
    }
  }


  def socket = WebSocket.accept[Project, String] { request =>
    Flow[Project]
      .groupedWithin(10, 10 millis)
      .map(_.toList)
      .mapAsyncUnordered(parallelism = 4)(projectRepo.insert)
      .map(_.n.toString)
  }

  def createProject(name: String) = Action.async {
    projectRepo.create(name)
      .map(id => Ok(s"project $id created"))
  }

  def listProjects = Action {
    val projects = projectRepo.all
      .map(p => Json.toJson[List[Project]](p))
      .map(js => ByteString(js.toString()))

    Ok.sendEntity(Streamed(projects, None, Some(MimeTypes.JSON)))
  }

  def projects(name: String) = Action.async {
    for {
      Some(project) <- projectRepo.findByName(name)
    } yield Ok(Json.toJson(project))
  }

} 
开发者ID:jonasanso,项目名称:play-tepkin-mongo,代码行数:56,代码来源:Application.scala



注:本文中的play.api.libs.json.JsSuccess类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Terminated类代码示例发布时间:2022-05-23
下一篇:
Scala PropertyChecks类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap