play.api.libs.ws.ahc.AhcWSClient Scala Examples

The following examples show how to use play.api.libs.ws.ahc.AhcWSClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: NominatimLookup.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package examples.nominatim

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import play.api.libs.ws.ahc.AhcWSClient
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.JsonNode
import clients.HTTPClient

// SEE: Prefix.cc Lookup - http://prefix.cc/foaf.file.json

class NominatimLookup {

  val http = HTTPClient

  def start() {
    http.start()
  }

  def stop() {
    http.stop()
  }

  def nominatim(address: String) = {

    val url = "http://nominatim.openstreetmap.org/search"

    val parameters = Map(
      "q" -> address,
      "addressdetails" -> "1",
      "format" -> "json",
      "limit" -> "4",
      "addressdetails" -> "1",
      "dedupe" -> "1",
      "extratags" -> "1",
      "namedetails" -> "1").toList

    val ret = http.ws.url(url)
      .withQueryString(parameters: _*)
      .get()
      .map { response =>
        response.status match {
          case 200 => response.body
          case _   => "{}"
        }

      }

    ret

  }

}

object MainNominatimLookup extends App {

  import scala.collection.JavaConversions._
  import scala.collection.JavaConverters._

  val nominatim = new NominatimLookup
  nominatim.start()

  val json_mapper = new ObjectMapper
  val json_reader = json_mapper.reader()

  val result = Await.ready(nominatim.nominatim("135 pilkington avenue, birmingham"), Duration.Inf)
    .value.get.get

  val json_list: List[JsonNode] = json_reader.readTree(result).elements().toList

  // simulazione di output...
  if (json_list.size > 0) {
    println(s"RESULTS [${json_list.size}]")
    json_list
      .zipWithIndex
      .foreach {
        case (node, i) =>
          println(s"result ${i + 1}")
          println(node.get("place_id"))
          println(node.get("address").get("road").asText() + ", " + node.get("address").get("house_number").asText())
      }
  } else {
    println("cannot find results...")
  }

  nominatim.stop()

} 
Example 2
Source File: TestingHttpApi.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package it.almawave.linkeddata.kb.http

import play.api.inject.guice.GuiceApplicationBuilder
import org.junit.Test
import org.junit.After
import play.api.Application
import org.junit.Before
import it.almawave.linkeddata.kb.utils.JSONHelper
import play.api.libs.ws.WSClient
import org.asynchttpclient.DefaultAsyncHttpClient
import play.api.libs.ws.ssl.SystemConfiguration
import akka.stream.ActorMaterializer
import play.api.libs.ws.ahc.AhcWSClient
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import java.net.URL
import com.typesafe.config.ConfigFactory

class TestingHttpApi {

  var app: Application = null
  var conf = ConfigFactory.empty()
  var ws: WSClient = null
  var app_url = new URL("http://localhost:8080")

  @Test
  def testing_contexts() {

    //    curl -X GET http://localhost:8999/kb/v1/prefixes/lookup?prefix=no_pref 
    //    -H  "accept: application/json" 
    //    -H  "content-type: application/json"

    val fut = ws.url(s"http://localhost:8999/kb/v1/prefixes/lookup")
      .withHeaders(("accept", "application/json"))
      .withHeaders(("content-type", "application/json"))
      .withFollowRedirects(true)
      .withQueryString(("prefix", "muapit"))
      .get()

    val results = Await.result(fut, Duration.Inf)
    println(results.body)

  }

  @Before
  def before() {

    app = GuiceApplicationBuilder()
      .build()

    conf = app.configuration.underlying

    // play.app.local.url
    // play.server.http.address
    // play.server.http.port

    println(JSONHelper.writeToString(conf.root().unwrapped()))

    app_url = new URL(conf.getString("app.local.url"))

    println(s"\n\nrunning at ${app_url}")

    val materializer = ActorMaterializer()(app.actorSystem)
    ws = AhcWSClient()(materializer)

  }

  @After
  def after() {
    ws.close()
    app.stop()
  }

} 
Example 3
Source File: SemanticRepositorySpecs.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package specs

import org.junit.runner.RunWith

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

