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

Scala JsArray类代码示例

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

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



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

示例1: MonitoringServer

//设置package包名称以及导入依赖的类
package com.scalaio.http.monitoring

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes, Uri}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import com.typesafe.config.Config
import com.yammer.metrics.HealthChecks
import com.yammer.metrics.core.HealthCheckRegistry
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, Json}

import scala.util.{Failure, Success}
import scala.collection.convert.wrapAsScala._

object MonitoringServer {

  lazy val logger = LoggerFactory.getLogger(getClass)

  def handleHealthchecks(registry: HealthCheckRegistry): Route = {
    path("health") {
      get {
        complete {
          val checks = registry.runHealthChecks
          val payload = JsArray(checks.map {
            case (name, result) =>
              Json.obj(
                "name" -> name,
                "healthy" -> result.isHealthy,
                "message" -> result.getMessage
              )
          }.toSeq)
          val status = if (checks.values().forall(_.isHealthy)) OK else InternalServerError
          HttpResponse(entity = HttpEntity(`application/json`, Json.stringify(payload)), status = status)
        }
      }
    }
  }

  def start(serverConfig: Config, registry: HealthCheckRegistry = HealthChecks.defaultRegistry())
           (implicit system: ActorSystem, materializer: Materializer): Unit = {
    val host = serverConfig.getString("host")
    val port = serverConfig.getInt("port")
    logger.info(s"Starting monitoring server at: $host:$port")

    val routes = handleHealthchecks(registry) ~ redirect(Uri("/health"), StatusCodes.SeeOther)
    import system.dispatcher
    Http()
      .bindAndHandle(routes, host, port).onComplete {
      case Success(Http.ServerBinding(address)) =>
        logger.info(s"Monitoring server started at :$address")
      case Failure(t) =>
        logger.error("Error while trying to start monitoring server", t)
    }
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:61,代码来源:MonitoringServer.scala


示例2: DailyResult

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


import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import frontend.{Account, AuthorizationConfig}
import jp.t2v.lab.play2.auth.AuthElement
import play.api.libs.json.JsArray
import play.api.libs.ws.WSClient
import play.api.mvc.Controller

import scala.concurrent.Future



case class DailyResult(arena: String, guestTeam: String, homeTeam: String, guestScore: String, homeScore:String,
                       guestScoreLine:String, homeScoreLine:String, date: String)

@Singleton class DailyResults @Inject() (val conf: play.api.Configuration,
                              val ws: WSClient, val system: ActorSystem) extends Controller with AuthElement
  with AuthorizationConfig with GatewaySupport {

  override val key = "url.daily-results"

  override val log = akka.event.slf4j.Logger("daily-results")

  def gateway(stage: String, user: Account): Future[Seq[DailyResult]] = {
    val url = getUrl(key, stage)
    log.info(s"${user.login} -> $url")
    ws.url(url).withHeaders(authHeader -> user.token).get().flatMap { response =>
      response.status match {
        case OK => Future {
          (response.json \ "view").as[JsArray].value.map { item =>
            val teams = item.\("lineup").as[String].trim.split("@")
            val score = item.\("score").as[String].trim.split(" - ")
            val guestT = score(0).split(":")
            val guestFinalScore = guestT(1)
            val guestScoreLine = guestT(0)
            val homeT = score(1).split(":")
            val homeFinalScore = homeT(1)
            val homeScoreLine = homeT(0)
            DailyResult(item.\("arena").as[String], s"$picPref${teams(0).trim}.gif", s"$picPref${teams(1).trim}.gif",
              guestFinalScore, homeFinalScore, guestScoreLine, homeScoreLine,
              item.\("time").as[String])
          }
        }
        case FORBIDDEN => refreshGatewayToken[DailyResult](user, stage, gateway)
        case badCode => Future.successful(Seq.empty)
      }
    }
  }
} 
开发者ID:haghard,项目名称:scenter-frontend,代码行数:54,代码来源:DailyResults.scala


示例3: PokemonController

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


import javax.inject.Inject

import play.api.Logger
import play.api.cache._
import play.api.libs.json.{JsArray, JsObject, JsValue}
import play.api.mvc._
import shared._


class PokemonController @Inject() (cache: CacheApi) extends Controller {

  def postTweets = Action(parse.json) { implicit req =>
    Ok(SharedTwitterAPICalls.getLastTweets(req.body.toString()))
  }

  // Name, URL, Slot/Base_stat
  def parsePokemonWithParameter(param: String, param2: String, types: JsArray): Seq[((String, String), Int)] = {
    (types \\ param).map(x => ( (x \ "name").as[String], (x \ "url").as[String] ))
      .zip( (types \\ param2).map(x => x.as[Int]) )
  }

  def index(name: String) = Action {
    SharedPokemonList.set(cache.getOrElse[Seq[(String,String)]]("pokemonList") {
      val list = SharedPokemonAPICalls.initializePokemonList
      cache.set("pokemonList", list)
      list
    })

    val foundPokemons = SharedPokemonList.get.filter(x => x._1 == name)
    if (foundPokemons == Seq.empty[(String, String)])
      NotFound(views.html.notFoundPage(name))
    else {
      val foundPokemon = foundPokemons.head
      val result: JsValue = SharedPokemonAPICalls.getPokemonById(foundPokemon._2).as[JsObject] - "moves"
      SharedPokemonActive.set(result)

      Ok(views.html.pokemon(
        (result \ "sprites" \ "front_default").as[String],
        (result \ "name").as[String],
        (result \ "base_experience").as[Int],
        parsePokemonWithParameter("type", "slot", (result \ "types").as[JsArray] ),
        parsePokemonWithParameter("ability", "slot", (result \ "abilities").as[JsArray] ),
        parsePokemonWithParameter("stat", "base_stat", (result \ "stats").as[JsArray] ),
        SharedTwitterAPICalls.getLastTweets((result \ "name").as[String]),
        60000,
        routes.PokemonController.postTweets
      ))
    }
  }

} 
开发者ID:aNkM,项目名称:homework-pokemon,代码行数:55,代码来源:PokemonController.scala


示例4: PersonController

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

import javax.inject._

import model.Person
import play.api.Logger
import play.api.libs.json.{JsArray, JsValue, Json, Writes}
import play.api.mvc._

@Singleton
class PersonController @Inject() extends Controller {
  val logger = Logger(this.getClass)

  implicit val personWrites = new Writes[Person] {
    override def writes(person: Person): JsValue = Json.obj(
      "id" -> person.id,
      "name" -> person.name
    )
  }

  def all = Action {
    logger.debug(s"GET all: ${PersonController.persons.size}")
    val result = PersonController.persons.values.map(p => Json.toJson(p)).toSeq
    Ok(Json.toJson(JsArray(result)))
  }

  def put() = Action { request =>
    val jsonBody = request.body.asJson

    jsonBody.map { json =>
      logger.debug(s"PUT json is $json")
      jsonToPerson(json).map { person =>
        logger.debug(s"Inserting a $person")
        PersonController.persons += person.id -> person
        NoContent
      }.getOrElse {
        BadRequest("Missing data fields")
      }
      NoContent
    }.getOrElse {
      BadRequest("Expecting json in request body")
    }
  }

  private def jsonToPerson(json: JsValue): Option[Person] = {
    val id = (json \ "id").as[Int]
    val name = (json \ "name").as[String]

    if (id != 0 && name != null) {
      Some(Person(id, name))
    } else {
      None
    }
  }
}

object PersonController {
  var persons = Map.empty[Int, Person]
} 
开发者ID:jonasrichard,项目名称:chat-play,代码行数:60,代码来源:PersonController.scala


示例5: Application

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

import java.util.UUID

import play.api._
import play.api.libs.json.{JsArray, Json}
import play.api.mvc._

class Application extends Controller {

    //constants
    val JSON_KEY_AUTHOR = "author"
    val JSON_KEY_TEXT = "text"
    val JSON_KEY_COMMENTS = "comments"
    val JSON_KEY_ID = "id"

    //properties
    var commentsJson: JsArray = Json.arr(
        Json.obj(
            JSON_KEY_ID -> UUID.randomUUID().toString,
            JSON_KEY_AUTHOR -> "Pete Hunt",
            JSON_KEY_TEXT -> "This is first comment"),

        Json.obj(
            JSON_KEY_ID -> UUID.randomUUID().toString,
            JSON_KEY_AUTHOR -> "Michael Jordan",
            JSON_KEY_TEXT -> "This is another comment")
    )

    //actions
    def index = Action {
        Ok(views.html.projectDashboard())
    }

    def comments = Action {
        Ok(commentsJson)
    }

    def comment(author: String, text: String) = Action {
        val newComment = Json.obj(
            JSON_KEY_ID -> UUID.randomUUID().toString,
            JSON_KEY_AUTHOR -> author,
            JSON_KEY_TEXT -> text)

        commentsJson = commentsJson :+ newComment
        Ok(newComment)
    }

} 
开发者ID:complexityclass,项目名称:ProjectsLand,代码行数:50,代码来源:Application.scala


示例6: PartOfSpeechController

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

import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer
import scala.util.{Failure, Success, Try}
import javax.inject._
import play.api.libs.json.{JsArray, JsValue, Json}
import play.api.mvc._
import IndonesianNLP._

@Singleton
class PartOfSpeechController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def tagger: Action[JsValue] = Action(parse.json) { implicit request: Request[JsValue] =>
    val string = (request.body \ "string").as[String]

    Try {
      IndonesianPOSTagger.doPOSTag(string)
    } match {
      case Success(tagged) =>
        val tagListString = new ListBuffer[String]()
        val tagListJs = new ListBuffer[JsValue]()

        for(tag <- tagged.asScala) {
          for(word <- tag) {
            tagListString += word
            if(tag.indexOf(word) % 2 == 1) {
              tagListJs += Json.toJson(word)
            }
          }
        }
        val tagMap = tagListString.grouped(2).collect { case ListBuffer(k, v) => k -> v }.toMap

        Ok(Json.obj("status" -> "success", "data" -> Json.obj("map" -> Json.toJson(tagMap), "list" -> JsArray(tagListJs))))
      case Failure(failure) => InternalServerError(Json.obj("status" -> "error", "message" -> failure.toString))
    }
  }
} 
开发者ID:panggi,项目名称:pujangga,代码行数:39,代码来源:PartOfSpeechController.scala


示例7: NamedEntityController

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

import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer
import scala.util.{Failure, Success, Try}
import javax.inject._
import play.api.libs.json.{JsArray, JsValue, Json}
import play.api.mvc._
import IndonesianNLP._

@Singleton
class NamedEntityController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  val nETagger = new IndonesianNETagger

