akka.http.scaladsl.HttpExt Scala Examples

The following examples show how to use akka.http.scaladsl.HttpExt. 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: Registry.scala    From kanadi   with MIT License 5 votes vote down vote up
package org.zalando.kanadi.api

import java.net.URI

import defaults._
import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.{ContentTypes, HttpMethods, HttpRequest, Uri}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.Materializer
import com.typesafe.scalalogging.{Logger, LoggerTakingImplicit}
import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport._
import org.mdedetrich.webmodels.{FlowId, OAuth2TokenProvider}
import org.mdedetrich.webmodels.RequestHeaders.`X-Flow-ID`
import org.zalando.kanadi.models._

import scala.concurrent.{ExecutionContext, Future}

case class Registry(baseUri: URI, oAuth2TokenProvider: Option[OAuth2TokenProvider] = None)(implicit
                                                                                           kanadiHttpConfig: HttpConfig,
                                                                                           http: HttpExt,
                                                                                           materializer: Materializer)
    extends RegistryInterface {
  protected val logger: LoggerTakingImplicit[FlowId] = Logger.takingImplicit[FlowId](classOf[Registry])
  private val baseUri_                               = Uri(baseUri.toString)

  
  def partitionStrategies(implicit flowId: FlowId = randomFlowId(),
                          executionContext: ExecutionContext): Future[List[PartitionStrategy]] = {
    val uri =
      baseUri_.withPath(baseUri_.path / "registry" / "partition-strategies")

    val baseHeaders = List(RawHeader(`X-Flow-ID`, flowId.value))

    for {
      headers <- oAuth2TokenProvider match {
                  case None => Future.successful(baseHeaders)
                  case Some(futureProvider) =>
                    futureProvider.value().map { oAuth2Token =>
                      toHeader(oAuth2Token) +: baseHeaders
                    }
                }
      request  = HttpRequest(HttpMethods.GET, uri, headers)
      _        = logger.debug(request.toString)
      response <- http.singleRequest(request)
      result <- {
        if (response.status.isSuccess()) {
          Unmarshal(response.entity.httpEntity.withContentType(ContentTypes.`application/json`))
            .to[List[PartitionStrategy]]
        } else
          processNotSuccessful(request, response)
      }
    } yield result
  }

} 
Example 2
Source File: AkkaHttpBackend.scala    From drunk   with Apache License 2.0 5 votes vote down vote up
package com.github.jarlakxen.drunk.backend

import scala.collection.immutable
import scala.concurrent.{ExecutionContext, Future}
import akka.actor.ActorSystem
import akka.http.scaladsl.{Http, HttpExt}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpHeader, HttpMethods, HttpRequest, Uri}
import akka.stream.ActorMaterializer

class AkkaHttpBackend private[AkkaHttpBackend] (
  uri: Uri,
  headers: immutable.Seq[HttpHeader],
  httpExt: HttpExt
)(override implicit val as: ActorSystem, override implicit val mat: ActorMaterializer)
    extends AkkaBackend {

  def send(body: String): Future[(Int, String)] = {
    implicit val ec: ExecutionContext = as.dispatcher

    val req = HttpRequest(HttpMethods.POST, uri, headers, HttpEntity(ContentTypes.`application/json`, body))

    val res = httpExt.singleRequest(req)

    res.flatMap { hr =>
      val code = hr.status.intValue()

      val charsetFromHeaders = encodingFromContentType(hr.entity.contentType.toString).getOrElse("utf-8")
      val decodedResponse = decodeResponse(hr)
      val stringBody = bodyToString(decodedResponse, charsetFromHeaders)

      if (code >= 200 && code < 300) {
        stringBody.map { body =>
          hr.discardEntityBytes()
          (code, body)
        }
      } else {
        stringBody.flatMap { body =>
          hr.discardEntityBytes()
          Future.failed(new RuntimeException(s"${uri.toString} return $code with body: $body"))
        }
      }
    }
  }

}

object AkkaHttpBackend {
  val ContentTypeHeader = "Content-Type"

