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

Scala AhcWSClient类代码示例

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

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



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

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


示例2: AppComponent

//设置package包名称以及导入依赖的类
import com.typesafe.config.Config
import controllers.{ OAuthGitHubController, TEAHubController, UIController }
import play.api.{ Application, ApplicationLoader, BuiltInComponentsFromContext, LoggerConfigurator }
import play.api.ApplicationLoader.Context
import play.api.cache.EhCacheComponents
import play.api.libs.ws.ahc.AhcWSClient
import play.api.i18n._
import services.impl.{ ApiGitHubService, ApiOAuthGitHubService, ApiTogglService }
import scala.concurrent.{ ExecutionContext, Future }
import router.Routes


class AppComponent(context: Context)(implicit val ec: ExecutionContext) extends BuiltInComponentsFromContext(context)
    with EhCacheComponents with I18nComponents {

  val config: Config = context.initialConfiguration.underlying
  val wsClient = AhcWSClient()

  lazy val oauthGitHubService = new ApiOAuthGitHubService(config, wsClient)
  lazy val oauthGitHubController = new OAuthGitHubController(oauthGitHubService)
  lazy val gitHubService = new ApiGitHubService(wsClient)
  lazy val togglService = new ApiTogglService(wsClient)
  lazy val teahubController = new TEAHubController(togglService, gitHubService, defaultCacheApi)
  lazy val assetsController = new controllers.Assets(httpErrorHandler)
  lazy val uiController = new UIController(messagesApi, defaultCacheApi, teahubController)(ec)

  lazy val router = new Routes(
    httpErrorHandler,
    oauthGitHubController,
    uiController,
    teahubController,
    assetsController
  )

  applicationLifecycle.addStopHook(() => Future.successful(wsClient.close))
} 
开发者ID:lunatech-labs,项目名称:teahub,代码行数:37,代码来源:AppLoader.scala


示例3: StandaloneWsClient

//设置package包名称以及导入依赖的类
package com.github.implicitdef.toolbox.http
import java.io.IOException

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.libs.ws.ahc.AhcWSClient

class StandaloneWsClient extends WSClient {

  private implicit val actorSystem = ActorSystem()
  private implicit val materializer = ActorMaterializer()
  private val ahcWsClient = AhcWSClient()

  override def underlying[T] = ahcWsClient.underlying[T]

  override def url(url: String): WSRequest = ahcWsClient.url(url)

  @scala.throws[IOException]
  override def close(): Unit = {
    ahcWsClient.close()
    materializer.shutdown()
    actorSystem.terminate()
  }
} 
开发者ID:implicitdef,项目名称:toolbox,代码行数:26,代码来源:StandaloneWsClient.scala


示例4: LetsEncryptWSClient

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

import akka.stream.Materializer
import com.typesafe.config.ConfigFactory
import play.api.inject.ApplicationLifecycle
import play.api.libs.ws.ahc.{AhcConfigBuilder, AhcWSClient, AhcWSClientConfig}
import play.api.libs.ws.{WSClient, WSConfigParser, WSRequest}
import play.api.{Configuration, Environment}

import scala.concurrent.Future

import contexts._


class LetsEncryptWSClient(lifecycle: ApplicationLifecycle,
                          env: Environment)(implicit mat: Materializer, wsEc: WSExecutionContext) extends WSClient {

  private val propsConfig = ConfigFactory.systemProperties()

  private val wsConfig = ConfigFactory.load(propsConfig.withFallback(ConfigFactory.parseString(
    """
      |play.ws {
      |  ssl {
      |    trustManager = {
      |      stores = [
      |        # Seems to be required for https://helloworld.letsencrypt.com
      |        { type = "PEM", path = "./conf/dst-x3-root.pem" }
      |        { type = "PEM", path = "./conf/letsencrypt-authority-x1.pem" }
      |      ]
      |    }
      |  }
      |}
    """.stripMargin)))

  private lazy val client = {
    val configuration = Configuration.reference ++ Configuration(wsConfig)
    val parser = new WSConfigParser(configuration, env)
    val config = new AhcWSClientConfig(wsClientConfig = parser.parse())
    val builder = new AhcConfigBuilder(config)
    val client = AhcWSClient(builder.build())
    lifecycle.addStopHook { () =>
      Future(client.close())
    }
    client
  }

  override def underlying[T]: T = client.underlying[T]

  override def url(url: String): WSRequest = client.url(url)

  override def close(): Unit = client.close()
} 
开发者ID:wsargent,项目名称:play-ws-with-letsencrypt,代码行数:53,代码来源:LetsEncryptWSClient.scala


