本文整理汇总了Scala中play.api.libs.ws.WS类的典型用法代码示例。如果您正苦于以下问题:Scala WS类的具体用法?Scala WS怎么用?Scala WS使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WS类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: BadWord
//设置package包名称以及导入依赖的类
package models
import org.joda.time.DateTime
import play.api.libs.json.{Writes, Reads, Json}
import play.api.libs.ws.WS
import scala.concurrent.Future
case class BadWord(
id: Long,
word: String,
createdAt: DateTime,
createdBy: Long,
linkUrlsOnly: Boolean
)
object BadWord {
implicit val yourJodaDateReads = Reads.jodaDateReads("yyyy-MM-dd'T'HH:mm:ss'Z'")
implicit val yourJodaDateWrites = Writes.jodaDateWrites("yyyy-MM-dd'T'HH:mm:ss'Z'")
implicit val badwordFmt = Json.format[BadWord]
def list: Future[List[BadWord]] = {
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global
WS.url(s"http://discussion.code.dev-guardianapis.com/discussion-api/moderation/antispam").get map { response =>
(response.json \ "badwords").as[List[BadWord]]
}
}
}
示例2: KikBot
//设置package包名称以及导入依赖的类
package controllers
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc.{Action, Controller}
import play.api.http.HeaderNames
import play.api.libs.ws.WS
import play.api.Play
import play.api.libs.json._
import models.{ChatBotMessage, KikBotMessage}
import utils.Bot
object KikBot extends Controller {
def kikBot() = Action.async { request =>
implicit val app = Play.current
val token = sys.env("KIK_TOKEN")
var body: JsValue = null
var text: String = null
try {
val message = (request.body.asJson.get \ "messages")(0)
text = Bot.parseInputGetOutput((message \ "body").toString)
val to = (message \ "from").toString
val chatId = (message \ "chatId").toString
body = Json.parse(s"""{
"messages": [
{
"body": "$text",
"to": $to,
"type": "text",
"chatId": $chatId
}
]}""")
} catch {
case e: Throwable => println(e)
}
KikBotMessage.create(new KikBotMessage(0, request.toString() + " # " + request.body.toString ))
WS.url("https://api.kik.com/v1/message").
withHeaders(HeaderNames.AUTHORIZATION -> s"Basic $token").
post(body).map { response =>
ChatBotMessage.create(new ChatBotMessage(0, response.toString + " # " + response.body.toString ))
Ok(text) }
}
def kikBotGetConfig() = Action.async { request =>
implicit val app = Play.current
val token = sys.env("KIK_TOKEN")
WS.url("https://api.kik.com/v1/config").
withHeaders(HeaderNames.AUTHORIZATION -> s"Basic $token", HeaderNames.CONTENT_TYPE -> "application/json").
get().map { response => Ok(response.json.toString) }
}
}
示例3: Bot
//设置package包名称以及导入依赖的类
package utils
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.util.{Failure, Success}
import play.api.Play.current
import play.api.libs.ws.WS
object Bot {
def duck(qry: String): String = {
val res = Await.ready(
WS.url(s"http://api.duckduckgo.com/?format=json&q=$qry").get,
5 seconds).value.get
res match {
case Success(wsResponse) => (wsResponse.json \\ "Text").head.toString.replace("\"", "")
case Failure(ex) => ex.toString
}
}
def parseInputGetOutput(input: String): String = {
val words = "\\w+".r.findAllIn(input).toList
words.head match {
case "duck" => duck(words.tail.mkString("%20"))
case x => duck(words.mkString("%20"))
}
}
}
示例4: ProviderActor
//设置package包名称以及导入依赖的类
package uk.mm.mpp.actors
import akka.actor.{Actor, Props}
import akka.pattern.pipe
import org.apache.commons.lang3.StringUtils._
import org.json4s._
import org.json4s.native.JsonMethods._
import play.api.Logger
import play.api.Play.current
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import uk.mm.mpp.actors.ProviderActor.{ProductRequest, ProductResponse}
import uk.mm.mpp.globals._
import scala.concurrent.ExecutionContext.Implicits.global
object ProviderActor {
def props(uid: String, port: Int) = Props(classOf[ProviderActor], uid, port)
case class ProductRequest()
case class ProductResponse(products: JArray)
}
class ProviderActor(uid: String, port: Int) extends Actor {
private lazy val request: WSRequest = WS.client.url(providerUrl)
.withFollowRedirects(false)
.withRequestTimeout(15000)
val logger = Logger(MPP_WORKER_PREFIX + getClass.getSimpleName + "_" + uid + "_" + port)
val providerUrl: String = "http://localhost:" + port + "/3rd/products"
def receive = {
case ProductRequest =>
request.get()
.map(productUpdateFrom)
.recover(withEmptyJsonArray)
.pipeTo(sender)
}
val withEmptyJsonArray: PartialFunction[Throwable, ProductResponse] = {
case _ => ProductResponse(JArray(List()))
}
def productUpdateFrom(response: WSResponse): ProductResponse = if (response.status == 200) {
logger.debug(s"from: [$providerUrl]: [${piedPiper(response)}]")
ProductResponse(parseJsonFrom(response))
} else {
logger.warn(s"from: [$providerUrl]: [${response.body}]")
ProductResponse(JArray(List()))
}
def piedPiper(response: WSResponse) = {
abbreviate(replacePattern(response.body, """\s{2,}""", " "), 30)
}
def parseJsonFrom(response: WSResponse) = parse(response.body).asInstanceOf[JArray]
}
示例5: getArsByModelId
//设置package包名称以及导入依赖的类
package connectors
import play.api.Logger
import play.api.http.Status._
import play.api.libs.ws.{WS, WSResponse}
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
trait ZolAPIConnector{
def getArsByModelId(modelId: String): Future[WSResponse] = {
val getUrl = s"""https://api.zalando.com/article-reviews-summaries/$modelId"""
WS.url(getUrl).get().map { response =>
response.status match {
case OK =>
response
case status =>
Logger.warn(s"[ZolAPIConnector][getArsByModelId] - status: $status Error ${response.body}")
response
}
}
}
}
object ZolAPIConnector extends ZolAPIConnector {
}
示例6: IntegrationSpec
//设置package包名称以及导入依赖的类
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.libs.json.Json
import play.api.libs.ws.WS
import play.api.test._
import play.api.test.Helpers._
class IntegrationSpec extends Specification {
val port = {
val portFromEnv = System.getProperties.getProperty("testserver.port")
if(portFromEnv == null) "19001" else portFromEnv
}
val serverUrl = s"http://localhost:${port}"
"Appl should" should {
"return detected changes" in new WithServer() {
Helpers.await(WS.url(s"${serverUrl}/v1/compare").post(Json.obj(
"left" -> Json.arr(1,2),
"right" -> Json.arr(4)
))).json shouldEqual Json.obj(
"changes" -> Json.arr(
Json.obj("change" -> Json.obj("index" -> 0, "original" -> 1, "revision" ->4)),
Json.obj("remove" -> Json.obj("index" -> 1, "value" ->2))
)
)
}
"contains information about processed time" in new WithServer() {
Helpers.await(WS.url(s"${serverUrl}/v1/compare").post(Json.obj(
"left" -> Json.arr(1,2),
"right" -> Json.arr(4)
))).header("Request-Time") should not beEmpty
}
"return bad request for mailformed json" in new WithServer() {
Helpers.await(WS.url(s"${serverUrl}/v1/compare").post(Json.obj(
"left" -> Json.arr(1,2)
))).status should beEqualTo(BAD_REQUEST)
}
}
}
示例7: Http
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support
import play.api.Play.current
import play.api.http.{HeaderNames, MimeTypes}
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import play.api.mvc.Results
import uk.gov.hmrc.play.http.ws.WSHttpResponse
import uk.gov.hmrc.play.http.{HeaderCarrier, HttpResponse}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
object Http {
def get(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.get()
}
def post(url: String, body: String, headers: Seq[(String, String)] = Seq.empty)
(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.withHeaders(headers: _*).post(body)
}
def postEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
import play.api.http.Writeable._
request.post(Results.EmptyContent())
}
def putEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
import play.api.http.Writeable._
request.put(Results.EmptyContent())
}
def delete(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.delete()
}
private def perform(url: String)(fun: WSRequest => Future[WSResponse])(implicit hc: HeaderCarrier): WSHttpResponse =
await(fun(WS.url(url).withHeaders(hc.headers: _*).withRequestTimeout(20000 milliseconds)).map(new WSHttpResponse(_)))
private def await[A](future: Future[A]) = Await.result(future, Duration(10, SECONDS))
}
class Resource(path: String, port: Int) {
private def url() = s"http://localhost:$port$path"
def get()(implicit hc: HeaderCarrier = HeaderCarrier()) = Http.get(url)(hc)
def postAsJson(body: String)(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.post(url, body, Seq(HeaderNames.CONTENT_TYPE -> MimeTypes.JSON))(hc)
def postEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.postEmpty(url)(hc)
def putEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.putEmpty(url)(hc)
}
示例8: BotTaskModule
//设置package包名称以及导入依赖的类
package tasks
import akka.actor.ActorSystem
import com.google.inject.{AbstractModule, Inject}
import models.{BotMessageComposer, BotMessageSender, PostgresSurveyRespondentRepository}
import org.joda.time.{DateTime, Seconds}
import play.api.Play.current
import play.api.inject.ApplicationLifecycle
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.ws.WS
import scala.concurrent.Future
import scala.concurrent.duration._
class BotTaskModule extends AbstractModule {
override def configure() = {
bind(classOf[BotTask]).asEagerSingleton()
}
}
class BotTask @Inject() (actorSystem: ActorSystem, lifecycle: ApplicationLifecycle) {
val currentTime = new DateTime()
val targetTime = currentTime.withHourOfDay(16).withMinuteOfHour(45).withSecondOfMinute(0)
val delayInSeconds: Int = Seconds.secondsBetween(currentTime, targetTime).getSeconds
actorSystem.scheduler.schedule(delayInSeconds.second, 1.day) {
if (play.api.Play.isDev(play.api.Play.current)) {
val respondentRepository = PostgresSurveyRespondentRepository()
val surveyRespondents = respondentRepository.getAll()
val messageComposer = BotMessageComposer()
val sender = BotMessageSender(WS.client)
for (surveyRespondent <- surveyRespondents) {
val message = messageComposer.createMessage(surveyRespondent)
sender.sendMessage(message)
}
}
}
lifecycle.addStopHook{ () =>
Future.successful(actorSystem.shutdown())
}
}
示例9: BotMessageSenderSpec
//设置package包名称以及导入依赖的类
package models
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import play.api.Play
import play.api.libs.ws.WS
import play.api.test.WithApplication
@RunWith(classOf[JUnitRunner])
class BotMessageSenderSpec extends Specification {
"#buildRequest" should {
"returns a WSRequest with the correct URL and params" in new WithApplication {
val botMessage = BotMessage("malina", "Hi there")
val result = BotMessageSender(WS.client).buildRequest(botMessage)
result.url must equalTo("https://slack.com/api/chat.postMessage")
result.queryString.getOrElse("username", List("")).head must equalTo("surveybot")
result.queryString.getOrElse("channel", List("")).head must equalTo("@malina")
result.queryString.getOrElse("token", List("")).head must equalTo(Play.current.configuration.getString("slack.botUserToken").get)
result.queryString.getOrElse("text", List("")).head must equalTo("Hi there")
}
}
}
示例10: ShortUrl
//设置package包名称以及导入依赖的类
package models
import org.h2.index.HashIndex
import play.api.libs.json.{Writes, Format, Json}
import play.api.libs.ws.{WSRequest, WS}
import play.api.Play.current
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random
case class ShortUrl(hash: String, fullUrl: String)
object ShortUrl {
implicit val shortUrlFmt: Format[ShortUrl] = Json.format[ShortUrl]
def lookup(hash: String)(implicit ec: ExecutionContext): Future[Option[ShortUrl]] = {
//todo:read the mapping from db and return ShortUrl obj
val fullurl: Future[Option[String]] = ShorturlDAO.findByHash(hash)
fullurl.map((result: Option[String]) => {
result.map{ (fullurl: String) =>
ShortUrl(hash,fullurl)
}
})
}
def shorten(fullUrl: String)(implicit ec: ExecutionContext): Future[ShortUrl] = {
//todo:compute a unique hash,done
nextUniqueId.map{nextId =>
hashId(nextId)
}.flatMap{hash =>
val insertFuture = ShorturlDAO.saveMapping(hash,fullUrl)
insertFuture.map{ _ =>
ShortUrl(hash,fullUrl)
}
}
}
//val countIoServiceUrl: String = "http://count.io/vb/urlshortner/hash+"
//val countioRequestHolder: WSRequest = WS.url(countIoServiceUrl)
private def nextUniqueId(implicit ex: ExecutionContext): Future[Int] = {
val r = new Random().nextInt(30)
Future.successful(r)
}
private val hashIndex: String = "abcdefghABCDEFGH123456"
private def hashId(id: Int,acc: String = ""): String = {
//val hashInd = hashIndex + url
id match {
case 0 => acc
case _ => hashId(id / hashIndex.length, acc + hashIndex.charAt(id % hashIndex.length))
}
}
}
示例11: WSController
//设置package包名称以及导入依赖的类
package controllers
import play.api.Play.current
import play.api.libs.json.{JsObject, JsValue}
import play.api.libs.ws.WS
import play.mvc.Controller
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
object WSController extends Controller {
val leerzeichen = " "
val plus = "+"
private def parseGoogleJsonNumber(json: JsValue): Int = {
val rows = (json \ "rows").as[List[JsObject]]
val jsonDistance = (rows.head \ "elements").as[List[JsObject]].head
(jsonDistance \ "distance" \ "value").asOpt[Int].get
}
def getDistance(adress: String, plz: String, city: String, email: String,
password: String): Future[Double] = {
val apiUrl = "https://maps.googleapis.com/maps/api/distancematrix/json"
val apiKey = "AIzaSyC6VCdDfHl2b9yRYnJnMq2PgSjPoXlEXow"
val futureDistance = WS.url(apiUrl +
"?origins=" + models.Company.adress.replaceAll(leerzeichen, "") + plus +
models.Company.plz + plus + models.Company.city + plus +
"&destinations=" + adress.replaceAll(leerzeichen, "") + plus
+ plz + plus + city + "&mode=car&language=de-DE&key=" + apiKey).get
futureDistance map { response =>
val distanceNumber: Int = parseGoogleJsonNumber(response.json)
val updateDistance = services.UserService.updateDistanceData(email,
password, distanceNumber)
updateDistance
}
}
}
示例12: Api
//设置package包名称以及导入依赖的类
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.ws.WS
import play.api.Play.current
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import models.Repo
class Api extends Controller {
implicit val writesRepo = new Writes[Repo] {
def writes(repo:Repo) = Json.obj(
"name" -> repo.name,
"language" -> repo.language,
"is_fork" -> repo.isFork,
"size" -> repo.size
)
}
implicit val readsRepoFromGithub:Reads[Repo] = (
(JsPath \ "name").read[String] and
(JsPath \ "language").read[String] and
(JsPath \ "fork").read[Boolean] and
(JsPath \ "size").read[Long]
)(Repo.apply _)
def repos(login:String) = Action.async {
val url = s"https://api.github.com/users/$login/repos"
val request = WS.url(url).withHeaders("Content-Type" -> "application/json").get()
request.map { r =>
if (r.status == 200) {
val reposOpt = Json.parse(r.body).validate[List[Repo]]
reposOpt match {
case JsSuccess(repos, _) => Ok(Json.toJson(repos))
case _ => InternalServerError
}
}
else {
NotFound
}
}
}
}
示例13: Monitor
//设置package包名称以及导入依赖的类
package controllers
import play.api.libs.ws.WS
import play.api.mvc._
import play.api.Play.current
import scala.concurrent.duration._
import lila.app._
object Monitor extends LilaController {
private val url = "http://api.monitor.lichess.org/render"
private object path {
val coachPageView = "servers.lichess.statsite.counts.main.counter.coach.page_view.profile"
}
private val coachPageViewCache = Env.memo.asyncCache.multi[lila.user.User.ID, Result](
name = "monitor.coachPageView",
f = userId =>
Env.coach.api byId lila.coach.Coach.Id(userId) flatMap {
_ ?? { coach =>
val days = coach.daysOld atLeast 3 atMost 30
WS.url(url).withQueryString(
"format" -> "json",
"target" -> s"""summarize(${path.coachPageView}.$userId,"1d","sum",false)""",
// "target" -> s"""summarize(servers.lichess.statsite.counts.main.counter.insight.request,'1d','sum',false)""",
"from" -> s"-${days}d",
"until" -> "now"
).get() map {
case res if res.status == 200 => Ok(res.body)
case res =>
lila.log("monitor").warn(s"coach ${res.status} ${res.body}")
NotFound
}
}
},
expireAfter = _.ExpireAfterWrite(10 minute)
)
def coachPageView = Secure(_.Coach) { ctx => me =>
coachPageViewCache get me.id
}
}
示例14: PngExport
//设置package包名称以及导入依赖的类
package lila.game
import play.api.libs.iteratee._
import play.api.libs.ws.WS
import play.api.Play.current
import chess.format.{ Forsyth, FEN }
final class PngExport(url: String, size: Int) {
def fromGame(game: Game): Fu[Enumerator[Array[Byte]]] = apply(
fen = FEN(Forsyth >> game.toChess),
lastMove = game.castleLastMoveTime.lastMoveString,
check = game.toChess.situation.checkSquare,
orientation = game.firstColor.some,
logHint = s"game ${game.id}"
)
def apply(
fen: FEN,
lastMove: Option[String],
check: Option[chess.Pos],
orientation: Option[chess.Color],
logHint: => String
): Fu[Enumerator[Array[Byte]]] = {
val queryString = List(
"fen" -> fen.value.takeWhile(' ' !=),
"size" -> size.toString
) ::: List(
lastMove.map { "lastMove" -> _ },
check.map { "check" -> _.key },
orientation.map { "orientation" -> _.name }
).flatten
WS.url(url).withQueryString(queryString: _*).getStream() flatMap {
case (res, body) if res.status != 200 =>
logger.warn(s"PgnExport $logHint ${fen.value} ${res.status}")
fufail(res.status.toString)
case (_, body) => fuccess(body)
}
}
}
示例15: Env
//设置package包名称以及导入依赖的类
package lila.explorer
import akka.actor._
import com.typesafe.config.Config
final class Env(
config: Config,
gameColl: lila.db.dsl.Coll,
system: ActorSystem
) {
private val InternalEndpoint = config getString "internal_endpoint"
private val IndexFlow = config getBoolean "index_flow"
private lazy val indexer = new ExplorerIndexer(
gameColl = gameColl,
internalEndpoint = InternalEndpoint
)
def cli = new lila.common.Cli {
def process = {
case "explorer" :: "index" :: since :: Nil => indexer(since) inject "done"
}
}
def fetchPgn(id: String): Fu[Option[String]] = {
import play.api.libs.ws.WS
import play.api.Play.current
WS.url(s"$InternalEndpoint/master/pgn/$id").get() map {
case res if res.status == 200 => res.body.some
case _ => None
}
}
if (IndexFlow) system.lilaBus.subscribe(system.actorOf(Props(new Actor {
def receive = {
case lila.game.actorApi.FinishGame(game, _, _) if !game.aborted => indexer(game)
}
})), 'finishGame)
}
object Env {
lazy val current = "explorer" boot new Env(
config = lila.common.PlayApp loadConfig "explorer",
gameColl = lila.game.Env.current.gameColl,
system = lila.common.PlayApp.system
)
}