  def apply(
    uri: Uri,
    headers: immutable.Seq[HttpHeader] = Nil,
    httpExt: Option[HttpExt] = None
  )(implicit as: ActorSystem, mat: ActorMaterializer): AkkaHttpBackend = {

    val http = httpExt.getOrElse { Http(as) }
    new AkkaHttpBackend(uri, headers, http)
  }
} 
Example 3
Source File: AkkaInterpExampleMain.scala    From hammock   with MIT License 5 votes vote down vote up
package example.interpret
import akka.actor.ActorSystem
import akka.http.scaladsl.{Http, HttpExt}
import akka.stream.ActorMaterializer
import cats.effect.{ContextShift, IO}
import example.repr.{GetResp, GetRespWithQueryString, Req, Resp}
import hammock.{Hammock, Method}
import hammock.marshalling._
import hammock.circe.implicits._
import io.circe.generic.auto._
import hammock.akka.AkkaInterpreter._
import scala.concurrent.ExecutionContext

object AkkaInterpExampleMain extends App {

  implicit val actorSystem: ActorSystem        = ActorSystem()
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  implicit val ec: ExecutionContext            = ExecutionContext.Implicits.global
  implicit val cs: ContextShift[IO]            = IO.contextShift(ec)
  implicit val client: HttpExt                 = Http(actorSystem)

  //GET
  val getResp = Hammock
    .request(Method.GET, getUri, Map())
    .as[GetResp]
    .exec[IO]
    .unsafeRunSync

  println(s"GET::Response = $getResp")

  //GET with query string
  val getRespWithQueryString = Hammock
    .request(Method.GET, getUriWithQueryString, Map())
    .as[GetRespWithQueryString]
    .exec[IO]
    .unsafeRunSync

  println(s"GET with query string::Response = $getRespWithQueryString")

  //POST
  val postResp = Hammock
    .request(Method.POST, postUri, Map(), Some(Req("name", 4)))
    .as[Resp]
    .exec[IO]
    .unsafeRunSync

  println(s"POST::Response = $postResp")

  //PUT
  val putResp = Hammock
    .request(Method.PUT, putUri, Map(), Some(Req("name", 4)))
    .as[Resp]
    .exec[IO]
    .unsafeRunSync

  println(s"PUT::Response = $putResp")

  //DELETE
  val deleteResp = Hammock
    .request(Method.DELETE, deleteUri, Map(), Some(Req("name", 4)))
    .exec[IO]
    .unsafeRunSync

  println(s"DELETE::Response = $deleteResp")

  actorSystem.terminate()
} 
Example 4
Source File: InfluxAkkaClient.scala    From chronicler   with Apache License 2.0 5 votes vote down vote up
package com.github.fsanaulla.chronicler.akka.shared

import akka.actor.ActorSystem
import akka.http.scaladsl.{Http, HttpExt, HttpsConnectionContext}

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

abstract class InfluxAkkaClient(
    terminateActorSystem: Boolean,
    httpsContext: Option[HttpsConnectionContext]
  )(implicit system: ActorSystem,
    ec: ExecutionContext) { self: AutoCloseable =>

  private[akka] implicit val http: HttpExt = Http()

  private[akka] val (ctx, schema) =
    httpsContext
      .map(_ -> "https")
      .getOrElse(http.defaultClientHttpsContext -> "http")

  def close(): Unit =
    Await.ready(closeAsync(), Duration.Inf)

  def closeAsync(): Future[Unit] = {
    for {
      _ <- http.shutdownAllConnectionPools()
      _ <- if (terminateActorSystem) system.terminate().map(_ => {}) else Future.successful({})
    } yield {}
  }
} 
Example 5
Source File: AkkaRequestExecutor.scala    From chronicler   with Apache License 2.0 5 votes vote down vote up
package com.github.fsanaulla.chronicler.akka.shared.handlers

import akka.http.scaladsl.coding.Gzip
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.{`Accept-Encoding`, `Content-Encoding`, HttpEncodings}
import akka.http.scaladsl.{HttpExt, HttpsConnectionContext}
import com.github.fsanaulla.chronicler.core.components.RequestExecutor

import scala.concurrent.Future


  override def post(uri: Uri): Future[HttpResponse] = {
    val request = HttpRequest(
      method = HttpMethods.GET,
      uri = uri
    )

    http.singleRequest(
      request,
      connectionContext = ctx
    )
  }
} 
Example 6
Source File: GraphQlClientImpl.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.graphql