import play.api.test._
import play.api.http.Status
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ahc.AhcWSClient
import org.specs2.runner.JUnitRunner
import org.specs2.mutable.Specification
import play.api.libs.json.Json
//import it.almawave.linkeddata.kb.utils.ConfigHelper

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import play.twirl.api.Content
import play.api.test.Helpers._
import play.api.libs.json.JsObject
import java.io.File
import play.api.http.Writeable
import akka.stream.scaladsl.Source
import play.api.mvc.MultipartFormData
import play.api.libs.Files.TemporaryFile
import java.nio.file.Files
import org.asynchttpclient.AsyncHttpClient
import play.api.libs.ws.WS
import akka.util.ByteString
import play.api.mvc.MultipartFormData.DataPart
import play.api.mvc.MultipartFormData.FilePart
import akka.stream.scaladsl.FileIO
import play.api.libs.ws.WSClient

/*
 * TODO: REWRITE
 */
@RunWith(classOf[JUnitRunner])
class SemanticRepositorySpecs extends Specification {

  def application: Application = GuiceApplicationBuilder().build()

  "The semantic repository" should {

    "call kb/v1/contexts to obtain a list of contexts" in {
      new WithServer(app = application, port = 9999) {
        WsTestClient.withClient { implicit client =>

          val response: WSResponse = Await.result[WSResponse](
            client.url(s"http://localhost:${port}/kb/v1/contexts").execute,
            Duration.Inf)

          response.status must be equalTo Status.OK
          response.json.as[Seq[JsObject]].size must be equals 0
          // response.json.as[Seq[JsObject]].size must be greaterThan 0 // if pre-loaded ontologies!

        }
      }
    }

    "call kb/v1/contexts ensuring all contexts have triples" in {
      new WithServer(app = application, port = 9999) {
        WsTestClient.withClient { implicit client =>

          val response: WSResponse = Await.result[WSResponse](
            client.url(s"http://localhost:${port}/kb/v1/contexts").execute,
            Duration.Inf)

          val json_list = response.json.as[Seq[JsObject]]
          forall(json_list)((_) must not beNull)
          forall(json_list)(_.keys must contain("context", "triples"))
          forall(json_list)(item => (item \ "triples").get.as[Int] > 0)

        }
      }
    }

  }

} 
Example 4
Source File: NifiProcessorSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.ingestion.nifi


import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.typesafe.config.Config
import it.gov.daf.catalogmanager.MetaCatalog
import it.gov.daf.catalogmanager.json._
import it.gov.daf.ingestion.metacatalog.MetaCatalogProcessor
import org.scalatest.{AsyncFlatSpec, Matchers}
import play.api.libs.json._
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ahc.AhcWSClient

import scala.concurrent.Future
import scala.io.Source

class NifiProcessorSpec extends AsyncFlatSpec with Matchers {

  "A Nifi Processor " should "create a nifi pipeline for a correct meta catalog entry" in {

    val in = this.getClass.getResourceAsStream("/data_test.json")
    val sMetaCatalog = Source.fromInputStream(in).getLines().mkString(" ")
    in.close()

    val parsed = Json.parse(sMetaCatalog)
    val metaCatalog: JsResult[MetaCatalog] = Json.fromJson[MetaCatalog](parsed)

    metaCatalog.isSuccess shouldBe true

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

    implicit val config: Config = com.typesafe.config.ConfigFactory.load()
    implicit val ec = system.dispatcher

    def closeAll(): Unit = {
      system.terminate()
      materializer.shutdown()
      wsClient.close()
    }

    val fResult = NifiProcessor(metaCatalog.get).createDataFlow()

    fResult.map { response =>
      println(response)
      closeAll()
      true shouldBe true
    }
  }


} 
Example 5
Source File: TestAbstractModule.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers.modules

import akka.stream.Materializer
import daf.util.TestCache
import org.pac4j.play.store.{ PlayCacheSessionStore, PlaySessionStore }
import play.api.{ Configuration, Environment }
import play.api.inject.Module
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSClient
import play.api.mvc.BodyParsers
import play.cache.{ CacheApi, DefaultCacheApi }
import play.api.cache.{ CacheApi => ApiCacheApi }
import play.api.inject.guice.GuiceInjectorBuilder

abstract class TestAbstractModule extends Module {

  private lazy val injector = new GuiceInjectorBuilder().bindings(this).injector()

  private lazy val sessionStoreInstance: PlaySessionStore = injector.instanceOf { classOf[PlaySessionStore] }
  private lazy val wsClientInstance: WSClient = injector.instanceOf { classOf[WSClient] }
  private lazy val bodyParsersInstance: BodyParsers = BodyParsers

  final def sessionStore: PlaySessionStore = sessionStoreInstance
  final def ws: WSClient = wsClientInstance
  final def bodyParsers: BodyParsers = bodyParsersInstance