  def tagger: Action[JsValue] = Action(parse.json) { implicit request: Request[JsValue] =>
    val string = (request.body \ "string").as[String]

    Try {
      nETagger.extractNamedEntity(string)
    } match {
      case Success(extracted) =>

        val namedEntityList = new ListBuffer[JsValue]()

        for(tag <- extracted.asScala) {
          namedEntityList += Json.toJson(tag)
        }

        Ok(Json.obj("status" -> "success", "data" -> JsArray(namedEntityList)))
      case Failure(failure) => InternalServerError(Json.obj("status" -> "error", "message" -> failure.toString))
    }
  }
} 
开发者ID:panggi,项目名称:pujangga,代码行数:34,代码来源:NamedEntityController.scala


示例8: PhraseController

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

import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer
import scala.util.{Failure, Success, Try}
import javax.inject._
import play.api.libs.json.{JsArray, JsValue, Json}
import play.api.mvc._
import IndonesianNLP._

@Singleton
class PhraseController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
  val phraseChunker = new IndonesianPhraseChunker

  def chunker: Action[JsValue] = Action(parse.json) { implicit request: Request[JsValue] =>
    val string = (request.body \ "string").as[String]

    Try {
      phraseChunker.doPhraseChunker(string)
    } match {
      case Success(chunked) =>

        val chunkListString = new ListBuffer[String]()
        val chunkListJs = new ListBuffer[JsValue]()

        for(chunk <- chunked.asScala) {
          for(phrase <- chunk) {
            chunkListString += phrase
            if(chunk.indexOf(phrase) % 2 == 1) {
              chunkListJs += Json.toJson(phrase)
            }
          }
        }
        val chunkMap = chunkListString.grouped(2).collect { case ListBuffer(k, v) => k -> v }.toMap

        Ok(Json.obj("status" -> "success", "data" -> Json.obj("map" -> Json.toJson(chunkMap), "list" -> JsArray(chunkListJs))))
      case Failure(failure) => InternalServerError(Json.obj("status" -> "error", "message" -> failure.toString))
    }
  }
} 
开发者ID:panggi,项目名称:pujangga,代码行数:41,代码来源:PhraseController.scala