示例5: FBAdsStandaloneModule

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

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.fourseasapp.facebookads.network.{APIRequest, APIRequestFactory, BatchAPIRequest}
import com.google.inject.assistedinject.FactoryModuleBuilder
import com.google.inject.{AbstractModule, Inject, Provider}
import com.typesafe.config.ConfigFactory
import net.codingwell.scalaguice.ScalaModule
import org.asynchttpclient.AsyncHttpClientConfig
import play.api.libs.ws.ahc.{AhcConfigBuilder, AhcWSClient, AhcWSClientConfig}
import play.api.libs.ws.{WSClient, WSConfigParser}
import play.api.{Configuration, Environment, Mode}


class FBAdsStandaloneModule extends AbstractModule with ScalaModule {
  override def configure(): Unit = {
    install(new FactoryModuleBuilder()
      .implement(classOf[APIRequest], classOf[APIRequest])
      .implement(classOf[BatchAPIRequest], classOf[BatchAPIRequest])
      .build(classOf[APIRequestFactory]))

    bind[ActorSystem].toInstance(ActorSystem(classOf[FBAdsStandaloneModule].getSimpleName))
    bind[WSClient].toProvider[WSClientProvider].in[javax.inject.Singleton]
  }
}

class WSClientProvider @Inject() (system: ActorSystem) extends Provider[WSClient] {
  override def get(): WSClient = {
    val materializer = ActorMaterializer(namePrefix = Some(classOf[FBAdsStandaloneModule].getSimpleName))(system)

    val configuration = Configuration.reference ++ Configuration(ConfigFactory.parseString(
      """
        |ws.followRedirects = true
      """.stripMargin))

    val parser = new WSConfigParser(configuration, Environment.simple(mode = Mode.Prod))
    val config = new AhcWSClientConfig(wsClientConfig = parser.parse())
    val builder = new AhcConfigBuilder(config)
    val logging = new AsyncHttpClientConfig.AdditionalChannelInitializer() {
      override def initChannel(channel: io.netty.channel.Channel): Unit = {
        channel.pipeline.addFirst("log", new io.netty.handler.logging.LoggingHandler("debug"))
      }
    }
    val ahcBuilder = builder.configure()
    ahcBuilder.setHttpAdditionalChannelInitializer(logging)
    val ahcConfig = ahcBuilder.build()
    return new AhcWSClient(ahcConfig)(materializer)
  }
} 
开发者ID:hailg,项目名称:facebook-scala-ads-sdk,代码行数:51,代码来源:FBAdsStandaloneModule.scala


示例6: ScamandrillTest

//设置package包名称以及导入依赖的类
package io.github.scamandrill.client

import io.github.scamandrill.MandrillSpec
import play.api.Configuration
import play.api.libs.ws.ahc.AhcWSClient

class ScamandrillTest extends MandrillSpec {
  "Scamandrill" should "create a new WSClient using overridden values from supplied config" in {
    val instance = Scamandrill(Configuration(
      "play.ws.ahc.maxConnectionsPerHost" -> 5
    ))
    try {
      instance.ws match {
        case AhcWSClient(underlying) => underlying.getMaxConnectionsPerHost shouldBe 5
        case _ => fail("The underlying client should be a AhcWSClient if scamandrill is constructed with no args")
      }
    } finally {
      instance.shutdown()
    }
  }

  it should "use the key from application.conf if no config is specified" in {
    val instance = Scamandrill()
    try {
      instance.get().key.key shouldBe "example key"
    } finally {
      instance.shutdown()
    }
  }
} 
开发者ID:scamandrill,项目名称:scamandrill,代码行数:31,代码来源:ScamandrillTest.scala


示例7: HocsWebService

//设置package包名称以及导入依赖的类
package uk.gov.homeoffice.mercury.boot.configuration

import java.net.URL
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws.ahc.AhcWSClient
import uk.gov.homeoffice.configuration.HasConfig
import uk.gov.homeoffice.web.WebService

object HocsWebService extends HasConfig {
  def apply() = {
    val webServiceHost = new URL(config.getString("web-services.hocs.uri"))

    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    val wsClient = AhcWSClient()

    sys addShutdownHook {
      system.terminate()
      wsClient.close()
    }

    new WebService(webServiceHost, wsClient)
  }
} 
开发者ID:UKHomeOffice,项目名称:mercury,代码行数:26,代码来源:HocsWebService.scala


