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

Scala WSClient类代码示例

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

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



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


示例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)
    }
} 
开发者ID:KadekM,项目名称:play-slick-silhouette-auth-api,代码行数:51,代码来源:PermissionsViaHttpAuthorizer.scala


示例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)
  }
} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:56,代码来源:ScheduleDownloadActor.scala


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

} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:51,代码来源:NewsReaderActor.scala


示例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))  }
      }
    }
  }
} 
开发者ID:haghard,项目名称:scenter-frontend,代码行数:49,代码来源:GatewaySupport.scala


示例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)
      }
    }
  }
} 
开发者ID:haghard,项目名称:scenter-frontend,代码行数:54,代码来源:DailyResults.scala


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

} 
开发者ID:andrewconner,项目名称:spotsy,代码行数:41,代码来源:AppLoader.scala


示例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
} 
开发者ID:andrewconner,项目名称:spotsy,代码行数:21,代码来源:EC2InstanceDetailsFetcher.scala


示例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
  }
} 
开发者ID:jborkowski,项目名称:twitter-analytics-service,代码行数:23,代码来源:Actors.scala


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

} 
开发者ID:devconferences,项目名称:devconferences,代码行数:39,代码来源:ElasticsearchClient.scala


示例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")
      }
  }
} 
开发者ID:my-web-services,项目名称:mws-collections,代码行数:21,代码来源:TalkController.scala


示例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")
      }
  }
} 
开发者ID:my-web-services,项目名称:mws-collections,代码行数:21,代码来源:BookController.scala


示例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")
      }
  }
} 
开发者ID:my-web-services,项目名称:mws-collections,代码行数:23,代码来源:ConferenceController.scala


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

} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:25,代码来源:AuthController.scala


示例16: listPokemons

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

import javax.inject.{Inject, Singleton}

import com.github.racc.tscg.TypesafeConfig
import play.api.http.HeaderNames.ACCEPT
import play.api.libs.ws.{WSClient, WSRequest}
import pokestats.pokeapi.model.{NamedApiResourceList, Pokemon, Type}
import pokestats.util.OptionSnakePickler._

import scala.concurrent.{ExecutionContext, Future}

trait PokeApi {
  def listPokemons: Future[NamedApiResourceList]
  def getPokemon(id: Int): Future[Pokemon]
  def getType(id: Int): Future[Type]
}

@Singleton
class PokeApiClient @Inject()(
    ws: WSClient,
    @TypesafeConfig("pokestats.pokeapi.rootUrl") rootUrl: String)(
    implicit context: ExecutionContext)
    extends PokeApi {

  override def listPokemons: Future[NamedApiResourceList] =
    list[NamedApiResourceList]("pokemon")

  override def getPokemon(id: Int): Future[Pokemon] =
    get[Pokemon](s"pokemon/$id")

  override def getType(id: Int): Future[Type] =
    get[Type](s"type/$id")

  private def get[A: Reader](path: String) = {
    val req = request(path)
    getAndParse[A](req)
  }

  private def list[A: Reader](path: String) = {
    // Always get the full list by passing a very high limit
    val req = request(path).withQueryStringParameters("limit" -> "999999")
    getAndParse[A](req)
  }

  private def request(path: String) = {
    ws.url(s"$rootUrl/$path")
      .withHttpHeaders(ACCEPT -> "application/json")
  }

  private def getAndParse[A: Reader](request: WSRequest) = {
    val response = request.get()
    response.map(r => read[A](r.body))
  }
} 
开发者ID:guilgaly,项目名称:pokemon-stats,代码行数:56,代码来源:PokeApiClient.scala


示例17: NavigationController

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

import javax.inject.Inject

import play.api.data._
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.ws.WSClient
import play.api.mvc.{Action, Controller}
import play.twirl.api.Html


class NavigationController @Inject() (ws: WSClient) (val messagesApi: MessagesApi) extends Controller with I18nSupport{
  def navigate() = Action.async
  {
    implicit request =>
      val xml : UserXML = xmlForm.bindFromRequest().get
    val code = scala.xml.XML.loadString(xml.xml)
    val pageId = (code \ "state" \ "page-id").text

    val selections = code \ "selection"
    val selectionNumbers = selections.map(i => (i \ "@page-id").text)

    val texts = code \ "text"
    val textNumbers = texts.map(i => (i \ "@page-id").text)

    val paragraphs = code \ "paragraph"
    val paragraphNumbers = paragraphs.map(i => (i \ "@page-id").text)

    implicit val context = play.api.libs.concurrent.Execution.Implicits.defaultContext

    if (selectionNumbers.contains(pageId)){
      ws.url("http://" + request.host + "/selection/").post(Map("xml" -> Seq(xml.xml))).map { response =>
        Ok(Html(response.body))
      }
    }else if(textNumbers.contains(pageId)) {
      ws.url("http://" + request.host + "/text/").post(Map("xml" -> Seq(xml.xml))).map { response =>
        Ok(response.body)
      }
    }else if(paragraphNumbers.contains(pageId)) {
      ws.url("http://" + request.host + "/paragraph/").post(Map("xml" -> Seq(xml.xml))).map { response =>
        Ok(response.body)
      }
    }else {
      ws.url("http://" + request.host + "/").get().map { response =>
        Ok(Html(response.body))
      }
    }
  }

  val xmlForm = Form(
    mapping(
      "xml" -> nonEmptyText
    )(UserXML.apply)(UserXML.unapply)
  )
} 
开发者ID:Peantab,项目名称:paragraph-framework,代码行数:57,代码来源:NavigationController.scala


示例18: getUser

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

import scala.concurrent.{ExecutionContext, Future}
import play.api.libs.json.JsValue
import play.api.libs.ws.WSClient

import models.User