示例9: JsObjectInstances

//设置package包名称以及导入依赖的类
package com.iravid.playjsoncats

import cats.kernel.Eq
import play.api.libs.json.{ Json, JsObject, JsArray }
import cats.Monoid

object JsObjectInstances extends JsObjectInstances
trait JsObjectInstances {
  implicit val jsObjectMonoid: Monoid[JsObject] = new Monoid[JsObject] {
    def empty: JsObject = Json.obj()
    def combine(x: JsObject, y: JsObject): JsObject = x deepMerge y
  }

  implicit val jsObjectEq: Eq[JsObject] = Eq.fromUniversalEquals
}

object JsArrayInstances extends JsArrayInstances
trait JsArrayInstances {
  implicit val jsArrayMonoid: Monoid[JsArray] = new Monoid[JsArray] {
    def empty: JsArray = Json.arr()
    def combine(x: JsArray, y: JsArray): JsArray = x ++ y
  }

  implicit val jsArrayEq: Eq[JsArray] = Eq.fromUniversalEquals
} 
开发者ID:iravid,项目名称:play-json-cats,代码行数:26,代码来源:JsValueInstances.scala


示例10: RequestActor

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

import akka.actor._
import models.db.Tables
import models.db.Tables.PropertiesRow
import play.api.Logger
import play.api.libs.json.JsObject
import services.db.DBService
import play.api.libs.json.{JsArray, Json}
import play.api.libs.ws.WSClient
import services.nestoria._
import utils.db.TetraoPostgresDriver.api._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

