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

Scala _类代码示例

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

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



在下文中一共展示了_类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Helper

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

import models.project.Project
import models.project.Project.EmbeddedProject
import play.api.libs.json.{JsError, _}

object Helper {
  // URLs
  val StatsPath = "http://api.sengab.com/v1/stats/"
  val ResultPath = "http://api.sengab.com/v1/results/"
  val CategoryPath = "http://api.sengab.com/v1/categories/"
  val ProjectPath = "http://api.sengab.com/v1/projects/"
  val UserPath = "http://api.sengab.com/v1/users/"
  val ContributionsPath = "http://api.sengab.com/v1/contributions/"

  val CreatedPostfixPath = "/created_projects"
  val ContributionsPostfixPath = "/contributions"

  // IDs
  val UserIDPrefix = "user::"
  val ActivityIDPrefix = "activity::"
  val StatsIDPrefix = "stats::"
  val ResultIDPrefix = "result::"

  // expected filter keywords on list projects
  val PopularKeyword = "popular"
  val FeaturedKeyword = "featured"
  val LatestKeyword = "latest"

  val EnrolledKeyword = "enrolled"
  val CreatedKeyword = "created"

  
  def trimEntityID(entityID: String) = entityID.substring(entityID.indexOf("::") + 2)

} 
开发者ID:Sengab-platform,项目名称:backend,代码行数:37,代码来源:Helper.scala


示例2: index

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

import javax.inject._

import dao.UserDAO
import models.{Bad, User}
import play.api.mvc._
import play.api.libs.json.{JsError, JsSuccess, Json, _}
import play.api.Mode
import system.MyExecutionContext

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration
import scala.concurrent.Future



  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }
implicit val userformat = Json.format[User]


  def create = Action.async(parse.json) { implicit request =>
    val validationResult: JsResult[User] = request.body.validate[User]
      validationResult match {
        case r: JsSuccess[User] =>
          val user:User=r.get
         val futureLong : Future[Long] =  userDAO.insert(user)
          futureLong.map{
            result => Ok("success")
          }
        case r: JsError =>
          scala.concurrent.Future {
            val errors = JsError.toJson(r)
            Ok(Json.toJson(Bad(Some(430), "bad.request", data = errors)))
          }
      }
  }


  def getAll = Action.async { implicit rs =>
    val users : Future[Seq[User]] =  userDAO.all()
    users.map(u => Ok(Json.toJson(u)))
  }



  def deleteUser(id:Long) = Action.async {  implicit request =>
      userDAO.delete(id).map(num => Ok(Json.toJson(num)))
  }


  def getById(id:Long) =Action.async{  implicit request =>
    userDAO.findById(id).map(num => Ok(Json.toJson(num)))
  }

} 
开发者ID:sarathraj-coder,项目名称:play2_6curd_rest,代码行数:59,代码来源:HomeController.scala


示例3: BitbucketStatus

//设置package包名称以及导入依赖的类
package com.pedrorijo91.status.model

import com.pedrorijo91.status.Config
import com.pedrorijo91.status.model.BitbucketStatus.ApiStatus
import org.joda.time.DateTime
import play.api.Logger
import play.api.libs.functional.syntax._
import play.api.libs.json.{Reads, _}
import scala.util.Try

case class BitbucketStatus(updatedAt: DateTime, status: ApiStatus.Value, description: String) extends HostStatus {
  def datetime: String = updatedAt.toString(Config.dateTimeFormat)
}

object BitbucketStatus {

  private val logger = Logger(this.getClass)

  implicit val read: Reads[BitbucketStatus] = (
    (JsPath \ "page" \ "updated_at").read[String].map(new DateTime(_)) and
      (JsPath \ "status" \ "indicator").read[String].map(ApiStatus.findByName) and
      (JsPath \ "status" \ "description").read[String]
    ) (BitbucketStatus.apply _)

  object ApiStatus extends Enumeration {
    val None, Minor, Major, Critical, Unknown = Value

    def findByName(name: String): ApiStatus.Value = {
      Try(ApiStatus.withName(name.toLowerCase.capitalize)).getOrElse {
        logger.warn(s"Found unexpected Bitbucket API status: $name")
        Unknown
      }
    }
  }

} 
开发者ID:pedrorijo91,项目名称:git-status-notifier,代码行数:37,代码来源:BitbucketStatus.scala