  protected implicit def materializer: Materializer

  override def bindings(environment: Environment, configuration: Configuration) = Seq(
    bind(classOf[ApiCacheApi]).to(classOf[TestCache]),
    bind(classOf[CacheApi]).to(classOf[DefaultCacheApi]),
    bind(classOf[PlaySessionStore]).to(classOf[PlayCacheSessionStore]),
    bind(classOf[BodyParsers]).to(BodyParsers),
    bind(classOf[WSClient]).toInstance(AhcWSClient())
  )
} 
Example 6
Source File: ServiceSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.{File, FileNotFoundException, IOException}
import java.net.ServerSocket
import java.util.Base64

import it.gov.daf.entitymanager.Entity
import it.gov.daf.entitymanager.client.Entity_managerClient
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAfterAll
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.ahc.AhcWSClient
import play.api.test.WithServer

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{Failure, Random, Try}

@SuppressWarnings(
  Array(
    "org.wartremover.warts.NonUnitStatements",
    "org.wartremover.warts.Throw",
    "org.wartremover.warts.Var"
  )
)
class ServiceSpec extends Specification with BeforeAfterAll {

  def getAvailablePort: Int = {
    try {
      val socket = new ServerSocket(0)
      try {
        socket.getLocalPort
      } finally {
        socket.close()
      }
    } catch {
      case e: IOException =>
        throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e)
    }
  }

  private def constructTempDir(dirPrefix: String): Try[File] = Try {
    val rndrange = 10000000
    val file = new File(System.getProperty("java.io.tmpdir"), s"$dirPrefix${Random.nextInt(rndrange)}")
    if (!file.mkdirs())
      throw new RuntimeException("could not create temp directory: " + file.getAbsolutePath)
    file.deleteOnExit()
    file
  }

  private def deleteDirectory(path: File): Boolean = {
    if (!path.exists()) {
      throw new FileNotFoundException(path.getAbsolutePath)
    }
    var ret = true
    if (path.isDirectory)
      path.listFiles().foreach(f => ret = ret && deleteDirectory(f))
    ret && path.delete()
  }

  var tmpDir: Try[File] = Failure[File](new Exception(""))
  
  def application: Application = GuiceApplicationBuilder().
    configure("pac4j.authenticator" -> "test").
    configure("janusgraph.storage.directory" -> s"${tmpDir.map(_.getCanonicalPath).getOrElse("db")}/berkeleyje").
    configure("janusgraph.index.search.directory" -> s"${tmpDir.map(_.getCanonicalPath).getOrElse("db")}/lucene").
    build()

  "The entity_manager" should {
    "create an entity and retrieve it correctly" in new WithServer(app = application, port = getAvailablePort) {

      val ws: AhcWSClient = AhcWSClient()

      val plainCreds = "david:david"
      val plainCredsBytes = plainCreds.getBytes
      val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes)
      val base64Creds = new String(base64CredsBytes)

      val client = new Entity_managerClient(ws)(s"http://localhost:$port")

      val result = Await.result(client.createEntity(s"Basic $base64Creds", Entity("DAVID")), Duration.Inf)
      val entity = Await.result(client.getEntity(s"Basic $base64Creds", "DAVID"), Duration.Inf)

      entity must beEqualTo(Entity("DAVID"))
    }
  }

  override def beforeAll(): Unit = tmpDir = constructTempDir("test")

  override def afterAll(): Unit = tmpDir.foreach(deleteDirectory(_))
} 
Example 7
Source File: ServiceSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.{IOException, File => JFile}
import java.net.ServerSocket
import java.util.Base64

import it.gov.daf.securitymanager.client.Security_managerClient
import org.specs2.mutable.Specification
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.ahc.AhcWSClient
import play.api.libs.ws.{WSAuthScheme, WSResponse}
import play.api.test.{WithServer, WsTestClient}

import scala.concurrent.Await
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.duration.Duration

//@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw"))
class ServiceSpec extends Specification {

