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

Scala NingWSClient类代码示例

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

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



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

示例1: Main

//设置package包名称以及导入依赖的类
package com.skat.bowling.main

import com.ning.http.client.AsyncHttpClientConfig.Builder
import com.skat.bowling.caseclasses.{Game, GetResponse, PostRequest}
import play.api.libs.ws.DefaultWSClientConfig
import play.api.libs.ws.ning.{NingAsyncHttpClientConfigBuilder, NingWSClient}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success, Try}

object Main {

  import play.api.libs.json._

  implicit val residentFormat = Json.format[GetResponse]
  implicit val postRequestFormat = Json.format[PostRequest]

  //See: http://carminedimascio.com/2015/02/how-to-use-the-play-ws-library-in-a-standalone-scala-app/

  def main(args: Array[String]): Unit = {

    val url = "http://37.139.2.74/api/points"
    val result = scala.io.Source.fromURL(url).mkString
    println(result)
    val json = Json.parse(result)
    val getResponse: Try[GetResponse] = json.validate[GetResponse] match {
      case s: JsSuccess[GetResponse] => {
        Success(s.get)
      }
      case e: JsError => {
        Failure(new Exception(s"Parse Exception: $e"))
      }
    }

    println(s"GET: $getResponse")
    val config = new NingAsyncHttpClientConfigBuilder(DefaultWSClientConfig()).build
    val builder = new Builder(config)
    val client = new NingWSClient(builder.build)

    val game = Game.createFromFrameResult(getResponse)
    println(s"Result.total: ${game.gameResultTotal}")

    val innerJson: String = Json.toJson(PostRequest(game.gameResultTotal)).toString()
    println(s"TOKEN: ${getResponse.get.token}")
    println(s"innerJson: ${innerJson}")

    client.url(s"$url?token=${getResponse.get.token}").post(innerJson).onComplete {
      case Success(content) => {
        println(s"Successful response: Status: ${content.status} Body: ${content.body}")
      }
      case Failure(t) => {
        println(s"An error has occured: ${t.getMessage}")
      }
    }
    Thread.sleep(5000)
    client.close()
  }

} 
开发者ID:GoranSchumacher,项目名称:skat-bowling,代码行数:60,代码来源:Main.scala


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


示例3: name

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

import java.io.File

import anchorman.core._
import anchorman.docx._
import anchorman.media._
import org.scalatest._
import play.api.libs.ws.ning.NingWSClient

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

trait IntegrationSpec extends FreeSpec {
  def name: String
  def doc: Document

  def directory: File =
    new File("target/it")

  def outputFile(extension: String): File =
    new File(directory, s"${name}.${extension}")

  s"${name} integration spec" - {
    val file = outputFile("docx")

    s"writes ${file.getPath}" in {
      val wsClient = NingWSClient()
      val mediaDownloader = new MediaDownloader(wsClient)
      val docxWriter = new DocxWriter(mediaDownloader)
      try {
        directory.mkdirs()
        Await.result(docxWriter.write(doc, file), 5.seconds)
      } finally {
        wsClient.close()
      }
    }
  }
} 
开发者ID:davegurnell,项目名称:anchorman,代码行数:41,代码来源:IntegrationSpec.scala


示例4: NewRelic

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

import com.iheart.sqs.Utils._
import play.Logger
import play.api.libs.ws.ning.NingWSClient
import scala.concurrent.ExecutionContext.Implicits.global

object NewRelic {

  val wsClient = NingWSClient()


  
  def postJson(entries: List[LogEntry]) = {
    DBUtils.incrNewRelicCounter(entries.size)
    val json = entries.asJ
    wsClient.url(insightUrl)
      .withHeaders(("X-Insert-Key", insightApiKey), ("Content-Type", "application/json"))
      .withRequestTimeout(2000)
      .post(json).map { response =>
        if (response.status != 200 ) {
          Logger.error("Invalid Status Code " + response.status.toString + " Error: " + response.body)
        }
      }
  }

  def sendToNewRelicChunk(entries: List[LogEntry], splitCount: Int): Unit = entries.nonEmpty match {
    case true =>
      postJson(entries.take(splitCount))
      sendToNewRelicChunk(entries.drop(splitCount), splitCount)
    case _ =>
      Logger.debug("Done with NewRelic Chunks")
  }

