本文整理汇总了Scala中play.api.libs.ws.WSResponse类的典型用法代码示例。如果您正苦于以下问题:Scala WSResponse类的具体用法?Scala WSResponse怎么用?Scala WSResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WSResponse类的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: payloadJson
//设置package包名称以及导入依赖的类
package neo4j.client
import com.typesafe.config.Config
import play.api.libs.json._
import play.api.libs.ws.{ WSAuthScheme, WSRequest, WSResponse }
import scala.concurrent.Future
trait Neo4jRestConnection {
protected val config: Config
protected val client = WSClient.client
val SERVER_ROOT_HOST = config.getString("neo4j-scala-dsl.neo4j.rest.host")
val SERVER_ROOT_PORT = config.getInt("neo4j-scala-dsl.neo4j.rest.port")
val SERVER_ROOT_URI = s"http://$SERVER_ROOT_HOST:$SERVER_ROOT_PORT"
val SERVER_ROOT_DATA_URI = s"$SERVER_ROOT_URI/db/data"
val SERVER_USERNAME = config.getString("neo4j-scala-dsl.neo4j.rest.username")
val SERVER_PASSWORD = config.getString("neo4j-scala-dsl.neo4j.rest.password")
val txUri = s"$SERVER_ROOT_DATA_URI/transaction/commit"
def payloadJson(statements: String*): JsObject =
Json.obj("statements" -> statements.map(s ? Map("statement" -> s)).toList)
def request(url: String): WSRequest = client.url(url)
.withHeaders(
("Content-Type", "application/json"),
("Accept", "application/json"))
.withAuth(SERVER_USERNAME, SERVER_PASSWORD, WSAuthScheme.BASIC)
def txCommit(queries: String*): Future[WSResponse] = {
println(s"txCommit: $queries")
request(txUri).post(payloadJson(queries: _*))
}
}
开发者ID:mardambey,项目名称:neo4j-scala-dsl,代码行数:37,代码来源:Neo4jRestConnection.scala
示例3: 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
示例4: config
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux
import com.pygmalios.reactiveinflux.response.ReactiveInfluxJsonResultException
import play.api.libs.ws.{WSClient, WSRequestHolder, WSResponse}
import scala.concurrent.Future
trait ReactiveInfluxCore {
def config: ReactiveInfluxConfig
def execute[R <: ReactiveInfluxCommand](command: R): Future[command.TResult]
}
trait ReactiveInfluxCommand extends Serializable {
type TResult <: Any
def apply(wsRequest: WSRequestHolder, wsResponse: WSResponse): TResult = {
try {
responseFactory(wsResponse).result
}
catch {
case ex: ReactiveInfluxJsonResultException =>
throw new ReactiveInfluxResultError(ex.errors, wsRequest)
case ex: Exception =>
throw new ReactiveInfluxException(s"Response processing failed!\n [$wsResponse]\n [${wsRequest.method}]\n [${wsRequest.url}\n [${wsResponse.body}]]", ex)
}
}
def logInfo: String = ""
protected def responseFactory(httpResponse: WSResponse): ReactiveInfluxResult[TResult]
}
trait ReactiveInfluxResult[+T] extends Serializable {
def result: T
}
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:37,代码来源:ReactiveinfluxCore.scala
示例5: 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
示例6: DropDatabaseCommand
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query
import java.net.URI
import com.pygmalios.reactiveinflux.ReactiveInfluxDbName
import com.pygmalios.reactiveinflux.error.{DatabaseNotFound, ReactiveInfluxError}
import com.pygmalios.reactiveinflux.response.EmptyJsonResponse
import play.api.libs.ws.{WSClient, WSResponse}
class DropDatabaseCommand(baseUri: URI, dbName: ReactiveInfluxDbName, failIfNotExists: Boolean)
extends BaseQueryCommand(baseUri) {
import DropDatabaseCommand._
override type TResult = Unit
override protected def responseFactory(wsResponse: WSResponse) =
new DropDatabaseResponse(wsResponse, failIfNotExists)
override def httpRequest(ws: WSClient) = ws.url(qUri(queryPattern.format(dbName.value)).toString)
}
object DropDatabaseCommand {
val queryPattern = "DROP DATABASE %s"
}
class DropDatabaseResponse(wsResponse: WSResponse, failIfNotExists: Boolean)
extends EmptyJsonResponse(wsResponse) {
override protected def errorHandler: PartialFunction[ReactiveInfluxError, Option[ReactiveInfluxError]] = {
case DatabaseNotFound(_) if !failIfNotExists => None
}
}
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:30,代码来源:DropDatabaseCommand.scala
示例7: ExampleApplication
//设置package包名称以及导入依赖的类
package com.example
import java.net.URI
import com.pygmalios.reactiveinflux.ReactiveInfluxDbName
import com.pygmalios.reactiveinflux.command.query.BaseQueryCommand
import com.pygmalios.reactiveinflux.itest.ITestConfig
import com.pygmalios.reactiveinflux.response.EmptyJsonResponse
import com.pygmalios.reactiveinflux.{ReactiveInflux, ReactiveInfluxCore}
import org.scalatest.FunSuite
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import play.api.libs.ws.{WSClient, WSResponse}
class ExampleApplication extends FunSuite with ScalaFutures with IntegrationPatience {
test("Execute custom command") {
val reactiveInflux = ReactiveInflux(config = Some(ITestConfig.config))
try {
implicit val dbName = ReactiveInfluxDbName("ExampleApplicatixon")
val db = reactiveInflux.database
try {
val core = reactiveInflux.asInstanceOf[ReactiveInfluxCore]
whenReady(core.execute(new CustomQueryCommand(core.config.url)).failed) { ex =>
}
}
finally {
db.drop()
}
}
finally {
reactiveInflux.close()
}
}
}
class CustomQueryCommand(baseUri: URI) extends BaseQueryCommand(baseUri) {
override type TResult = Unit
override protected def responseFactory(wsResponse: WSResponse) = new CustomQueryCommandResponse(wsResponse)
override def httpRequest(ws: WSClient) = ws.url(qUri("WHATEVER").toString)
}
class CustomQueryCommandResponse(wsResponse: WSResponse) extends EmptyJsonResponse(wsResponse)
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:42,代码来源:ExampleApplication.scala
示例8: PlayWsHttpResponse
//设置package包名称以及导入依赖的类
package http.client.connection.impl
import http.client.connection.HttpConnection
import http.client.request.HttpRequest
import http.client.response.{HttpHeader, HttpResponse}
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ning.NingWSClient
import scala.concurrent.{ExecutionContext, Future}
private[impl] case class PlayWsHttpResponse(status: Int, headers: Seq[HttpHeader], response: WSResponse) extends HttpResponse {
override val statusText = response.statusText
override val body = response.body
override val bodyAsBytes = response.bodyAsBytes
override def json = response.json
}
private[impl] object PlayWsHttpResponse {
def apply(wsReponse: WSResponse): PlayWsHttpResponse =
PlayWsHttpResponse(
wsReponse.status,
// turn Map[String, Seq[String]] into Seq[HttpHeader]
wsReponse.allHeaders.flatMap { kv ? kv._2.map { v ? HttpHeader(kv._1, v) } }.toSeq,
wsReponse)
}
class PlayWSHttpConnection extends HttpConnection {
implicit val client = NingWSClient()
private def queryStringToSeq(fields: Map[String, Seq[String]]): Seq[(String, String)] =
fields.flatMap(keyAndValues ? {
val key = keyAndValues._1
keyAndValues._2.map(value ? (key, value)).toList
}).toSeq
override def shutdown() = client.close()
override def makeRequest(request: HttpRequest)(implicit ec: ExecutionContext): Future[HttpResponse] = {
println(request.baseUrl + request.relativeUrl + " " + request.queryString)
val r = client
.url(request.baseUrl + request.relativeUrl)
.withHeaders(request.headers.map({ h ? h.name ? h.value }): _*)
.withQueryString(queryStringToSeq(request.queryString): _*)
.withMethod(request.method.name)
val req = if (request.body.isDefined) {
val r2 = r.withBody(request.body.get)
r2.execute()
} else {
r.execute()
}
req.map(PlayWsHttpResponse.apply)
}
}
开发者ID:SocialOrra,项目名称:social4s,代码行数:59,代码来源:PlayWSHttpConnection.scala
示例9: 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]
}
开发者ID:mikemey,项目名称:mpp,代码行数:60,代码来源:ProviderActor.scala
示例10: UserControllerTest
//设置package包名称以及导入依赖的类
package users.controllers
import commons.models.Login
import play.api.libs.json.{JsValue, Json}
import play.api.libs.ws.WSResponse
import testhelpers.PlayWithFoodWithServerBaseTest
import users.controllers.mappings.UserJsonMappings._
import users.models.{User, UserId}
import users.repositories.UserRepo
class UserControllerTest extends PlayWithFoodWithServerBaseTest {
val apiPath: String = "users"
"user API" should {
"return list with Marek" in {
implicit val c = components
import c._
// given
val user = User(UserId(1), Login("Marek"))
val persistedUser = runAndAwaitResult(userRepo.create(user))
// when
val response: WSResponse = await(wsUrl(s"/$apiPath").get)
// then
response.status.mustBe(OK)
val expectedBody: JsValue = Json.toJson(List(persistedUser))
response.body.mustBe(expectedBody.toString())
}
}
}
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:34,代码来源:UserControllerTest.scala
示例11: getToken
//设置package包名称以及导入依赖的类
package controllers
import java.nio.file.Path
import com.typesafe.config.ConfigFactory
import play.api.libs.ws.{WSClient, WSResponse}
import scala.concurrent.Future
trait GitHubServer {
val config = ConfigFactory.load().getConfig("devgym.github")
val clientId = config.getString("client-id")
val clientSecret = config.getString("client-secret")
val redirectUri = config.getString("uri")
def getToken(code: String)(implicit ws: WSClient): Future[WSResponse] = {
ws.url("https://github.com/login/oauth/access_token")
.withQueryString(
"client_id" -> clientId,
"client_secret" -> clientSecret,
"code" -> code,
"redirect_uri" -> redirectUri
)
.withHeaders("Accept" -> "application/json")
.withMethod("POST")
.get()
}
def query(token: String, path: Path)(implicit ws: WSClient): Future[WSResponse] = {
ws.url(s"https://api.github.com/$path")
.withHeaders("Authorization" -> s"token $token")
.get()
}
}
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:36,代码来源:GitHubServer.scala
示例12: Halo5Api
//设置package包名称以及导入依赖的类
package haloapi
import javax.inject._
import com.google.inject.ConfigurationException
import play.api.{Configuration, Play}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.ws.{WSClient, WSResponse}
class Halo5Api @Inject() (ws: WSClient, configuration: Configuration) {
val primaryKey = configuration.getString("halo.api.primary").getOrElse(throw new RuntimeException("Halo 5 API primary key not configured"))
val subscriptionKeyHeader = "Ocp-Apim-Subscription-Key"
def getMatchesForUser(gamerTag: String) = {
val urlTemplate = s"https://www.haloapi.com/stats/h5/players/$gamerTag/matches"
val request = ws.url(urlTemplate).withHeaders(subscriptionKeyHeader -> primaryKey)
request.get().map(transformMatchResponse)
}
def transformMatchResponse(response: WSResponse) = {
response.json
}
}
开发者ID:ManjunathChet,项目名称:Halo_Goat,代码行数:24,代码来源:Halo5Api.scala
示例13: WSClientImplicits
//设置package包名称以及导入依赖的类
package anchorman.media
import play.api.libs.ws.WSResponse
object WSClientImplicits {
implicit class WSResponseOps(response: WSResponse) {
def filename(url: String): String =
contentDispositionFilename getOrElse urlFilename(url)
val ContentDispositionFilename = ".*filename=\"([^;]+)\"".r
def contentDispositionFilename: Option[String] =
response header "Content-Disposition" collect {
case ContentDispositionFilename(filename) =>
filename.replaceAll("[^a-zA-Z0-9.-_]", "")
}
def urlFilename(url: String): String =
java.net.URLDecoder.decode(url.split("/").last, "UTF-8")
def contentType: String =
response header "Content-Type" getOrElse "application/octet-stream"
}
}
开发者ID:davegurnell,项目名称:anchorman,代码行数:25,代码来源:WSClientImplicits.scala
示例14: BotMessageSender
//设置package包名称以及导入依赖的类
package models
import play.api.Play
import play.api.libs.ws.{WSClient, WSRequest, WSResponse}
import scala.concurrent.Future
case class BotMessageSender(ws: WSClient) {
private val USERNAME = "surveybot"
private val TOKEN = Play.current.configuration.getString("slack.botUserToken").get
private val SLACK_API_URL = "https://slack.com/api/chat.postMessage"
def sendMessage(botMessage: BotMessage): Future[WSResponse] = {
buildRequest(botMessage).get()
}
def buildRequest(botMessage: BotMessage): WSRequest = {
ws.url(SLACK_API_URL)
.withQueryString(
("username", USERNAME),
("channel", s"@${botMessage.channel}"),
("token", TOKEN),
("text", botMessage.text))
}
}
开发者ID:mh120888,项目名称:surveybot,代码行数:25,代码来源:BotMessageSender.scala
示例15: createRelationship
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentfirelationship.support
import org.scalatest.Suite
import play.api.libs.ws.WSResponse
import play.api.mvc.Results
trait RelationshipActions extends ActionsSupport {
this: Suite =>
def createRelationship ( agentId: String, clientId: String, service: String ): WSResponse =
wsClient
.url(s"$url/agent/$agentId/service/$service/client/$clientId")
.put(Results.EmptyContent())
.futureValue
def getRelationship ( agentId: String, clientId: String, service: String ): WSResponse =
wsClient
.url(s"$url/agent/$agentId/service/$service/client/$clientId")
.get()
.futureValue
def deleteRelationship ( agentId: String, clientId: String, service: String ): WSResponse =
wsClient
.url(s"$url/agent/$agentId/service/$service/client/$clientId")
.delete()
.futureValue
}
开发者ID:hmrc,项目名称:agent-fi-relationship,代码行数:32,代码来源:RelationshipActions.scala
示例16: ViewRelationshipIntegrationSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentfirelationship
import play.api.libs.json.Json
import play.api.libs.ws.WSResponse
import uk.gov.hmrc.agentfirelationship.support.{IntegrationSpec, RelationshipActions}
class ViewRelationshipIntegrationSpec extends IntegrationSpec with RelationshipActions {
feature("View relationships for a client individual") {
scenario("Agent views an existing relationship") {
Given("there exists a relationship between an agent and client for a given service")
val agentId = "Agent123"
val clientId = "Client123"
val service = "Service123"
createRelationship(agentId,clientId,service)
When("I call the View Relationship endpoint")
val viewRelationshipResponse: WSResponse = getRelationship(agentId, clientId, service)
Then("I will receive a 200 OK response")
viewRelationshipResponse.status shouldBe OK
And("The response body will contain the relationship details")
val jsonResponse = Json.parse(viewRelationshipResponse.body)
val actualAgentId = (jsonResponse(0) \ "arn").as[String]
val actualClientId = (jsonResponse(0) \ "clientId").as[String]
val actualService = (jsonResponse(0) \ "service").as[String]
actualAgentId shouldBe agentId
actualClientId shouldBe clientId
actualService shouldBe service
//cleanup
deleteRelationship(agentId,clientId,service)
}
scenario("Agent views a non-existent relationship") {
Given("no relationship exists for a combination of agent, client and service")
val agentId = "Agent123"
val clientId = "Client123"
val service = "Service123"
When("I call the View Relationship endpoint")
val viewRelationshipResponse: WSResponse = getRelationship(agentId, clientId, service)
Then("I will receive a 404 NOT FOUND response")
viewRelationshipResponse.status shouldBe NOT_FOUND
}
}
}
开发者ID:hmrc,项目名称:agent-fi-relationship,代码行数:53,代码来源:ViewRelationshipIntegrationSpec.scala
示例17: RouteService
//设置package包名称以及导入依赖的类
package services
import javax.inject.Inject
import models.{Route, Vehicle}
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.http.HeaderNames
import play.api.http.ContentTypes
import scala.concurrent.{ExecutionContext, Future}
class RouteService @Inject() (ws: WSClient) {
private val BASE_URL = "http://m.cdsvyatka.com/tratata.php"
private val ROUTE_PARAM_NAME = "marsh"
private val REFERER = "http://m.cdsvyatka.com/mobile_map.php"
private def parseResponse(res: WSResponse): Seq[Vehicle] = {
res.json.validate[Map[String, Vehicle]].fold(_ => Seq.empty, _.values.toSeq)
}
def routeVehicles(route: Route)(implicit ec: ExecutionContext): Future[Seq[Vehicle]] = {
ws.url(BASE_URL)
.withQueryString(ROUTE_PARAM_NAME -> route.id.toString)
.withHeaders(HeaderNames.ACCEPT -> ContentTypes.JSON, HeaderNames.REFERER -> REFERER)
.get()
.map(parseResponse)
}
}
开发者ID:watchbus,项目名称:play-watchbus,代码行数:30,代码来源:RouteService.scala
示例18: sendCommandQuarantineFile
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fileupload.support
import org.scalatest.Suite
import play.api.libs.json.Json
import play.api.libs.ws.WSResponse
import uk.gov.hmrc.fileupload.controllers.{FileInQuarantineStored, FileScanned}
import uk.gov.hmrc.fileupload.write.envelope.Formatters._
import uk.gov.hmrc.fileupload.write.envelope._
trait EventsActions extends ActionsSupport {
this: Suite =>
def sendCommandQuarantineFile(e: QuarantineFile): WSResponse =
client
.url(s"$url/commands/quarantine-file")
.post(Json.toJson(e))
.futureValue
def sendCommandMarkFileAsClean(e: MarkFileAsClean): WSResponse =
client
.url(s"$url/commands/mark-file-as-clean")
.post(Json.toJson(e))
.futureValue
def sendCommandMarkFileAsInfected(e: MarkFileAsInfected): WSResponse =
client
.url(s"$url/commands/mark-file-as-infected")
.post(Json.toJson(e))
.futureValue
def sendCommandStoreFile(e: StoreFile): WSResponse =
client
.url(s"$url/commands/store-file")
.post(Json.toJson(e))
.futureValue
def sendFileInQuarantineStored(e: FileInQuarantineStored): WSResponse =
client
.url(s"$url/events/${e.getClass.getSimpleName.toLowerCase}")
.post(EventsSupport.fileInQuarantineStoredRequestBodyAsJson(e))
.futureValue
def sendFileScanned(e: FileScanned): WSResponse =
client
.url(s"$url/events/${e.getClass.getSimpleName.toLowerCase}")
.post(EventsSupport.fileScannedRequestBodyAsJson(e))
.futureValue
}
开发者ID:hmrc,项目名称:file-upload,代码行数:49,代码来源:EventsActions.scala
示例19: basic644
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fileupload.support
import com.google.common.base.Charsets
import com.google.common.io.BaseEncoding
import org.scalatest.Suite
import play.api.http.HeaderNames
import play.api.libs.ws.WSResponse
import play.utils.UriEncoding
import uk.gov.hmrc.fileupload.{EnvelopeId, FileId, FileRefId}
trait FileActions extends ActionsSupport {
this: Suite =>
def basic644(s:String): String = {
BaseEncoding.base64().encode(s.getBytes(Charsets.UTF_8))
}
def urlEncode(fileId: FileId) = UriEncoding.encodePathSegment(fileId.value, "UTF-8")
def upload(data: Array[Byte], envelopeId: EnvelopeId, fileId: FileId, fileRefId: FileRefId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/$fileId/$fileRefId")
.withHeaders("Content-Type" -> "application/octet-stream")
.put(data)
.futureValue
def delete(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}")
.delete()
.futureValue
def download(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/content").withHeaders(HeaderNames.AUTHORIZATION -> ("Basic " + basic644("yuan:yaunspassword")))
.get()
.futureValue
def getFileMetadataFor(envelopeId: EnvelopeId, fileId: FileId): WSResponse =
client
.url(s"$url/envelopes/$envelopeId/files/${urlEncode(fileId)}/metadata")
.get()
.futureValue
def downloadEnvelope(envelopeId: EnvelopeId): WSResponse =
client
.url(s"$fileTransferUrl/envelopes/$envelopeId")
.get()
.futureValue
}
开发者ID:hmrc,项目名称:file-upload,代码行数:52,代码来源:FileActions.scala
示例20: createEnvelope
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.fileupload.support
import java.io.File
import org.scalatest.Suite
import play.api.libs.ws.WSResponse
import uk.gov.hmrc.fileupload.EnvelopeId
import scala.io.Source
trait EnvelopeActions extends ActionsSupport {
this: Suite =>
def createEnvelope(file: File): WSResponse = createEnvelope(Source.fromFile(file).mkString)
def createEnvelope(data: String): WSResponse = createEnvelope(data.getBytes())
def createEnvelope(data: Array[Byte]): WSResponse =
client
.url(s"$url/envelope")
.withHeaders("Content-Type" -> "application/json")
.post(data)
.futureValue
def getEnvelopeFor(id: EnvelopeId): WSResponse =
client
.url(s"$url/envelopes/$id")
.get()
.futureValue
def envelopeIdFromHeader(response: WSResponse): EnvelopeId = {
val locationHeader = response.header("Location").get
EnvelopeId(locationHeader.substring(locationHeader.lastIndexOf('/') + 1))
}
def createEnvelope(): EnvelopeId = {
val response: WSResponse = createEnvelope(EnvelopeReportSupport.requestBody())
val locationHeader = response.header("Location").get
EnvelopeId(locationHeader.substring(locationHeader.lastIndexOf('/') + 1))
}
def deleteEnvelopFor(id: EnvelopeId): WSResponse =
client
.url(s"$url/envelopes/$id")
.delete()
.futureValue
}
开发者ID:hmrc,项目名称:file-upload-frontend,代码行数:49,代码来源:EnvelopeActions.scala
注:本文中的play.api.libs.ws.WSResponse类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论