  def getAvailablePort: Int = {
    try {
      val socket = new ServerSocket(0)
      try {
        socket.getLocalPort
      } finally {
        socket.close()
      }
    } catch {
      case e: IOException =>
        throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e)
    }
  }

  def application: Application = GuiceApplicationBuilder().
    configure("pac4j.authenticator" -> "test").
    build()

  "The security_manager" should {
    "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) {

      private val token = WsTestClient.withClient { implicit client =>
        val response: WSResponse = Await.result[WSResponse](client.
          url(s"http://localhost:$port/security-manager/v1/token").
          withAuth("david", "david", WSAuthScheme.BASIC).
          execute, Duration.Inf)
        response.body
      }

      val ws: AhcWSClient = AhcWSClient()

      val plainCreds = "david:david"
      val plainCredsBytes = plainCreds.getBytes
      val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes)
      val base64Creds = new String(base64CredsBytes)

      val client = new Security_managerClient(ws)(s"http://localhost:$port")

      val token2 = Await.result(client.token(s"Basic $base64Creds"), Duration.Inf)

      s""""$token2"""" must be equalTo token

      Await.result(client.token(s"Bearer $token2").map(token => s""""$token""""), Duration.Inf) must be equalTo token
    }
  }

} 
Example 8
Source File: Iot_managerSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.{IOException, File => JFile}
import java.net.ServerSocket
import java.util.Base64

import better.files._
import it.gov.daf.iotmanager.client.Iot_managerClient
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAfterAll
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.ahc.AhcWSClient
import play.api.libs.ws.{WSAuthScheme, WSResponse}
import play.api.test.{WithServer, WsTestClient}

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.util.{Failure, Try}

import org.apache.solr.client.solrj.embedded.JettyConfig
import org.apache.solr.client.solrj.embedded.JettySolrRunner
import org.eclipse.jetty.servlet.ServletHolder


@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw"))
class Iot_managerSpec extends Specification with BeforeAfterAll {

  import Iot_managerSpec._

  def getAvailablePort: Int = {
    try {
      val socket = new ServerSocket(0)
      try {
        socket.getLocalPort
      } finally {
        socket.close()
      }
    } catch {
      case e: IOException =>
        throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e)
    }
  }

  def application: Application = GuiceApplicationBuilder().
    configure("hadoop_conf_dir" -> s"${ServiceSpec.confPath.pathAsString}").
    configure("pac4j.authenticator" -> "test").
    build()

  "The security_manager" should {
    "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) {
      print("ciao ciao")


    }
  }

  override def beforeAll(): Unit = {
    val solrXml = new Nothing("/solr/home/solr.xml")
    val solrHomeDir = solrXml.getParentFile

    val port = 8080
    val context = "/solr"
    // use org.apache.solr.client.solrj.embedded.JettySolrRunner
    val jettySolr = new Nothing(solrHomeDir.getAbsolutePath, context, port)

    val waitUntilTheSolrWebAppHasStarted = true
    jettySolr.start(waitUntilTheSolrWebAppHasStarted)
  }

  override def afterAll(): Unit = {
    jettySolr.stop()
  }
}

@SuppressWarnings(Array("org.wartremover.warts.Var", "org.wartremover.warts.Null"))
object Iot_managerSpec {



} 
Example 9
Source File: DirManager.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package it.gov.daf.catalogmanager.listeners



import java.net.URLEncoder

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{ FileIO, Source }
import net.caoticode.dirwatcher.FSListener
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSClient
import play.api.mvc.MultipartFormData.FilePart
import play.Logger
import scala.concurrent.Future

class DirManager() extends FSListener {

  import java.nio.file.Path
  import scala.concurrent.ExecutionContext.Implicits.global

  val logger = Logger.underlying()

  override def onCreate(ref: Path): Unit = {

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

    val name = ref.getParent.getFileName.toString
    println(name)
    val uri: Option[String] = IngestionUtils.datasetsNameUri.get(name)
    val logicalUri = URLEncoder.encode(uri.get, "UTF-8")
    logger.debug("logicalUri: " + logicalUri)

    call(wsClient)
      .andThen { case _ => wsClient.close() }
      .andThen { case _ => system.terminate() }

    def call(wsClient: WSClient): Future[Unit] = {
      wsClient.url("http://localhost:9001/ingestion-manager/v1/add-datasets/" + logicalUri)
        //.withHeaders("content-type" -> "multipart/form-data")
        .post(
          Source(FilePart("upfile", name, None, FileIO.fromPath(ref)) :: List())).map { response =>
            val statusText: String = response.statusText
            logger.debug(s"Got a response $statusText")
          }
    }
    logger.debug(s"created $ref")
  }