  def sendToNewRelic(entries: List[LogEntry], splitCount: Int = 2000) = {
    entries.isEmpty match {
      case true =>
        Logger.debug("Skipping NewRelic, no valid entries")
      case _ =>
        Logger.debug("Sending Chunks to NewRelic")
        sendToNewRelicChunk(entries, splitCount)
    }
  }
} 
开发者ID:iheartradio,项目名称:fastly-sqs,代码行数:45,代码来源:NewRelic.scala


示例5: get

//设置package包名称以及导入依赖的类
package com.reactivecore.quotes.workshop.api

import play.api.libs.ws.WSResponse
import play.api.libs.ws.ning.NingWSClient

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

package object feature {

  def get(url: String): Future[WSResponse] = {
    implicit val client = NingWSClient()

    client.url(url).get().andThen {
      case response =>
        client.close()
        response
    }
  }

  def options(url: String): Future[WSResponse] = {
    implicit val client = NingWSClient()

    client.url(url).options().andThen {
      case response =>
        client.close()
        response
    }
  }

} 
开发者ID:bschaff,项目名称:quotes-workshop-api,代码行数:32,代码来源:package.scala


示例6: DefaultRpgApp

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

import activities.{ActivitiesRepositoryComponent, DefaultActivitiesRepositoryComponent}
import chronicles.{ChroniclesRepositoryComponent, DefaultChroniclesRepositoryComponent}
import com.google.inject.{ImplementedBy, Singleton}
import context.{Futures, Neo4jConfigurations, PlayApp, WebServiceClient}
import org.anormcypher.Neo4jREST
import play.api.libs.ws.ning.NingWSClient
import play.api.{Application, Play}
import utils.auth0._

import scala.concurrent.ExecutionContext


@ImplementedBy(classOf[DefaultRpgApp])
trait RpgApp
  extends PlayApp
  with Futures
  with AppFormats
  with Auth0SecurityComponent
  with Auth0DetailsApiComponent
  with ActivitiesRepositoryComponent
  with ChroniclesRepositoryComponent

trait Injector
  extends PlayApp
  with Futures
  with WebServiceClient
  with Neo4jConfigurations
  with Auth0Context {

  override implicit val current: Application = Play.current
  override implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext

  override implicit val wsclient = NingWSClient()

  override lazy implicit val neo4jConnection = Neo4jREST(current.configuration.getString("neo.server.name").get,
    current.configuration.getInt("neo.server.port").get,
    "/db/data/",
    current.configuration.getString("neo.user.name").get,
    current.configuration.getString("neo.user.passwd").get)(wsclient)


  override val auth0Endpoint: String = current.configuration.getString("auth0.endpoint").get
  override val auth0ClientId: String = current.configuration.getString("auth0.clientId").get
  override val auth0ClientSecret: String = current.configuration.getString("auth0.clientSecret").get
}

@Singleton
class DefaultRpgApp
  extends Injector
  with DefaultAuth0SecurityComponent
  with DefaultAuth0DetailsApiComponent
  with DefaultActivitiesRepositoryComponent
  with DefaultChroniclesRepositoryComponent
  with RpgApp 
开发者ID:dohr-michael,项目名称:rpg_character,代码行数:57,代码来源:RpgApp.scala


示例7: MeetupSource

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

import com.carlossouza.models.{Member, Group, City}
import play.api.libs.json.JsValue
import play.api.libs.ws.ning.NingWSClient
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}
import play.api.libs.json.Json



class MeetupSource(client: NingWSClient, APIKey: String) {
  implicit val cityWrites = Json.format[City]
  implicit val groupWrites = Json.format[Group]
  implicit val memberWrites = Json.format[Member]

  val append = "&key=" + APIKey + "&sign=true"

  def getCities(country: String, numCities: Int): Future[List[City]] = {
    val url = "http://api.meetup.com/2/cities?country=" + country + "&page=" + numCities.toString + append
    client.url(url).get().map { response =>
      (response.json \ "results").as[List[City]]
    }
  }

  def findGroups(query: String, city: String, numGroups: Int, radius: Int = 10): Future[List[Group]] = {
    val url = "http://api.meetup.com/find/groups?location='" + city + "'&radius=" + radius + "&page=" + numGroups + "&text='" + query + "'" + append
    client.url(url).get().map { response =>
      response.json.as[List[Group]]
    }
  }