trait UserClient {

  def getUser(id: Int)(implicit ec: ExecutionContext): Future[Option[User]]

}

class RandomUserClient(
  ws: WSClient,
  baseUrl: String = "https://randomuser.me"
) extends UserClient {

  def getUser(id: Int)(implicit ec: ExecutionContext): Future[Option[User]] = {
    ws.url(baseUrl + "/api?seed=" + id).get().map { response =>
      if (response.status == 200) {
        (response.json \ "results")(0).asOpt[JsValue].flatMap { result =>
          for {
            firstName <- (result \ "name" \ "first").asOpt[String]
            lastName <- (result \ "name" \ "last").asOpt[String]
            email <- (result \ "email").asOpt[String]
          } yield User(firstName, lastName, email)
        }
      } else None
    }
  }

} 
开发者ID:EVENFinancial,项目名称:play-compile-time-di-example,代码行数:35,代码来源:UserClient.scala


示例19: AutoshopIntegrationTest

//设置package包名称以及导入依赖的类
import cambillaum.autoshop.dto.{CarDTO, MotorcycleDTO, VehicleCategoryWithNumberDTO, VehiclesPageDTO}
import org.scalatestplus.play._
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import play.api.test._
import play.api.test.Helpers.{GET => GET_REQUEST, _}

class AutoshopIntegrationTest extends PlaySpec with OneServerPerSuite with FutureAwaits with DefaultAwaitTimeout {

  "The autoshop VehiclesPage Rest Service" must {
    "Return the expected JSON response" in {
      val wsClient = app.injector.instanceOf[WSClient]
      val vehiclesPageServiceUrl = s"http://localhost:$port/vehicles/page"
      val response = await(wsClient.url(vehiclesPageServiceUrl).withQueryString("numberOfVehiclesPerPage" -> 3.toString, "offset" -> 0.toString).get())
      response.status.mustBe(OK)
      val vehiclesPageDTO = Json.fromJson[VehiclesPageDTO](response.json).get
      val expectedVehiclesPageDTO = VehiclesPageDTO(
        totalNumberOfVehicles = 6,
        numberOfVehiclesByCategory = List(
          VehicleCategoryWithNumberDTO("SUV", 1),
          VehicleCategoryWithNumberDTO("Sedan", 1),
          VehicleCategoryWithNumberDTO("Truck", 1),
          VehicleCategoryWithNumberDTO("Motorcycle", 3)
        ),
        vehiclesInPage = List(
          CarDTO("car1", "Car For Sale 1", 1000, 2000, "SEDAN", 3),
          MotorcycleDTO("motorcycle2", "Motorcycle For Sale 2", 3000, 2010, false),
          CarDTO("car3", "Car For Sale 3", 5000, 2007, "TRUCK", 5)
        )
      )
      vehiclesPageDTO.mustBe(expectedVehiclesPageDTO)
    }
  }

} 
开发者ID:cambillaum,项目名称:autoshop-scala,代码行数:36,代码来源:AutoshopIntegrationTest.scala


示例20: QueryCommand

//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query

import java.net.URI

import com.pygmalios.reactiveinflux.impl.OptionalParameters
import com.pygmalios.reactiveinflux.response.PlayWSJsonResponse
import com.pygmalios.reactiveinflux.{BigDecimalValue, BooleanValue, Query, QueryResult, ReactiveInfluxDbName, ReactiveInfluxException, Result, Rfc3339, Series, StringValue, TimeFormat, Value}
import play.api.libs.json._
import play.api.libs.ws.{WSClient, WSResponse}

class QueryCommand(baseUri: URI, dbName: ReactiveInfluxDbName, qs: Seq[Query], params: QueryParameters) extends BaseQueryCommand(baseUri) {
  override type TResult = Seq[QueryResult]
  override protected def responseFactory(wsResponse: WSResponse) = {
    val timeFormat: TimeFormat = params.epoch.getOrElse(Rfc3339)
    new QueryCommandResult(wsResponse, qs, timeFormat)
  }
  override def httpRequest(ws: WSClient) = {
    val q = qs.map(_.influxQl).mkString(";")
    ws.url(qUri(q).toString)
  }
  override def otherParams = OptionalParameters(
    QueryParameters.dbQ -> Some(dbName.value),
    QueryParameters.epochQ -> params.epoch.map(_.q),
    QueryParameters.chunkSizeQ -> params.chunkSize.map(_.toString)
  )
}

private[reactiveinflux] class QueryCommandResult(wsResponse: WSResponse, qs: Seq[Query], timeFormat: TimeFormat)
  extends PlayWSJsonResponse[Seq[QueryResult]](wsResponse) {
  import JsonResultFormat._

  override def result: Seq[QueryResult] = qs.zip(results).map {
    case (q, jsResult) =>
      QueryResult(q, jsToResult(jsResult.as[JsonResult]))
  }

  private def jsToResult(jsonResult: JsonResult): Result = Result(jsonResult.series.map(jsToSeries))

  private def jsToSeries(jsonSeries: JsonSeries): Series = Series(
    name        = jsonSeries.name,
    columns     = jsonSeries.columns,
    values      = jsonSeries.values.map(jsRow => jsRow.flatMap(jsToValue)),
    timeFormat  = timeFormat
  )

  private def jsToValue(jsValue: JsValue): Option[Value] = jsValue match {
    case JsString(value) => Some(StringValue(value))
    case JsNumber(value) => Some(BigDecimalValue(value))
    case JsBoolean(value) => Some(BooleanValue(value))
    case JsNull => None
    case other => throw new ReactiveInfluxException(s"Unsupported JSON value type! [$other]")
  }
}

object QueryCommandResult {
  val seriesField = "series"
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:58,代码来源:QueryCommand.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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