本文整理汇总了Scala中play.api.libs.ws.WSClient类的典型用法代码示例。如果您正苦于以下问题:Scala WSClient类的具体用法?Scala WSClient怎么用?Scala WSClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WSClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: myPublicAddress
//设置package包名称以及导入依赖的类
package org.zalando.hutmann.spec
import org.scalatest.concurrent.PatienceConfiguration.Interval
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import org.scalatestplus.play.{ PlaySpec, PortNumber, WsScalaTestClient }
import play.api.Application
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.{ WSClient, WSResponse }
trait PlayUnitSpec extends PlaySpec with ScalaFutures with WsScalaTestClient {
def myPublicAddress(): String
implicit val portNumber: PortNumber
def callWs(testPaymentGatewayURL: String)(implicit app: Application): WSResponse = {
implicit val wSClient = app.injector.instanceOf[WSClient]
val callbackURL = s"http://${myPublicAddress()}/callback"
whenReady(
wsUrl(testPaymentGatewayURL)
.withQueryStringParameters("callbackURL" -> callbackURL)
.withHttpHeaders(HeaderNames.ACCEPT -> MimeTypes.TEXT)
.get(),
Interval(Span(10, Seconds))
) { result =>
result
}
}
}
示例2: PlayWithFoodWithTestComponents
//设置package包名称以及导入依赖的类
package testhelpers
import config.ExampleComponents
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.components.OneServerPerTestWithComponents
import play.api.db.evolutions.Evolutions
import play.api.http.Status
import play.api.libs.ws.WSClient
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, Helpers, TestServer}
import play.api.{Application, Configuration}
import slick.dbio.DBIO
trait PlayWithFoodWithServerBaseTest extends PlaySpec
with OneServerPerTestWithComponents
with DefaultFutureDuration
with DefaultExecutionContext
with Status
with DefaultAwaitTimeout
with FutureAwaits
with BeforeAndAfterEach {
class PlayWithFoodWithTestComponents extends ExampleComponents(context) {
override def configuration: Configuration = {
val testConfig = Configuration.from(TestUtils.config)
val config = super.configuration
val testConfigMerged = config ++ testConfig
config.toString
testConfigMerged
}
implicit lazy val testWsClient: WSClient = wsClient
}
override def components: PlayWithFoodWithTestComponents = new PlayWithFoodWithTestComponents
private def runServerAndCleanUpInMemDb(c: PlayWithFoodWithTestComponents) = {
runServerAndExecute(c.application) {
val dbapi = c.dbApi
Evolutions.cleanupEvolutions(dbapi.database("default"))
}
}
override protected def afterEach(): Unit = {
runServerAndCleanUpInMemDb(components)
}
protected def runServerAndExecute[T](app: Application)(blockWithComponents: => T): T = {
Helpers.running(TestServer(port, app))(blockWithComponents)
}
def runAndAwaitResult[T](action: DBIO[T])(implicit components: ExampleComponents): T = {
TestUtils.runAndAwaitResult(action)(components.actionRunner, duration)
}
}
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:58,代码来源:PlayWithFoodWithServerBaseTest.scala
示例3: 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)
}
}
示例4: ScheduleDownloadActor
//设置package包名称以及导入依赖的类
package logic.actors.schedule
import java.nio.charset.StandardCharsets
import javax.inject._
import akka.actor.{Actor, ActorRef}
import helpers.SpiritHelper
import logic.actors.schedule.ScheduleDownloadActor.DownloadSchedule
import logic.actors.schedule.ScheduleParseActor._
import org.fhs.spirit.scheduleparser.enumerations.EScheduleKind
import org.jsoup.Jsoup
import play.api.libs.ws.WSClient
import scala.collection.JavaConversions._
import scala.concurrent.Await
import scala.concurrent.duration._
@Singleton
class ScheduleDownloadActor @Inject()(ws: WSClient, @Named("parseActor") parseActor: ActorRef) extends Actor with SpiritHelper {
override def receive: Receive = {
case DownloadSchedule =>
val baseUrl = configuration.underlying.getString("schedule.baseUrl")
val lectureResults = uncachedCourseNames.map {
courseName =>
val outcome = "s_" + courseName + ".html"
val httpResult = Await.result(ws.url(baseUrl + outcome).get(), 10 seconds)
if (httpResult.status != 404) {
Some((httpResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString), courseName))
} else {
None
}
}.filter(_.nonEmpty).map(rs => (Jsoup.parse(rs.get._1).toString, rs.get._2)).map(rs => (EScheduleKind.REGULAR, rs))
val blockBaseResult = Await.result(ws.url(baseUrl + "bindex.html").get(), 10 seconds)
val bindex = Jsoup.parse(blockBaseResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString))
val blockRefs = bindex.select("a").map(_.attr("href")).toSet
val blockResult = blockRefs.map {
block =>
val httpResult = Await.result(ws.url(baseUrl + block).get(), 10 seconds)
if (httpResult.status != 404) {
Some((httpResult.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString), block))
} else {
None
}
}.filter(_.nonEmpty).map(rs => (Jsoup.parse(rs.get._1).toString, rs.get._2)).map(rs => (EScheduleKind.BLOCK, rs))
parseActor ! ParseSchedule(lectureResults ++ blockResult)
}
}
示例5: NewsReaderActor
//设置package包名称以及导入依赖的类
package logic.actors.rss
import javax.inject._
import akka.actor._
import helpers.SpiritHelper
import play.api.libs.ws.WSClient
import play.api.{Configuration, Logger}
import scala.concurrent.Await
import scala.concurrent.duration._
@Singleton
class NewsReaderActor @Inject()(configuration: Configuration, ws: WSClient,
@Named("rssParser") rssParserActor: ActorRef) extends Actor with SpiritHelper {
import NewsReaderActor._
import RSSParseActor._
val feedUrl = configuration.underlying.getString("rss.uri")
override def receive: Receive = {
case ReadNews =>
Logger.debug("Reading news")
val response = Await.result(ws.url(feedUrl).get(), 10 seconds)
//Logger.debug(response.statusText)
if (response.status != 200) {
Logger.error("error while news reading " + response.statusText)
} else {
// val responseString = response.bodyAsBytes.decodeString(StandardCharsets.ISO_8859_1.toString)
val responseString = response.body
val cachedValue = sessionCache.getOrElse("feedcontent")("")
if(!responseString.equals(cachedValue)) {
sessionCache.set("feedcontent", responseString, Duration.Inf)
rssParserActor ! RSSFeed(responseString)
}
}
case PoisonPill =>
}
}
object NewsReaderActor {
def props = Props[NewsReaderActor]
case object ReadNews
}
示例6: conf
//设置package包名称以及导入依赖的类
package controllers
import akka.actor.ActorSystem
import play.api.libs.ws.WSClient
import play.api.mvc.Result
import frontend.{AccountModel, Account}
import scala.concurrent.{Future, ExecutionContext}
trait GatewaySupport {
mixin: {
def conf: play.api.Configuration
def loginUrl: String
def ws: WSClient
def system: ActorSystem
} =>
lazy val picPref = "/assets/bootstrap/images/"
lazy val authHeader = conf.getString("http-session.auth").get
lazy val backendAuthHeader = conf.getString("http-session.auth-backend").get
def log: org.slf4j.Logger
implicit val ex = system.dispatchers.lookup("akka.stream-dispatcher")
def key: String
def getUrl(key: String, stage: String) = conf.getString(key).get + stage
def refreshGatewayToken[T](user: Account, stage: String, f: (String, Account) => Future[Seq[T]])
(implicit ex: ExecutionContext): Future[Seq[T]] = {
AccountModel.refreshToken(loginUrl, user, backendAuthHeader, ws).flatMap { tokenCtx =>
tokenCtx.fold(Future.failed[Seq[T]](new Exception("Refresh-token action has failed"))) { account =>
AccountModel.updateToken(user.login, user.password, account.token)
.flatMap { count => f(stage, user.copy(token = account.token)) }
}
}
}
def refreshToken(user: Account, url: String, f: (String, Account) => Future[Result])
(implicit ex: ExecutionContext): Future[Result] = {
AccountModel.refreshToken(loginUrl, user, backendAuthHeader, ws).flatMap { tokenCtx =>
tokenCtx.fold(Future.failed[Result](new Exception("Refresh-token action has failed"))) { account =>
AccountModel.updateToken(user.login, user.password, account.token)
.flatMap { count => f(url, user.copy(token = account.token)) }
}
}
}
}
示例7: 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)
}
}
}
}
示例8: AppLoader
//设置package包名称以及导入依赖的类
package org.andrewconner.spot
import _root_.controllers.Assets
import com.softwaremill.macwire._
import org.andrewconner.spot.core.time.Clock
import org.andrewconner.spot.modules._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSClient
import play.api.routing.Router
import scala.concurrent.ExecutionContext
class AppLoader extends ApplicationLoader {
def load(context: Context) = {
(new BuiltInComponentsFromContext(context) with AppComponents).application
}
}
trait AppComponents
extends BuiltInComponents
with PlayAppModule
with DatabaseModule // Database injection
with DaoModule
with ControllerModule // Application controllers
with CmdrModule
with CredentialsModule {
implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext // scala.concurrent.ExecutionContext.Implicits.global
implicit val clock: Clock = new Clock()
lazy val assets: Assets = wire[Assets]
val prefix: String = "/"
lazy val router: Router = wire[_root_.router.Routes].withPrefix(prefix)
implicit val wsClient: WSClient = AhcWSClient()
appShutdown.onStopAsync(wsClient.close())
}
示例9: EC2InstanceDetailsFetcher
//设置package包名称以及导入依赖的类
package org.andrewconner.spot.cmdrs.instance
import org.andrewconner.spot.core._
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import scala.concurrent.ExecutionContext
class EC2InstanceDetailsFetcher(wsClient: WSClient, implicit val ec: ExecutionContext) {
private lazy val fetch = {
wsClient.url("https://raw.githubusercontent.com/powdahound/ec2instances.info/master/www/instances.json").get().map { resp =>
implicit val eii = EC2Instance.eiiReads
Json.parse(resp.body).as[Seq[EC2Instance]].map { instance =>
instance.name -> instance
}.toMap
}
}
val value = fetch.asTask
}
示例10: Actors
//设置package包名称以及导入依赖的类
package modules
import actors.StatisticsProvider
import akka.actor.ActorSystem
import com.google.inject.{AbstractModule, Inject}
import play.api.Configuration
import play.api.libs.ws.WSClient
class Actors @Inject() (system: ActorSystem, ws: WSClient, config: Configuration) extends ApplicationActors {
system.actorOf(
props = StatisticsProvider.props.(ws, config).withDispatcher("control-aware-dispatcher"),
name = "statisticProvider"
)
}
trait ApplicationActors
class ActorsModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[ApplicationActors]).to(classOf[Actors]).asEagerSingleton
}
}
示例11: ElasticsearchClient
//设置package包名称以及导入依赖的类
package utils
import javax.inject.{Inject, Singleton}
import play.api.libs.ws.{WSAuthScheme, WSClient, WSRequest, WSResponse}
import play.api.{Configuration, Environment, Logger}
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class ElasticsearchClient @Inject()(ws: WSClient, environment: Environment, configuration: Configuration)(implicit ec: ExecutionContext) {
val logger = Logger("ElasticsearchClient")
val elasticsearchUri: String = configuration.getString("elasticsearch.uri").getOrElse("http://localhost:9200")
val elasticsearchUser: Option[String] = configuration.getString("elasticsearch.user")
val elasticsearchPassword: Option[String] = configuration.getString("elasticsearch.password")
logger.info(s"Elasticsearch URI = $elasticsearchUri")
private def client(path: String): WSRequest = {
val sanitizedPath: String = if (path.startsWith("/")) {
path
} else {
s"/$path"
}
elasticsearchUser match {
case None => ws.url(s"$elasticsearchUri$sanitizedPath")
case Some(user) => ws.url(s"$elasticsearchUri$sanitizedPath").withAuth(user, elasticsearchPassword.getOrElse(""), WSAuthScheme.BASIC)
}
}
def bulk(body: String): Future[WSResponse] = {
client(s"/_bulk").post(body)
}
}
示例12: TalkController
//设置package包名称以及导入依赖的类
package talks
import macros.Controller
import play.api.Logger
import play.api.libs.json._
import play.api.libs.ws.WSClient
import scala.concurrent.Future
@Controller
class TalkController {
def info(entity: Talk, ws: WSClient): Future[JsValue] = {
ws.url(s"https://www.TODO.com")
.get().map { response =>
val googleId: String = (response.json \\ "id").head.as[JsString].value
Logger(this.getClass).info(s"Google ID: $googleId")
JsString(s"https://books.google.fr/books?id=$googleId&printsec=frontcover&redir_esc=y")
}
}
}
示例13: BookController
//设置package包名称以及导入依赖的类
package books
import macros.Controller
import play.api.Logger
import scala.concurrent.Future
import play.api.libs.json._
import play.api.libs.ws.WSClient
@Controller
class BookController {
def info(entity: Book, ws: WSClient): Future[JsValue] = {
ws.url(s"https://www.googleapis.com/books/v1/volumes?q=intitle:${entity.title}+inauthor:${entity.author}&key=AIzaSyAP_-Rb-Hiw1C_fvOjzPBqLqttuJ-bspMA")
.get().map { response =>
val googleId: String = (response.json \\ "id").head.as[JsString].value
Logger(this.getClass).info(s"Google ID: $googleId")
JsString(s"https://books.google.fr/books?id=$googleId&printsec=frontcover&redir_esc=y")
}
}
}
示例14: ConferenceController
//设置package包名称以及导入依赖的类
package conferences
import macros.Controller
import play.api.Logger
import play.api.libs.json._
import play.api.libs.ws.WSClient
import scala.concurrent.Future
@Controller
class ConferenceController {
def info(entity: Conference, ws: WSClient): Future[JsValue] = {
ws.url(s"https://www.TODO.com")
.get().map { response =>
val googleId: String = (response.json \\ "id").head.as[JsString].value
Logger(this.getClass).info(s"Google ID: $googleId")
JsString(s"https://books.google.fr/books?id=$googleId&printsec=frontcover&redir_esc=y")
}
}
}
示例15: AuthController
//设置package包名称以及导入依赖的类
package controllers
import com.gu.googleauth.GoogleAuthConfig
import play.api.libs.ws.WSClient
import play.api.mvc._
class AuthController(val authConfig: GoogleAuthConfig, val wsClient: WSClient, val enableAuth: Boolean)
extends AuthActions
with Controller {
def login = Action.async { implicit request =>
startGoogleLogin()
}
def oauth2Callback = Action.async { implicit request =>
processOauth2Callback()
}
def authError = Action { request =>
val error = request.flash.get("error")
Ok(views.html.authError(error))
}
}