  def getMembers(groupId: Int): Future[List[Member]] = {
    val url = "http://api.meetup.com/2/members?group_id=" + groupId.toString + append
    client.url(url).get().map { response =>
      (response.json \ "results").as[List[Member]]
    }
  }

} 
开发者ID:cals80,项目名称:mlg,代码行数:42,代码来源:MeetupSource.scala


示例8: Main

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

import java.net.URLDecoder
import com.iheart.lambda.Utils._
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ning.NingWSClient
import scala.collection.JavaConverters._
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.amazonaws.services.lambda.runtime.Context
import scala.concurrent.{Future, Await}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global


class Main {

  val wsClient = NingWSClient()

  
  def handleEvent(event: S3Event, context: Context) = {
    event.getRecords.asScala.foreach { record =>
       val bucket = record.getS3.getBucket.getName
       val key = URLDecoder.decode(record.getS3.getObject.getKey,"UTF-8")
       println("Received key " + key)
       sendToNewRelic(parseLogFile(bucket,key))
    } 
  } 
} 
开发者ID:denen99,项目名称:fastly-lambda,代码行数:29,代码来源:Main.scala


示例9: MetaDefaultDCOS

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

import com.google.inject.AbstractModule
import com.ning.http.client.AsyncHttpClientConfigBean
import net.codingwell.scalaguice.ScalaModule
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.libs.ws.WSClient
import play.api.libs.ws.ning.NingWSClient
import services.{DCOSAuthTokenActor, DefaultMarathonClientFactory, MarathonClientFactory}

class MetaDefaultDCOS extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  override def configure(): Unit = {
    bind[MarathonClientFactory].to[DefaultMarathonClientFactory]
    bindActor[DCOSAuthTokenActor](DCOSAuthTokenActor.name)

    val config = new AsyncHttpClientConfigBean()
    config.setAcceptAnyCertificate(true)
    config.setFollowRedirect(true)
    val permissiveClient = NingWSClient(config)
    bind[WSClient].annotatedWithName("permissive-wsclient").toInstance(permissiveClient)
  }



} 
开发者ID:GalacticFog,项目名称:gestalt-meta,代码行数:27,代码来源:MetaDefaultDCOS.scala


示例10: MyGlobal

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

import com.ning.http.client.AsyncHttpClientConfig
import play.api.libs.ws.WSClient
import play.api.libs.ws.ning.NingWSClient
import play.api.{Application, GlobalSettings}


object MyGlobal extends GlobalSettings {

  private var clientVar: Option[WSClient] = None

  def customClient: WSClient = clientVar.get

  override def onStart(app: play.api.Application) = {
    val template = wsClientTemplateConfig(app)

    val builder = new AsyncHttpClientConfig.Builder(template)
    builder.setUseRawUrl(true) // stop Ning from fiddling with it...
    val config = builder.build()

    clientVar = Some(new NingWSClient(config))
  }

  private def wsClientTemplateConfig(app: play.api.Application): AsyncHttpClientConfig = {
    import play.api.libs.ws._
    import play.api.libs.ws.ning._

    val classLoader = app.classloader
    val parser = new DefaultWSConfigParser(configuration, classLoader)
    val builder = new NingAsyncHttpClientConfigBuilder(parser.parse())
    builder.build()
  }

  override def onStop(app: Application): Unit = {
    super.onStop(app)

    clientVar.foreach { client =>
      client.underlying[com.ning.http.client.AsyncHttpClient].close()
    }
  }
} 
开发者ID:edwardcallahan,项目名称:bintray-test-case,代码行数:43,代码来源:Global.scala


示例11: SmartiiAlexa

//设置package包名称以及导入依赖的类
package uk.co.smartii.alexa

import scala.io.Source
import scala.util.Random
import play.api.libs.ws.ning.NingWSClient

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.json._

object SmartiiAlexa {

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

  def ask(): String = {

    val futureResponse = wsClient.url(System.getenv("RESPONSE_URL")).get()
    // Has to be synchronous :(
    val response = Await.result(futureResponse, 2 seconds)

    response.json.as[String]
  }
} 
开发者ID:jimnybob,项目名称:smartii-skill-alexa,代码行数:29,代码来源:SmartiiAlexa.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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