class RequestActor(ws: WSClient, database: DBService) extends Actor {
  import RequestActor._

  override def receive = {

    case RequestNestoriaData =>
      Logger.info("Requesting data from Nestoria servers")

      val reqUrl = Nestoria(UK, SearchListings, pretty = true)
          .withParams(ListingType("buy"))
          .searchFor("brighton").url

      val request = ws.url(reqUrl).get()

      request.onComplete {
        case Success(response) =>
          Logger.info("Got data from Nestoria server")
          val listings = (response.json \ "response" \ "listings").as[JsArray].value
          val propRows = listings.map(o => Json.fromJson[PropertiesRow](o.as[JsObject])).filter(_.isSuccess).map(_.get)
          database.run(Tables.Properties.delete)
          database.run((Tables.Properties returning Tables.Properties) ++= propRows)

        case Failure(e) =>
          Logger.info("Failure, while requesting data from Nestoria servers.")
          Logger.info(e.getMessage)
      }

    case LookForKeywords(kws) =>
      val queryResult = database.run(Tables.Properties.filter(_.keywords @> kws).result)
      val jsonResult = Json.toJson(queryResult)
      sender() ! jsonResult
  }
}

object RequestActor {
  def props(ws: WSClient, db: DBService) = Props(new RequestActor(ws, db))

  case object RequestNestoriaData
  case class LookForKeywords(keywords: List[String])
} 
开发者ID:alexFrankfurt,项目名称:nest-api,代码行数:57,代码来源:RequestActor.scala


示例11: TransactionsBlockField

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

import com.google.common.primitives.{Bytes, Ints}
import play.api.libs.json.{JsArray, JsObject, Json}
import scorex.block.{Block, BlockField}

trait TransactionsBlockField extends BlockField[Seq[Transaction]]

object TransactionsBlockField {
  def apply(version: Int, value: Seq[Transaction]): TransactionsBlockField = version match {
    case 1 | 2 => TransactionsBlockFieldVersion1or2(value)
    case 3 => TransactionsBlockFieldVersion3(value)
  }
}