  override def onDelete(ref: Path): Unit = println(s"deleted $ref")
  override def onModify(ref: Path): Unit = println(s"modified $ref")
} 
Example 10
Source File: CatalogControllersSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.IOException
import java.net.ServerSocket

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import catalog_manager.yaml.MetaCatalog
import org.specs2.mutable.Specification
import play.api.Application
import play.api.http.Status
import play.api.routing.Router
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{JsArray, JsValue, Json}
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ahc.AhcWSClient
import play.api.test._
import it.gov.daf.catalogmanager
import it.gov.daf.catalogmanager.client.Catalog_managerClient

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


class CatalogControllersSpec extends Specification  {

  def application: Application = GuiceApplicationBuilder().build()

  import catalog_manager.yaml.BodyReads.MetaCatalogReads

  "The catalog-manager" should {
    "Call catalog-manager/v1/dataset-catalogs return ok status" in
      new WithServer(app = application, port = 9000) {
        WsTestClient.withClient { implicit client =>
          val response: WSResponse = Await.result[WSResponse](client.
            url(s"http://localhost:9001/catalog-manager/v1/dataset-catalogs").
            execute, Duration.Inf)
          println(response.status)
          response.status must be equalTo Status.OK
        }
      }

    "Call catalog-manager/v1/dataset-catalogs return a non empty list if" +
      "you have error maybe is necessaty to add data to db" in
      new WithServer(app = application, port = 9000) {
        WsTestClient.withClient { implicit client =>
          val response: WSResponse = Await.result[WSResponse](client.
            url(s"http://localhost:9001/catalog-manager/v1/dataset-catalogs").
            execute, Duration.Inf)
          println(response.status)
          println("ALE")
          println(response.body)
          val json: JsValue = Json.parse(response.body)
          json.as[JsArray].value.size must be greaterThan (0)
        }
      }


    "The catalog-manager" should {
      "Call catalog-manager/v1/dataset-catalogs/{logical_uri} return ok status" in
        new WithServer(app = application, port = 9000) {
          val logicalUri = "daf://dataset/std/standard/standard/uri_cultura/standard"
          val url = s"http://localhost:9001/catalog-manager/v1/dataset-catalogs/$logicalUri"
          println(url)
          WsTestClient.withClient { implicit client =>
            val response: WSResponse = Await.result[WSResponse](client.
              url(url).
              execute, Duration.Inf)
            println(response.status)
            response.status must be equalTo Status.OK
          }
        }
    }

    "The catalog-manager" should {
      "Call catalog-manager/v1/dataset-catalogs/{anything} return 401" in
        new WithServer(app = application, port = 9000) {
          val logicalUri = "anything"
          val url = s"http://localhost:9001/catalog-manager/v1/dataset-catalogs/$logicalUri"
          println(url)
          WsTestClient.withClient { implicit client =>
            val response: WSResponse = Await.result[WSResponse](client.
              url(url).
              execute, Duration.Inf)
            println(response.status)
            response.status must be equalTo 401
          }
        }
    }
  }
} 
Example 11
Source File: CommandsTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package cqrs.commands

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

import org.scalatest.BeforeAndAfterAll
import endpoints4s.play.client.{Endpoints, JsonEntitiesFromCodecs}
import endpoints4s.play.server.PlayComponents
import play.api.Mode
import play.api.libs.ws.ahc.{AhcWSClient, AhcWSClientConfig}
import play.core.server.{NettyServer, ServerConfig}

import scala.concurrent.Future
import scala.math.BigDecimal
import org.scalatest.freespec.AsyncFreeSpec

class CommandsTest extends AsyncFreeSpec with BeforeAndAfterAll {

  private val server =
    NettyServer.fromRouterWithComponents(ServerConfig(mode = Mode.Test)) { components =>
      new Commands(PlayComponents.fromBuiltInComponents(components)).routes
    }
  val app = server.applicationProvider.get.get
  import app.materializer
  private val wsClient = AhcWSClient(AhcWSClientConfig())

  object client
      extends Endpoints("http://localhost:9000", wsClient)
      with JsonEntitiesFromCodecs
      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)
    }
  }

} 
Example 12
Source File: Main.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package cqrs.infra

import cqrs.commands.Commands
import cqrs.publicserver.{BootstrapEndpoints, PublicServer}
import cqrs.queries.{Queries, QueriesService}
import endpoints4s.play.server.PlayComponents
import play.api.Mode
import play.api.libs.ws.ahc.{AhcWSClient, AhcWSClientConfig}
import play.api.routing.Router
import play.core.server.{DefaultNettyServerComponents, ServerConfig}


object Main extends App {

  object commandsService extends PlayService(port = 9001, Mode.Prod) {
    lazy val commands = new Commands(playComponents)
    lazy val router = Router.from(commands.routes)
  }