import akka.actor.ActorSystem
import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.model.HttpHeader.ParsingResult.Ok
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import play.api.libs.json.Json

import scala.concurrent.Future

case class GraphQlClientImpl(uri: String, headers: Map[String, String], akkaHttp: HttpExt)(
    implicit system: ActorSystem,
    materializer: ActorMaterializer
) extends GraphQlClient {
  import system.dispatcher

  def sendQuery(query: String): Future[GraphQlResponse] = {
    val body   = Json.obj("query" -> query)
    val entity = HttpEntity(ContentTypes.`application/json`, body.toString)
    val akkaHeaders = headers
      .flatMap {
        case (key, value) =>
          HttpHeader.parse(key, value) match {
            case Ok(header, _) => Some(header)
            case _             => None
          }
      }
      .to[collection.immutable.Seq]

    val akkaRequest = HttpRequest(
      uri = uri,
      method = HttpMethods.POST,
      entity = entity,
      headers = akkaHeaders
    )

    akkaHttp.singleRequest(akkaRequest).flatMap(convertResponse)
  }

  private def convertResponse(akkaResponse: HttpResponse): Future[GraphQlResponse] = {
    Unmarshal(akkaResponse).to[String].map { bodyString =>
      GraphQlResponse(akkaResponse.status.intValue, bodyString)
    }
  }
} 
Example 7
Source File: WSConnector.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package communicator
package ws.akka

import akka.http.scaladsl.{Http, HttpExt}
import akka.http.scaladsl.model.ws.{InvalidUpgradeResponse, ValidUpgrade, WebSocketRequest}
import akka.stream.{ConnectionException, Materializer}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success, Try}
import scala.util.control.NonFatal

private object WSConnector {
  locally(WSConnector)

  def apply[P <: WS: WSProtocolFactory](
      http: HttpExt,
      webSocketRequest: WebSocketRequest,
      properties: WS.Properties)(implicit
      materializer: Materializer) =
    new WSConnector[P](
      http, properties, webSocketRequest, Function const { })

  def apply[P <: WS: WSProtocolFactory](
      webSocketRequest: WebSocketRequest,
      properties: WS.Properties) = {
    implicit val (actorSystem, actorMaterializer) = WSActorSystem.retrieve()
    new WSConnector[P](
      Http(), properties, webSocketRequest, {
        case Success(connection) =>
          connection.closed foreach { _ => WSActorSystem.release() }
        case _ =>
          WSActorSystem.release()
      })
  }

  class WSConnector[P <: WS: WSProtocolFactory](
    http: HttpExt,
    properties: WS.Properties,
    webSocketRequest: WebSocketRequest,
    webSocketConnectionEstablished: Try[Connection[P]] => Unit)(implicit
    materializer: Materializer)
      extends Connector[P] {

    def connect(connectionEstablished: Connected[P]) = {
      val protocolPromise = Promise[P]

      def connected(connection: Try[Connection[P]]) = {
        webSocketConnectionEstablished(connection)
        connectionEstablished.set(connection)
      }

      val (future, _) =
        try http.singleWebSocketRequest(
          webSocketRequest,
          WSHandler.handleWebSocket(protocolPromise.future, properties, connected))
        catch {
          case NonFatal(exception) => (Future failed exception, ())
        }

      future onComplete {
        case Success(ValidUpgrade(response, _)) =>
          val uri = webSocketRequest.uri

          val WSSecurityProperties(isAuthenticated, isProtected, isEncrypted, certificates) =
            WSSecurityProperties(webSocketRequest, response, authenticated = false)

          implicitly[WSProtocolFactory[P]] make (
              uri.toString,
              Some(uri.authority.host.address), Some(uri.effectivePort),
              WSConnector.this, isAuthenticated, isEncrypted, isProtected,
              Some(Right(response)), Left(certificates))  match {
            case Failure(exception) =>
              connected(Failure(exception))

            case Success(ws) =>
              protocolPromise.success(ws)
          }

        case Success(InvalidUpgradeResponse(_, cause)) =>
          connected(Failure(new ConnectionException(cause)))

        case Failure(exception) =>
          connected(Failure(exception))
      }
    }
  }
}