示例4: ShapelessObjectJsonSpec

//设置package包名称以及导入依赖的类
package microtools.shapeless

import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec
import play.api.libs.json.{Json, _}
import shapeless.HNil
import shapeless.record._
import shapeless.syntax.singleton._

class ShapelessObjectJsonSpec extends PlaySpec with MustMatchers {

  "Shapeless writes" should {
    "serialize HNil to empty object" in {
      import ShapelessObjectJson._

      val json = Json.toJson(HNil)

      json mustBe Json.obj()
    }

    "serialize Labeled HList to object" in {
      import ShapelessObjectJson._

      val json =
        Json.toJson(('someInt ->> 1234) :: ('someStr ->> "string") :: ('someBool ->> true) :: HNil)

      (json \ "someInt").as[Int] mustBe 1234
      (json \ "someStr").as[String] mustBe "string"
      (json \ "someBool").as[Boolean] mustBe true
    }

  }

  "shapeless reads" should {
    "deserialize HNil on any" in {
      import ShapelessObjectJson._

      Json.obj("bla" -> "blub").as[HNil] mustBe HNil
      JsNull.as[HNil] mustBe HNil
    }

    "deserialize json object to labeled HList" in {
      import ShapelessObjectJson._

      type record = Record.`'someInt -> Int, 'someString -> String, 'someBool -> Boolean`.T
      val result = Json
        .obj("someString" -> "string", "someInt" -> 1234, "someBool" -> true)
        .as[record]

      result('someInt) mustBe 1234
      result('someString) mustBe "string"
      result('someBool) mustBe true
    }
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:56,代码来源:ShapelessObjectJsonSpec.scala


示例5: ResetPasswordMessage

//设置package包名称以及导入依赖的类
package access.authentication

import messaging.{SocketMessageType, ToServerSocketMessage, ToServerSocketMessageType}
import org.apache.commons.validator.routines.EmailValidator
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json.{Reads, _}

import scala.util.Try

case class ResetPasswordMessage(email: String, code: String, newPassword: String)
  extends ToServerSocketMessage {

  override val socketMessageType: SocketMessageType = ResetPasswordMessage.ResetPassword

  private val emailValidator = EmailValidator.getInstance()

  require(email.trim.nonEmpty)
  require(code.trim.nonEmpty)
  require(newPassword.trim.nonEmpty)
  require(emailValidator.isValid(email.trim))

}

object ResetPasswordMessage {

  implicit val resetPasswordMessageReads: Reads[ResetPasswordMessage] = (
    (JsPath \ "email").read[String](email) and
    (JsPath \ "code").read[String](minLength[String](1)) and
    (JsPath \ "newPassword").read[String](minLength[String](1))
    ) (ResetPasswordMessage.apply _)

  case object ResetPassword extends ToServerSocketMessageType {
    override val description = "toServerResetPassword"
    override def socketMessage(msg: JsValue): ResetPasswordMessage =
      Try(resetPasswordMessageReads.reads(msg)).toOption.flatMap(_.asOpt).getOrElse(ResetPasswordMessage("1", "2" , "3"))
  }

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


示例6: writes

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

import models._
import play.api.libs.json.{Json, Writes, _}

import scala.collection.mutable.ArrayBuffer // Combinator syntax

trait SalvoStatusFormatter {


  implicit val salvoStatusWrites = new Writes[SalvoStatus] {


    def writes(salvoStatus: SalvoStatus) : JsObject = {
      if (salvoStatus.nextTurn != null) {
        val hits = salvoStatus.hits
        val game = salvoStatus.gameOver match {
          case true => Json.obj("won" -> salvoStatus.nextTurn.id)
          case false => Json.obj("player_turn" -> salvoStatus.nextTurn.id)
        }

        Json.obj(
          "salvo" -> Json.obj(hits(0).position -> hits(0).status,
            hits(1).position -> hits(1).status,
            hits(2).position -> hits(2).status,
            hits(3).position -> hits(3).status,
            hits(4).position -> hits(4).status),
          "game" -> game
        )
      }else{
        Json.obj("message" -> "Game not found.check GameID.")
      }
    }
  }

} 
开发者ID:mickymots,项目名称:xlspaceship,代码行数:37,代码来源:SalvoStatusFormatter.scala


示例7: TeamsController

//设置package包名称以及导入依赖的类
package v1.teams

import com.github.scribejava.core.model.{OAuth1AccessToken, Response, Verb}
import models.DraftSummary
import play.api.libs.json.{Json, _}
import play.api.mvc.{Action, AnyContent, Controller, Request}
import services.RedisService._
import services.{RedisService, YahooOauthService}
import v1.YahooRoutes
import v1.JSParsers._

class TeamsController extends Controller{

  implicit val draftSummaryReads = Json.reads[DraftSummary]
  implicit val draftSummaryWrites = Json.writes[DraftSummary]

  implicit val jsStringReads = Json.reads[JsString]

  def getToken(implicit request: Request[AnyContent]): OAuth1AccessToken = {
    val tokenString = request.headers.get("Authentication").getOrElse("")
    new OAuth1AccessToken(tokenString, redis.get(tokenString).get)
  }

  def get(id: String) = Action { implicit request =>
    val yahooResponse: Response = new YahooOauthService().makeRequest(Verb.GET, YahooRoutes.playersFromTeamReplaceId.replaceAll(":id", s"363.l.63462.t.$id"), getToken)
    RedisService.checkDraftResults(getToken)
    RedisService.getPlayerRankings(getToken)
    val teamDraftSummary: DraftSummary = DraftSummary.generateDraftSummary(yahooResponse.getBody, id)
    Ok(Json.toJson(teamDraftSummary))
  }

  def getTeams = Action { implicit request =>
    val yahooRequest = new YahooOauthService().makeRequest(Verb.GET, YahooRoutes.usersTeams, getToken)
    val usersTeamResponse = Json.parse(yahooRequest.getBody)
    val teams = usersTeamResponse \ "team"
    Ok(teams.toString)
  }

} 
开发者ID:cregg,项目名称:flhserver,代码行数:40,代码来源:TeamsController.scala


示例8: EnumUtils

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

import play.api.libs.json.{JsString, _}


object EnumUtils {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
    def reads(json: JsValue): JsResult[E#Value] = json match {
      case JsString(s) => {
        try {
          JsSuccess(enum.withName(s))
        } catch {
          case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
        }
      }
      case _ => JsError("String value expected")
    }
  }

  implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
    def writes(v: E#Value): JsValue = JsString(v.toString)
  }

  implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(enumReads(enum), enumWrites)
  }
} 
开发者ID:hluu,项目名称:todos,代码行数:28,代码来源:EnumUtils.scala


示例9: SecretDetail

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

import play.api.libs.functional.syntax._
import play.api.libs.json.{Writes, _}


case class SecretDetail(id: Option[Int], title: Option[String], itemId: Option[Int], itemName: Option[String], itemDesc: Option[String], securityLevel: Option[Int], itemContent: Option[String])

object SecretDetail {
  implicit val reads: Reads[SecretDetail] = (
    (__ \ "id").readNullable[Int] ~
      (__ \ "title").readNullable[String] ~
      (__ \ "itemId").readNullable[Int] ~
      (__ \ "itemName").readNullable[String] ~
      (__ \ "itemDesc").readNullable[String] ~
      (__ \ "securityLevel").readNullable[Int] ~
      (__ \ "itemContent").readNullable[String]
    ) (SecretDetail.apply _)

  implicit lazy val writes: Writes[SecretDetail] = (
    (__ \ "id").writeNullable[Int] ~
      (__ \ "title").writeNullable[String] ~
      (__ \ "itemId").writeNullable[Int] ~
      (__ \ "itemName").writeNullable[String] ~
      (__ \ "itemDesc").writeNullable[String] ~
      (__ \ "securityLevel").writeNullable[Int] ~
      (__ \ "itemContent").writeNullable[String]
    ) (unlift(SecretDetail.unapply))
}

case class RelationSecretItem(secretId: Int, itemId: Int, itemContent: String)

object RelationSecretItem {
  implicit val reads: Reads[RelationSecretItem] = (
    (__ \ "secretId").read[Int] ~
      (__ \ "itemId").read[Int] ~
      (__ \ "itemContent").read[String]
    ) (RelationSecretItem.apply _)

  implicit lazy val writes: Writes[RelationSecretItem] = (
    (__ \ "secretId").write[Int] ~
      (__ \ "itemId").write[Int] ~
      (__ \ "itemContent").write[String]
    ) (unlift(RelationSecretItem.unapply))
} 
开发者ID:JasonRock,项目名称:xpass,代码行数:46,代码来源:ResponseStatus.scala


示例10: TransportRequest

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

import play.api.libs.functional.syntax._
import play.api.libs.json.{Reads, Writes, _}


class TransportRequest(val publicKey: String, val info: Option[String]) {
  override def toString = Json.toJson(this).toString()
}

object TransportRequest {

  implicit val reads: Reads[TransportRequest] = (
    (__ \ "publicKey").read[String] ~
      (__ \ "info").readNullable[String]
    ) (TransportRequest.apply _)

  implicit val writes: Writes[TransportRequest] = (
    (__ \ "publicKey").write[String] ~
      (__ \ "info").writeNullable[String]
    ) (unlift(TransportRequest.unapply))

  def apply(publicKey: String, info: Option[String]): TransportRequest = {
    info match {
      case error if error.isEmpty => new TransportRequest(publicKey, info)
      case _ => new TransportRequest(publicKey, info)
    }
  }

  def unapply(arg: TransportRequest): Option[(String, Option[String])] = Some(arg.publicKey, arg.info)
} 
开发者ID:JasonRock,项目名称:xpass,代码行数:32,代码来源:TransportRequest.scala


示例11: UrbanResponse

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

import play.api.Logger
import play.api.libs.functional.syntax._
import play.api.libs.json.{Reads, _}
import scala.language.postfixOps
import scala.util.Try

case class UrbanResponse(resultType: UrbanResponseResultType.Value, definitions: List[UrbanTerm])

object UrbanResponse {

  implicit val userReads: Reads[UrbanResponse] = (
    (__ \ "result_type").read[String].map(UrbanResponseResultType.findByName) and
      (__ \ "list").read[List[UrbanTerm]]
    ) (UrbanResponse.apply _)
}

object UrbanResponseResultType extends Enumeration {
  val Exact = Value("exact")
  val NoResults = Value("no_results")
  val Unknown = Value("unknown")

  def findByName(name: String): UrbanResponseResultType.Value = {
    Try(UrbanResponseResultType.withName(name)).getOrElse {
      Logger.warn(s"Found unexpected UrbanDictionary API result: $name")
      Unknown
    }
  }
}

case class UrbanTerm(definition: String, permalink: String, thumbsUp: Int, thumbsDown: Int, author: String, example: String)

object UrbanTerm {

  implicit val userReads: Reads[UrbanTerm] = (
    (__ \ "definition").read[String] and
      (__ \ "permalink").read[String] and
      (__ \ "thumbs_up").read[Int] and
      (__ \ "thumbs_down").read[Int] and
      (__ \ "author").read[String] and
      (__ \ "example").read[String]
    ) (UrbanTerm.apply _)
} 
开发者ID:pedrorijo91,项目名称:urban-slack,代码行数:45,代码来源:UrbanResponse.scala


示例12: JsonConverters

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

import models._
import play.api.libs.json.{JsError, JsSuccess, Writes, _}

object JsonConverters {

  implicit val userIdReads = idReads(jsonValue => UserId(jsonValue.toLong))
  implicit val userIdWrites = idWrites[Long, UserId]()
  implicit val commendIdReads = idReads(jsonValue => CommentId(jsonValue.toLong))
  implicit val commentIdWrites = idWrites[Long, CommentId]()
  implicit val githubRepoIdFormat = Json.format[GitHubRepositoryId]
  implicit val userFormat = Json.format[User]
  implicit val loginAttemptFormat = Json.format[LoginAttempt]
  implicit val gitRepositoryFormat = Json.format[GitRepository]
  implicit val commentFormat = Json.format[Comment]
  implicit val newCommentFormat = Json.format[NewComment]

  implicit val newCommentLikeFormat = Json.format[NewCommentLike]
  implicit val commentLikeFormat = Json.format[CommentLike]

  def idReads[T](constructor: String => T): Reads[T] = new Reads[T] {
    override def reads(json: JsValue): JsResult[T] = json match {
      case JsString(s) => JsSuccess(constructor(s))
      case _ => JsError("String value expected")
    }
  }

  def idWrites[ID, T <: ModelId[ID]](): Writes[T] = new Writes[T] {
    override def writes(o: T): JsValue = JsString(o.value.toString)
  }
} 
开发者ID:Antanukas,项目名称:play-reactive-workshop,代码行数:33,代码来源:JsonConverters.scala


示例13: RoleUtils

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

import play.api.data.validation.ValidationError
import play.api.libs.json.{Format, Json, Writes, _}
import slick.driver.PostgresDriver.api._

object RoleUtils{
  private val roleMap:Map[Int, ClientRole] = Map(
    0 -> Admin,
    1 -> L1,
    2 -> L2
  )
  def forId(id:Int) : ClientRole = roleMap.get(id).getOrElse(L1) // todo fix this.

  implicit val mappedTypeMapper = MappedColumnType.base[ClientRole,Int](
    r => r.id,
    i => forId(i)
  )

  object ClientRoleReads extends Reads[ClientRole] {
    override def reads(json: JsValue): JsResult[ClientRole] =
      (json \ "id").asOpt[Int] match {
        case Some(x) => JsSuccess(forId(x))
        case None => JsError(ValidationError("No id value found in client role json object."))
      }
  }

  object ClientRoleWrites extends Writes[ClientRole] {
    override def writes(o: ClientRole): JsValue = Json.obj(
      "id" -> o.id,
      "n" -> o.prettyName
    )
  }

  implicit val clientRoleFormats = Format(ClientRoleReads,ClientRoleWrites)
}

sealed trait ClientRole{
  val id: Int
  val prettyName:String
}

case object Admin extends ClientRole{
  val id = 0
  val prettyName:String = "Admin"

}
case object L1 extends ClientRole{
  val id = 1
  val prettyName:String = "L1"

}
case object L2 extends ClientRole{
  val id = 2
  val prettyName:String = "L2"
} 
开发者ID:abhilash-alex,项目名称:play-slick-multitenant-seed,代码行数:57,代码来源:ClientRole.scala


示例14: ApiToken

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

import play.api.libs.json.{ JsObject, Json, _ }
import play.api.libs.json.{ JsPath, Json, Reads, Writes }
import java.util.{ Date, UUID }

import play.api.libs.json.{ JsObject, Json, _ }
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection

import reactivemongo.play.json.BSONFormats._
import scala.concurrent.ExecutionContext.Implicits.global
import org.joda.time.DateTime
import play.api.Logger
import reactivemongo.bson.{ BSONDateTime, BSONObjectID }
import play.api.libs.functional.syntax._

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global


case class ApiToken(

    userId: Option[BSONObjectID],
    token: String, // UUID 36 digits
    apiKey: String,
    expirationTime: DateTime

) {
  def isExpired = expirationTime.isBeforeNow
}

object ApiToken {
  import FakeDB.tokens

  implicit val externalEventRead: Reads[ApiToken] = (
    (JsPath \ "userId").readNullable[BSONObjectID] and
    (JsPath \ "token").read[String] and
    (JsPath \ "apiKey").read[String] and
    (JsPath \ "expirationTime").read[DateTime]

  )(ApiToken.apply _)

  val externalEventWrites: Writes[ApiToken] = (
    (JsPath \ "userId").writeNullable[BSONObjectID] and
    (JsPath \ "token").write[String] and
    (JsPath \ "apiKey").write[String] and
    (JsPath \ "expirationTime").write[DateTime]
  )(unlift(ApiToken.unapply))

  implicit val apiTokenFormat = Json.format[ApiToken]

} 
开发者ID:Mousticusss,项目名称:Play2-Api,代码行数:54,代码来源:ApiToken.scala


示例15: Name

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

import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, Json, _}

case class Name(value: String)

object Name {
  implicit val nameFormat = Json.format[Name]
}

case class DOB(value: String)

object DOB {
  implicit val dobFormat = Json.format[DOB]
}

case class Pet(id: Option[Int], name: Name, dob: DOB, notes: String)

object Pet {

  val petReads: Reads[Pet] = (
    (JsPath \ "id").readNullable[Int] and
      (JsPath \ "name").read[String].map { value => Name(value) } and
      (JsPath \ "dateOfBirth").read[String].map { value => DOB(value) } and
      (JsPath \ "notes").read[String]
    ) (Pet.apply _)


  val petWrites: Writes[Pet] = (
    (JsPath \ "id").writeNullable[Int] and
      (JsPath \ "name").write[String].contramap { (name: Name) => name.value } and
      (JsPath \ "dateOfBirth").write[String].contramap { (dob: DOB) => dob.value } and
      (JsPath \ "notes").write[String]
    ) (unlift(Pet.unapply))

  implicit val petFormat: Format[Pet] =
    Format(petReads, petWrites)
} 
开发者ID:sofiaaacole,项目名称:FirstLookPlay,代码行数:40,代码来源:PetDefinitions.scala


示例16: TransactionController

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

import javax.inject.Inject

import biz._
import biz.interop.QueryBuilder
import models._
import models.interop.HTTPResponseError
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{Json, _}
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json._

import scala.concurrent.Future

// Reactive Mongo imports
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}

class TransactionController @Inject() (val reactiveMongoApi: ReactiveMongoApi)
  extends Controller
    with MongoController with ReactiveMongoComponents
    with CanResponse
    with CanCrossOrigin {

  def create(id: String) = Action.async(parse.json) { request =>
    request.body.validate[Transaction]
      .map { payload =>
        TransactionBiz.one(db, id).flatMap {
          case None => TransactionBiz.insert(db, payload.withId(id), id).map {
            case None => ResponseError(HTTPResponseError.MONGO_SET_FAILED)
            case Some(tx) => ResponseOk(tx)
          }
          case Some(_) => base.fs(ResponseError(HTTPResponseError.MONGO_ID_DUPLICATED))
        }
      }
      .recoverTotal { e => Future.successful(BadRequest(JsError.toJson(e))) }
      .map (corsPOST)
  }

  def get(id: String) = Action.async { request =>
    TransactionBiz.one(db, id).map {
      case None => ResponseError(HTTPResponseError.MONGO_NOT_FOUND(request))
      case Some(tx) => ResponseOk(tx)
    }.map (corsGET)
  }

  def list(tp: String) = Action.async { request =>
    TransactionBiz.sequence[String](db, Json.obj("type" -> tp), "_id")
      .map(ResponseOk)
      .map(corsGET)
  }

  def sum(id: String) = Action.async { request =>
    TransactionBiz.sequence[Double](db, QueryBuilder.or(QueryBuilder.withId(id), Json.obj("parent_id" -> id)), "amount")
      .map(lst => lst.sum)
      .map(ResponseOk)
      .map(corsGET)
  }
} 
开发者ID:scozv,项目名称:bolero,代码行数:60,代码来源:TransactionController.scala


示例17: CompaniesController

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Silhouette
import dao.MongoDbCompaniesRepository
import model.Company
import modules.JWTEnv
import play.api.i18n.MessagesApi
import play.api.libs.json.{JsError, Json, _}
import play.api.mvc._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.bson.{BSONDocument, BSONObjectID}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class CompaniesController @Inject()(val reactiveMongoApi: ReactiveMongoApi,
                                    val messagesApi: MessagesApi,
                                    val companiesRepository: MongoDbCompaniesRepository,
                                    silhouette: Silhouette[JWTEnv]) extends Controller {

  private[CompaniesController] def display(objects: Future[List[JsObject]]) =
    objects
      .map(obj => Ok(obj.map(b => b.values).mkString(",")))
      .recover { case e: Exception => BadRequest(e.getMessage) }

  def search(term: String) = Action.async { implicit request =>
    display(companiesRepository.find(term))
  }

  def all = Action.async { implicit request =>
    display(companiesRepository.find(""))
  }

  def save(id: String) = silhouette.SecuredAction.async { implicit request =>
    import model.Company.Fields._

    request.body.asJson.map { r =>
      r.validate[Company] match {
        case JsSuccess(business, _) =>
          val document = BSONDocument(
            Id -> id,
            Name -> business.name,
            Address -> business.address,
            Email -> business.email,
            Phone -> business.phone
          )

          companiesRepository.save(document)
            .map {
              result => Ok(Json.obj("success" -> result.ok))
            }
            .recover {
              case e: Exception => Ok(Json.obj("error while saving new entry" -> e.getMessage))
            }
        case [email protected](_) => Future.successful(BadRequest(JsError.toJson(err)))
      }
    }.getOrElse(Future.successful(BadRequest("Invalid request")))
  }
} 
开发者ID:team3,项目名称:Play2-mongodb-silhouette-activator-template,代码行数:62,代码来源:CompaniesController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala SQLExecution类代码示例发布时间:2022-05-23
下一篇:
Scala max类代码示例发布时间: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