示例8: HttpTest

//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.github.nscala_time.time.Imports._
import play.api.libs.ws._
import play.api.libs.ws.ahc.AhcWSClient
//import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Await
import scala.concurrent.duration.{Duration, SECONDS}

object HttpTest extends App{

  val url = "http://pit-devvm-opswisemaster2.snc1/opswise/resources/task/ops-task-launch"
  val userName = "ramsubramani"
  val password = "Savitha1$"

  implicit val actor = ActorSystem()
  implicit val materializer = ActorMaterializer()
  val ws = AhcWSClient()
  val request = ws.url(url)
                  .withAuth(userName, password, WSAuthScheme.BASIC)
                  .withHeaders( "Content-Type" -> "application/xml")


  val startDate = DateTime.parse("2017-01-01")
  val endDate = DateTime.parse("2017-01-10")
  val jobName = "Ramesh_test"

  for ( date: DateTime <- startDate to endDate by 1.day){

    val dt = date.toString("yyyy-MM-dd")
    val dtKey = dt.replace("-","")
    val dt1 = date + 1.day toString("yyyy-MM-dd")

    val variableName = "context"
    val variableValue = s"""--context=start_date_key:${dtKey},end_date_key:${dtKey},wf_key:${dtKey},start_date:${dt},end_date:${dt},load_date:${dt},load_start_date:${dt1}"""

    val data =
      <task-launch>
        <name>{jobName}</name>
        <variables>
          <variable>
            <name>{variableName}</name>
            <value>{variableValue}</value>
          </variable>
        </variables>
      </task-launch>

    println(data)
    val resp = request.post(data)
    val result = Await.result(resp, Duration( 5, SECONDS))
    println( result.body)
  }

  ws.close()
  actor.terminate()

} 
开发者ID:ramesavi,项目名称:play-http-example,代码行数:59,代码来源:HttpPostTest.scala


示例9: CommandsTest

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

import java.time.{LocalDateTime, OffsetDateTime, ZoneOffset}
import java.util.UUID

import akka.stream.Materializer
import org.scalatest.{AsyncFreeSpec, BeforeAndAfterAll}
import endpoints.play.client.{CirceEntities, Endpoints}
import play.api.libs.ws.ahc.{AhcWSClient, AhcWSClientConfig}
import play.core.server.NettyServer

import scala.concurrent.Future
import scala.math.BigDecimal

class CommandsTest extends AsyncFreeSpec with BeforeAndAfterAll {

  private val server = NettyServer.fromRouter()(Commands.routes)

  implicit val materializer: Materializer = server.materializer
  private val wsClient = AhcWSClient(AhcWSClientConfig())

  object client
    extends Endpoints("http://localhost:9000", wsClient)
      with CirceEntities
      with CommandsEndpoints

  override def afterAll(): Unit = {
    server.stop()
    wsClient.close()
  }

  "Commands" - {

    val arbitraryDate = OffsetDateTime.of(LocalDateTime.of(2017, 1, 8, 12, 34, 56), ZoneOffset.UTC).toInstant
    val arbitraryValue = BigDecimal(10)

    "create a new meter" in {
      client.command(CreateMeter("electricity")).map { maybeEvent =>
        assert(maybeEvent.collect { case StoredEvent(_, MeterCreated(_, "electricity")) => () }.nonEmpty)
      }
    }
    "create a meter and add readings to it" in {
      for {
        maybeCreatedEvent <- client.command(CreateMeter("water"))
        id <-
          maybeCreatedEvent
            .collect { case StoredEvent(_, MeterCreated(id, _)) => id }
            .fold[Future[UUID]](Future.failed(new NoSuchElementException))(Future.successful)
        maybeAddedEvent <- client.command(AddRecord(id, arbitraryDate, arbitraryValue))
        _ <-
          maybeAddedEvent
            .collect { case StoredEvent(_, RecordAdded(`id`, `arbitraryDate`, `arbitraryValue`)) => () }
            .fold[Future[Unit]](Future.failed(new NoSuchElementException))(Future.successful)
      } yield assert(true)
    }
  }

} 
开发者ID:julienrf,项目名称:endpoints,代码行数:59,代码来源:CommandsTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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