case class TransactionsBlockFieldVersion1or2(override val value: Seq[Transaction]) extends TransactionsBlockField {
  override val name = "transactions"

  override lazy val json: JsObject = Json.obj(name -> JsArray(value.map(_.json)))

  override lazy val bytes: Array[Byte] = {
    val txCount = value.size.ensuring(_ <= Block.MaxTransactionsPerBlockVer1).toByte
    value.foldLeft(Array(txCount)) { case (bs, tx) =>
      val txBytes = tx.bytes
      bs ++ Bytes.ensureCapacity(Ints.toByteArray(txBytes.length), 4, 0) ++ txBytes
    }
  }
}

case class TransactionsBlockFieldVersion3(override val value: Seq[Transaction]) extends TransactionsBlockField {
  override val name = "transactions"

  override lazy val json: JsObject = Json.obj(name -> JsArray(value.map(_.json)))

  override lazy val bytes: Array[Byte] = {
    val txCount = value.size.ensuring(_ <= Block.MaxTransactionsPerBlockVer2)
    val serTxCount = Seq((txCount / 256).toByte, txCount % 256).map(_.toByte).toArray
    value.foldLeft(serTxCount) { case (bs, tx) =>
      val txBytes = tx.bytes
      bs ++ Bytes.ensureCapacity(Ints.toByteArray(txBytes.length), 4, 0) ++ txBytes
    }
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:44,代码来源:TransactionsBlockField.scala


示例12: LobbyApi

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

import play.api.libs.json.{ Json, JsObject, JsArray }

import lila.common.PimpedJson._
import lila.game.{ GameRepo, Pov }
import lila.lobby.SeekApi
import lila.setup.FilterConfig
import lila.user.UserContext

final class LobbyApi(
    getFilter: UserContext => Fu[FilterConfig],
    lightUserApi: lila.user.LightUserApi,
    seekApi: SeekApi,
    pools: List[lila.pool.PoolConfig]
) {

  import lila.pool.JsonView._

  val poolsJson = Json toJson pools

  def apply(implicit ctx: Context): Fu[JsObject] =
    ctx.me.fold(seekApi.forAnon)(seekApi.forUser) zip
      (ctx.me ?? GameRepo.urgentGames) zip
      getFilter(ctx) flatMap {
        case ((seeks, povs), filter) =>
          lightUserApi.preloadMany(povs.flatMap(_.opponent.userId)) inject Json.obj(
            "me" -> ctx.me.map { u =>
              Json.obj("username" -> u.username)
            },
            "seeks" -> JsArray(seeks map (_.render)),
            "nowPlaying" -> JsArray(povs take 9 map nowPlaying),
            "nbNowPlaying" -> povs.size,
            "filter" -> filter.render,
            "pools" -> poolsJson
          )
      }

  def nowPlaying(pov: Pov) = Json.obj(
    "fullId" -> pov.fullId,
    "gameId" -> pov.gameId,
    "fen" -> (chess.format.Forsyth exportBoard pov.game.toChess.board),
    "color" -> pov.color.name,
    "lastMove" -> ~pov.game.castleLastMoveTime.lastMoveString,
    "variant" -> Json.obj(
      "key" -> pov.game.variant.key,
      "name" -> pov.game.variant.name
    ),
    "speed" -> pov.game.speed.key,
    "perf" -> lila.game.PerfPicker.key(pov.game),
    "rated" -> pov.game.rated,
    "opponent" -> Json.obj(
      "id" -> pov.opponent.userId,
      "username" -> lila.game.Namer.playerString(pov.opponent, withRating = false)(lightUserApi.sync),
      "rating" -> pov.opponent.rating,
      "ai" -> pov.opponent.aiLevel
    ).noNull,
    "isMyTurn" -> pov.isMyTurn,
    "secondsLeft" -> pov.remainingSeconds
  )
} 
开发者ID:DrNixx,项目名称:line,代码行数:62,代码来源:LobbyApi.scala


示例13: StockController

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

import java.util.concurrent.TimeUnit

import play.api.Play.current
import play.api.libs.json.{JsArray, Json}
import play.api.libs.ws.WS
import play.api.mvc._

import scala.concurrent.Await
import scala.concurrent.duration._

class StockController extends Controller {

  def message = Action { implicit request =>
    val body = request.body.asJson match {
      case Some(req) => {
        (req \ "content").asOpt[String] match {
          case Some(content) =>{
            val q = "??"+content.split(" ").mkString("+")
            val result = Await.result((WS.url("https://apis.daum.net/search/blog").withQueryString(("apikey","2facc253045575ff294bf7c9ab1fdfb9"),("q",q),("output","json"),("pageno","1")).get()),FiniteDuration(5000, TimeUnit.MILLISECONDS)).json
            (result \ "channel" \ "item").as[JsArray].value.map{ item =>
              s"${(item \ "title").as[String].replaceAll("&lt;b&gt;","").replaceAll("&lt;/b&gt;","")} \n${(item \ "link").as[String]}"
            }.mkString("\n")
          }
          case _ => "??? ????"
        }
      }
      case _ => "??? ?????"
    }

    Ok(Json.obj("message" -> Json.obj("text"->body), "keyboard" -> Json.obj("type" -> "text")))
  }

  def keyboard = Action {
    Ok(Json.obj("type" -> "text"))
  }
} 
开发者ID:suya55,项目名称:kakaoYellowIdBot,代码行数:39,代码来源:StockController.scala


示例14: DraftsController

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

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


class DraftsController extends Controller{

  implicit def draftWrites = Json.writes[DraftPick]

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

  def get(teamId: String) = Action { implicit request =>
    val yahooResponse = new YahooOauthService().makeRequest(Verb.GET, YahooRoutes.draftResults, getToken)
    val draftResponse = Json.parse(yahooResponse.getBody)
    val draftPicksJson = (draftResponse \ "query" \ "results" \ "league" \ "draft_results" \ "draft_result").as[JsArray]
    val picks = draftPicksJson.value.toIndexedSeq.map((draftJson) =>
      DraftPick(
        (draftJson \ "pick").as[String].toInt,
        (draftJson \ "round").as[String],
        (draftJson \ "team_key").as[String],
        (draftJson \ "player_key").as[String]
      )
    )
    redis.set("363.l.63462_draft", Json.toJson(picks))
    Ok(picks.toString)
  }
} 
开发者ID:cregg,项目名称:flhserver,代码行数:37,代码来源:DraftsController.scala


示例15: RedisService

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

import java.net.URI

import com.github.scribejava.core.model.OAuth1AccessToken
import com.redis.RedisClient
import models.{DraftPick, Player}
import play.api.libs.json.{JsArray, Json}
import v1.JSParsers._

import scala.util.{Properties, Try}


object RedisService {

//  val redis = if(System.getenv("heroku") == null) new RedisClient("localhost", 6379) else new RedisClient("redis://h:p9[email protected]ec2-34-198-124-158.compute-1.amazonaws.com", 40769)
  val redis = Properties.envOrNone("REDIS_URL") match {
    case Some(redisUrl) =>
      val redisUri = new URI(redisUrl)
      val host = redisUri.getHost
      val port = redisUri.getPort
      val secret = Try(redisUri.getUserInfo.split(":",2).last).toOption
      new RedisClient(host, port, secret = secret)
    case _ => new RedisClient("localhost", 6379)
  }

  def checkDraftResults(oAuth1AccessToken: OAuth1AccessToken): Seq[DraftPick] = {
    if(redis.get("363.l.63462_draft").isDefined) Json.parse(redis.get("363.l.63462_draft").get).as[JsArray].value.map(_.as[DraftPick]) else new YahooOauthService().updateLeagueDraft(oAuth1AccessToken)
  }

  def getPlayerRankings(oAuth1AccessToken: OAuth1AccessToken): Seq[Player] = {
    if(redis.get("363.l.63462").isDefined) Json.parse(redis.get("363.l.63462").get).as[JsArray].value.map(_.as[Player]) else new YahooOauthService().updatePlayerRankings(oAuth1AccessToken)
  }

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


示例16: ReactController

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

import play.api.libs.json.{Json, JsArray}
import play.api.mvc.{Action, Controller}


class ReactController extends Controller {

  val JSON_KEY_AUTHOR = "author"
  val JSON_KEY_TEXT = "text"

  // Initialise the comments list
  var commentsJson: JsArray = Json.arr(
    Json.obj(JSON_KEY_AUTHOR -> "Pete Hunt", JSON_KEY_TEXT -> "This is one comment"),
    Json.obj(JSON_KEY_AUTHOR -> "Jordan Walke", JSON_KEY_TEXT -> "This is *another* comment")
  )

  def reactIndex = Action { implicit request =>
    Ok(views.html.react_url_actor())
  }

  // Returns the comments list
  def comments = Action {
    Ok(commentsJson)
  }

  // Adds a new comment to the list and returns it
  def comment(author: String, text: String) = Action {
    val newComment = Json.obj(
      JSON_KEY_AUTHOR -> author,
      JSON_KEY_TEXT -> text)
    commentsJson = commentsJson :+ newComment
    Ok(newComment)
  }
} 
开发者ID:GoranSchumacher,项目名称:massive-actors,代码行数:36,代码来源:ReactController.scala


示例17: ProvidersTest

//设置package包名称以及导入依赖的类
package ru.tinkoff.api.providers

import org.scalactic.Snapshots._
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{FlatSpec, GivenWhenThen}
import play.api.libs.json.{JsArray, JsValue}

class ProvidersTest extends FlatSpec with GivenWhenThen with TableDrivenPropertyChecks {

  val providerGroups =
    Table(
      ("providerName"),
      ("????????"),
      ("????????"),
      ("???????????????????")
    )

  forAll(providerGroups) {
    (groupId: String) => {
      s"Provider group $groupId" should "return ok from ANONYMOUS with groups" in {
        When("I perform providers")
        val model = new ProvidersModel(ProvidersRequestHolder(groups = Some(groupId)))
        model.fire()
        info(s"$model")
        Then("I expect status in 2xx")
        assert(model.checkResult(), snap(model.globResult))
        Then("I expect doc is JSON")
        assert(model.responseModel.isInstanceOf[JsValue], snap(model))
        Then("I expect resultCode is OK")
        assert((model.responseModel \ "resultCode").asOpt[String].contains("OK"), snap(model))
        Then(s"I expect all groupId is $groupId")
        (model.responseModel \\ "groupId").foreach(x => {
          assert(x.as[String] == groupId, snap(model))
        })
        Then("I expect name is ??????? ??????????? where id is lastName")
        (model.responseModel \\ "providerFields").foreach(x => {
          x.as[JsArray].value.foreach(y => {if((y \ "id").asOpt[String].contains("lastName")){
            assert((y \ "name").asOpt[String].getOrElse("None").contains("???????"), snap(y))
          }})
        })
      }
    }
  }
} 
开发者ID:nmiroshnichenko,项目名称:apitests,代码行数:45,代码来源:ProvidersTest.scala


示例18: Holiday

//设置package包名称以及导入依赖的类
package com.github.yandoroshenko.workhourscounter

import java.time.LocalDate

import play.api.libs.json.{JsArray, JsNumber, Json}

import scala.util.{Failure, Success, Try}


trait HolidayCalendar extends Calendar {

  case class Holiday(date: LocalDate, name: String)

  private val url: String = "http://kayaposoft.com/enrico/json/v1.0/?action=getPublicHolidaysForMonth&month=%s&year=%s&country=%s"

  def getHolidays(from: LocalDate, to: LocalDate, countryCode: String): Either[Throwable, Set[Holiday]] =
    Try(getDays(from, to)
      .map(_.withDayOfMonth(1))
      .distinct
      .map(d =>
        Json.parse(io.Source.fromURL(String.format(url, d.getMonthValue.toString, d.getYear.toString, countryCode)).mkString)
          .as[JsArray].value
          .map(v => v \ "date" -> v \ "localName")
          .map(v => Holiday(
            LocalDate.of(
              (v._1 \ "year").as[JsNumber].value.toIntExact,
              (v._1 \ "month").as[JsNumber].value.toIntExact,
              (v._1 \ "day").as[JsNumber].value.toInt),
            v._2.as[String])))) match {
      case Success(a) => Right(a.reduceLeft(_ ++ _).toSet)
      case Failure(e) => Left(e)
    }
} 
开发者ID:YanDoroshenko,项目名称:work-hours-counter,代码行数:34,代码来源:HolidayCalendar.scala


示例19: index

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

import play.api.libs.json.{JsArray, JsObject, JsString}
import play.api.mvc._

import scala.collection.SortedMap


  def index = Action(parse.raw) { request =>
    val headerOrdering: Ordering[String] = Ordering.by(_.toLowerCase)
    val headers = request.headers.toMap.foldLeft(SortedMap.empty[String, Seq[String]](headerOrdering))(_ + _)
    val charset = request.charset.getOrElse("ISO-8859-1")
    val method = request.method
    val uri = request.uri
    val queryString = request.rawQueryString
    val bodyBytes: Seq[String] = for {
      bytes <- request.body.asBytes().toSeq
      by <- bytes
    } yield {
      val hex = Integer.toHexString(by)
      val prefix = if (by < 16) "0" else ""
      prefix + hex
    }
    val parsedBody = request.body.asBytes().map(_.decodeString(charset)).getOrElse("")
    Ok(JsObject(
      Seq(
        "method" -> JsString(method),
        "uri" -> JsString(uri),
        "queryString" -> JsString(queryString),
        "charset" -> JsString(charset),
        "body" -> JsObject(
          Seq(
            "string" -> JsString(parsedBody),
            "bytes" -> JsArray(bodyBytes.map(JsString))
          )
        ),
        "headers" -> JsObject(headers.mapValues(vs => JsArray(vs.map(JsString))))
      )
    ))
  }

} 
开发者ID:unclealex72,项目名称:whatamisending,代码行数:43,代码来源:GlobalController.scala


示例20: DifferenceService

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

import java.net.URLEncoder
import javax.inject.Inject

import client.JsonHttpClient
import controllers.SearchRequest
import play.api.Configuration
import play.api.libs.json.{JsArray, JsValue}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class DifferenceService @Inject()(jsonClient: JsonHttpClient, configuration: Configuration) {
  val originalSearchApiUrl: String = "ORIGINAL_SEARCH_API_URL"
  val newSearchApiUrl: String = "NEW_SEARCH_API_URL"

  def diff(searchRequest: SearchRequest): Future[(Set[String], Set[String])] = {
    val originalSearchUrl = getSearchUrl(searchRequest, originalSearchApiUrl)
    val newSearchUrl = getSearchUrl(searchRequest, newSearchApiUrl)

    val originalResultsFuture = jsonClient.get(originalSearchUrl).map {
      result => transformResult(result, searchRequest)
    }

    val newResultsFuture = jsonClient.get(newSearchUrl).map {
      result => transformResult(result, searchRequest)
    }

    originalResultsFuture.zip(newResultsFuture).map {
      case (originalResults, newResults) => {
        //newResults.groupBy(a => a).mapValues(_.size).toList.filter(_._2 > 1).foreach(println)
        val extraInQA = originalResults.toSet.diff(newResults.toSet)
        val extraInDEV = newResults.toSet.diff(originalResults.toSet)
        (extraInQA, extraInDEV)
      }
    }
  }

  private def transformResult(searchResponse: JsValue, searchRequest: SearchRequest): List[String] = {
    val result = searchResponse \ "searchResults"
    val searchResults = (result \ "results").get.as[JsArray]

    searchResults.value.indices.map(index => {
      (searchResults.value(index) \ "doi").get.as[String].replaceAll("<mark>|</mark>", "")
    }
    ).toList
  }

  def getSearchUrl(searchRequest: SearchRequest, searchApiUrl: String): String = {

    StringBuilder.newBuilder
      .append(configuration.getString(searchApiUrl).get)
      .append("/search?query=" + URLEncoder.encode(searchRequest.searchTerm, "UTF-8"))
      .append("&offset=1&limit=1000")
      .append("&sortType=relevance&startDate=1900-01-01&endDate=2017-02-17&disableFacets=country,technique,source,articleType")
      .toString()
  }

} 
开发者ID:kunalherkal,项目名称:comparator,代码行数:60,代码来源:DifferenceService.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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