  object queriesService extends PlayService(port = 9002, Mode.Prod) {
    lazy val wsClient = AhcWSClient(AhcWSClientConfig())
    lazy val service = new QueriesService(
      baseUrl(commandsService.port),
      wsClient,
      actorSystem.scheduler
    )
    lazy val queries = new Queries(service, playComponents)
    lazy val router = Router.from(queries.routes)
  }

  object publicService extends PlayService(port = 9000, Mode.Prod) {
    lazy val routes =
      new cqrs.publicserver.Router(
        new PublicServer(
          baseUrl(commandsService.port),
          baseUrl(queriesService.port),
          queriesService.wsClient,
          playComponents
        ),
        new BootstrapEndpoints(playComponents)
      ).routes
    lazy val router = Router.from(routes)
  }

  def baseUrl(port: Int): String = s"http://localhost:$port"

  // Start the commands service
  commandsService.server
  // Start the queries service
  queriesService.server
  // Start the public server
  publicService.server

  // …

  Runtime.getRuntime.addShutdownHook(new Thread {
    override def run(): Unit = {
      queriesService.wsClient.close()
      commandsService.server.stop()
      queriesService.server.stop()
      publicService.server.stop()
    }
  })

}

abstract class PlayService(val port: Int, mode: Mode) extends DefaultNettyServerComponents {
  override lazy val serverConfig = ServerConfig(port = Some(port), mode = mode)
  lazy val playComponents = PlayComponents.fromBuiltInComponents(this)
} 
Example 13
Source File: WSClientProvider.scala    From http-verbs   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.play.connectors

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

trait WSClientProvider {
  implicit val client: WSClient
}

trait DefaultWSClientProvider extends WSClientProvider {
  val builder    = new AhcConfigBuilder()
  val ahcBuilder = builder.configure()
  val ahcConfig  = ahcBuilder.build()

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

  implicit val client = new AhcWSClient(ahcConfig)
} 
Example 14
Source File: WSClientContext.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.test.contexts

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import org.specs2.execute.{AsResult, Result}
import org.specs2.specification.ForEach
import org.specs2.specification.mutable.ExecutionEnvironment
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSClient


trait WSClientContext extends ForEach[WSClient] {
  self: ExecutionEnvironment =>

  override protected def foreach[R: AsResult](f: (WSClient) => R): Result = {
    implicit val actorSystem = ActorSystem("nomad-http-client")
    try {
      implicit val materializer = ActorMaterializer()
      val client: WSClient = AhcWSClient()
      try AsResult(f(client))
      finally client.close()
    } finally {
      actorSystem.terminate()
    }
  }
} 
Example 15
Source File: BintrayDownloadPoms.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index.data
package bintray

import download.PlayWsDownloader
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path}

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

class BintrayDownloadPoms(paths: DataPaths)(
    implicit val system: ActorSystem,
    implicit val materializer: ActorMaterializer
) extends PlayWsDownloader {

  private val log = LoggerFactory.getLogger(getClass)

  private val bintrayPomBase = paths.poms(LocalPomRepository.Bintray)

  
  def run(): Unit = {

    download[BintraySearch, Unit]("Downloading POMs",
                                  searchesBySha1,
                                  downloadRequest,
                                  processPomDownload,
                                  parallelism = 32)
    ()
  }
} 
Example 16
Source File: WSClient.scala    From play-auditing   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.audit

import akka.stream.Materializer
import org.slf4j.{Logger, LoggerFactory}
import play.api.libs.ws.WSClientConfig
import play.api.libs.ws.ahc.{AhcConfigBuilder, AhcWSClientConfig, AhcWSClient}

import scala.concurrent.Future
import scala.concurrent.duration.Duration


package object handler {
  type WSClient = play.api.libs.ws.WSClient

  object WSClient {
    private val logger: Logger = LoggerFactory.getLogger(getClass)

    def apply(
      connectTimeout: Duration,
      requestTimeout: Duration,
      userAgent     : String
    )(implicit
      materializer: Materializer
    ): WSClient =
      new AhcWSClient(
        new AhcConfigBuilder(
          ahcConfig = AhcWSClientConfig()
                        .copy(wsClientConfig = WSClientConfig()
                          .copy(
                            connectionTimeout = connectTimeout,
                            requestTimeout    = requestTimeout,
                            userAgent         = Some(userAgent)

                          )
                        )
        ).build()
      )
  }
}