akka.http.scaladsl.HttpsConnectionContext Scala Examples
The following examples show how to use akka.http.scaladsl.HttpsConnectionContext.
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: ManagementRouteProviderSettings.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.management.scaladsl import java.util.Optional import java.util.concurrent.CompletionStage import java.util.function.{ Function => JFunction } import akka.annotation.DoNotInherit import akka.annotation.InternalApi import akka.http.javadsl.server.directives.SecurityDirectives.ProvidedCredentials import akka.http.scaladsl.HttpsConnectionContext import akka.http.scaladsl.model.Uri import akka.http.scaladsl.server.Directives.AsyncAuthenticator import akka.management.javadsl object ManagementRouteProviderSettings { def apply(selfBaseUri: Uri, readOnly: Boolean): ManagementRouteProviderSettings = { ManagementRouteProviderSettingsImpl(selfBaseUri, None, None, None, readOnly = readOnly) } } @InternalApi private[akka] final case class ManagementRouteProviderSettingsImpl( override val selfBaseUri: Uri, scaladslAuth: Option[AsyncAuthenticator[String]], javadslAuth: Option[JFunction[Optional[ProvidedCredentials], CompletionStage[Optional[String]]]], override val httpsConnectionContext: Option[HttpsConnectionContext], override val readOnly: Boolean ) extends ManagementRouteProviderSettings { // There is no public API for defining both so it should not be possible require(!(javadslAuth.isDefined && scaladslAuth.isDefined), "Defining both javadsl and scaladsl auth is not allowed") override def withAuth(newAuth: AsyncAuthenticator[String]): ManagementRouteProviderSettings = copy(scaladslAuth = Option(newAuth)) override def withHttpsConnectionContext( newHttpsConnectionContext: HttpsConnectionContext): ManagementRouteProviderSettings = copy(selfBaseUri = selfBaseUri.withScheme("https"), httpsConnectionContext = Option(newHttpsConnectionContext)) def javadslHttpsConnectionContext: Optional[akka.http.javadsl.HttpsConnectionContext] = httpsConnectionContext match { case None => Optional.empty() case Some(ctx) => Optional.of(ctx) // a scaladsl.HttpsConnectionContext is a javadsl.HttpsConnectionContext } override def withReadOnly(readOnly: Boolean): ManagementRouteProviderSettings = copy(readOnly = readOnly) def asJava: javadsl.ManagementRouteProviderSettingsImpl = javadsl.ManagementRouteProviderSettingsImpl( selfBaseUri = akka.http.javadsl.model.Uri.create(selfBaseUri), javadslAuth, scaladslAuth, javadslHttpsConnectionContext, readOnly) }
Example 2
Source File: InfluxAkkaClient.scala From chronicler with Apache License 2.0 | 5 votes |
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 3
Source File: AkkaRequestExecutor.scala From chronicler with Apache License 2.0 | 5 votes |
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 4
Source File: InfluxMng.scala From chronicler with Apache License 2.0 | 5 votes |
package com.github.fsanaulla.chronicler.akka.management import akka.actor.ActorSystem import akka.http.scaladsl.HttpsConnectionContext import com.github.fsanaulla.chronicler.akka.shared.InfluxConfig import com.github.fsanaulla.chronicler.akka.shared.implicits._ import com.github.fsanaulla.chronicler.core.model.InfluxCredentials import scala.concurrent.ExecutionContext def apply( conf: InfluxConfig )(implicit ex: ExecutionContext, system: ActorSystem ): AkkaManagementClient = apply( conf.host, conf.port, conf.credentials, conf.httpsContext, conf.terminateActorSystem ) }
Example 5
Source File: AkkaIOClient.scala From chronicler with Apache License 2.0 | 5 votes |
package com.github.fsanaulla.chronicler.akka.io import akka.actor.ActorSystem import akka.http.scaladsl.HttpsConnectionContext import akka.http.scaladsl.model.{HttpResponse, RequestEntity, Uri} import akka.stream.ActorMaterializer import com.github.fsanaulla.chronicler.akka.shared.InfluxAkkaClient import com.github.fsanaulla.chronicler.akka.shared.handlers._ import com.github.fsanaulla.chronicler.akka.shared.implicits._ import com.github.fsanaulla.chronicler.core.IOClient import com.github.fsanaulla.chronicler.core.alias.ErrorOr import com.github.fsanaulla.chronicler.core.model.{InfluxCredentials, InfluxDBInfo} import scala.concurrent.{ExecutionContext, Future} import scala.reflect.ClassTag final class AkkaIOClient( host: String, port: Int, credentials: Option[InfluxCredentials], compress: Boolean, httpsContext: Option[HttpsConnectionContext], terminateActorSystem: Boolean )(implicit ex: ExecutionContext, system: ActorSystem) extends InfluxAkkaClient(terminateActorSystem, httpsContext) with IOClient[Future, Future, HttpResponse, Uri, RequestEntity] { implicit val mat: ActorMaterializer = ActorMaterializer() implicit val bb: AkkaBodyBuilder = new AkkaBodyBuilder() implicit val qb: AkkaQueryBuilder = new AkkaQueryBuilder(schema, host, port, credentials) implicit val jh: AkkaJsonHandler = new AkkaJsonHandler(new AkkaBodyUnmarshaller(compress)) implicit val re: AkkaRequestExecutor = new AkkaRequestExecutor(ctx) implicit val rh: AkkaResponseHandler = new AkkaResponseHandler(jh) override def database(dbName: String): AkkaDatabaseApi = new AkkaDatabaseApi(dbName, compress) override def measurement[A: ClassTag]( dbName: String, measurementName: String ): AkkaMeasurementApi[A] = new AkkaMeasurementApi[A](dbName, measurementName, compress) override def ping: Future[ErrorOr[InfluxDBInfo]] = { re.get(qb.buildQuery("/ping", Nil), compressed = false) .flatMap(rh.pingResult) } }
Example 6
Source File: InfluxIO.scala From chronicler with Apache License 2.0 | 5 votes |
package com.github.fsanaulla.chronicler.akka.io import akka.actor.ActorSystem import akka.http.scaladsl.HttpsConnectionContext import com.github.fsanaulla.chronicler.akka.shared.InfluxConfig import com.github.fsanaulla.chronicler.core.model.InfluxCredentials import scala.concurrent.ExecutionContext def apply(conf: InfluxConfig)(implicit ex: ExecutionContext, system: ActorSystem): AkkaIOClient = apply( conf.host, conf.port, conf.credentials, conf.compress, conf.httpsContext, conf.terminateActorSystem ) }
Example 7
Source File: HttpClientProvider.scala From reactive-nakadi with MIT License | 5 votes |
package org.zalando.react.nakadi.client.providers import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager} import akka.actor.ActorContext import akka.http.scaladsl.Http.OutgoingConnection import akka.http.scaladsl.model.{HttpRequest, HttpResponse} import akka.http.scaladsl.settings.ClientConnectionSettings import akka.http.scaladsl.{Http, HttpsConnectionContext} import akka.stream.scaladsl.Flow import scala.concurrent.Future import scala.concurrent.duration._ class HttpClientProvider(actorContext: ActorContext, server: String, port: Int, isConnectionSSL: Boolean = false, acceptAnyCertificate: Boolean = false, connectionTimeout: FiniteDuration) { val http = Http(actorContext.system) private val settings = { ClientConnectionSettings .apply(actorContext.system) .withConnectingTimeout(connectionTimeout) .withIdleTimeout(Duration.Inf) } val connection: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = { isConnectionSSL match { case true => val sslContext = if (!acceptAnyCertificate) SSLContext.getDefault else { val permissiveTrustManager: TrustManager = new X509TrustManager() { override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} override def getAcceptedIssuers(): Array[X509Certificate] = Array.empty } val ctx = SSLContext.getInstance("TLS") ctx.init(Array.empty, Array(permissiveTrustManager), new SecureRandom()) ctx } http.outgoingConnectionHttps(server, port, new HttpsConnectionContext(sslContext), settings = settings) case false => http.outgoingConnection(server, port, settings = settings) } } }
Example 8
Source File: Main.scala From akka-grpc with Apache License 2.0 | 5 votes |
package example.myapp import java.io.InputStream import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext} import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.grpc.scaladsl.ServiceHandler import akka.http.scaladsl.{Http2, HttpsConnectionContext} import example.myapp.echo.EchoServiceImpl import example.myapp.echo.grpc.EchoServiceHandler import example.myapp.helloworld.GreeterServiceImpl import example.myapp.helloworld.grpc.GreeterServiceHandler object Main extends App { implicit val system = ActorSystem() implicit val mat = ActorMaterializer() val echoHandler = EchoServiceHandler.partial(new EchoServiceImpl) val greeterHandler = GreeterServiceHandler.partial(new GreeterServiceImpl) val serviceHandler = ServiceHandler.concatOrNotFound(echoHandler, greeterHandler) Http2().bindAndHandleAsync( serviceHandler, interface = "localhost", port = 8443, parallelism = 256, // Needed to allow running multiple requests concurrently, see https://github.com/akka/akka-http/issues/2145 connectionContext = serverHttpContext()) private def serverHttpContext() = { // never put passwords into code! val password = "abcdef".toCharArray val ks = KeyStore.getInstance("PKCS12") ks.load(Option(getClass.getClassLoader.getResourceAsStream("server.p12")).get, password) val keyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(ks, password) val context = SSLContext.getInstance("TLS") context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom) new HttpsConnectionContext(context) } }
Example 9
Source File: AkkaGrpcServerScala.scala From akka-grpc with Apache License 2.0 | 5 votes |
package akka.grpc.interop import java.io.FileInputStream import java.nio.file.{ Files, Paths } import java.security.cert.CertificateFactory import java.security.spec.PKCS8EncodedKeySpec import java.security.{ KeyFactory, KeyStore, SecureRandom } import scala.concurrent.duration._ import akka.actor.ActorSystem import akka.util.ByteString import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.model.{ HttpRequest, HttpResponse } import akka.http.scaladsl.{ Http2, HttpsConnectionContext } import akka.stream.SystemMaterializer import io.grpc.internal.testing.TestUtils import javax.net.ssl.{ KeyManagerFactory, SSLContext } import scala.concurrent.{ Await, Future } case class AkkaGrpcServerScala(serverHandlerFactory: ActorSystem => HttpRequest => Future[HttpResponse]) extends GrpcServer[(ActorSystem, ServerBinding)] { override def start() = { implicit val sys = ActorSystem() implicit val mat = SystemMaterializer(sys).materializer val testService = serverHandlerFactory(sys) val bindingFuture = Http2().bindAndHandleAsync( testService, interface = "127.0.0.1", port = 0, parallelism = 256, // TODO remove once https://github.com/akka/akka-http/pull/2146 is merged connectionContext = serverHttpContext()) val binding = Await.result(bindingFuture, 10.seconds) (sys, binding) } override def stop(binding: (ActorSystem, ServerBinding)) = binding match { case (sys, binding) => sys.log.info("Exception thrown, unbinding") Await.result(binding.unbind(), 10.seconds) Await.result(sys.terminate(), 10.seconds) } private def serverHttpContext() = { val keyEncoded = new String(Files.readAllBytes(Paths.get(TestUtils.loadCert("server1.key").getAbsolutePath)), "UTF-8") .replace("-----BEGIN PRIVATE KEY-----\n", "") .replace("-----END PRIVATE KEY-----\n", "") .replace("\n", "") val decodedKey = ByteString(keyEncoded).decodeBase64.toArray val spec = new PKCS8EncodedKeySpec(decodedKey) val kf = KeyFactory.getInstance("RSA") val privateKey = kf.generatePrivate(spec) val fact = CertificateFactory.getInstance("X.509") val is = new FileInputStream(TestUtils.loadCert("server1.pem")) val cer = fact.generateCertificate(is) val ks = KeyStore.getInstance("PKCS12") ks.load(null) ks.setKeyEntry("private", privateKey, Array.empty, Array(cer)) val keyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(ks, null) val context = SSLContext.getInstance("TLS") context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom) new HttpsConnectionContext(context) } override def getPort(binding: (ActorSystem, ServerBinding)): Int = binding._2.localAddress.getPort }
Example 10
Source File: JavaConverters.scala From squbs with Apache License 2.0 | 5 votes |
package akka.http.org.squbs.util import java.util.Optional import akka.NotUsed import akka.http.impl.util.JavaMapping import akka.http.javadsl.{model => jm} import akka.http.scaladsl.Http.HostConnectionPool import akka.http.scaladsl.HttpsConnectionContext import akka.http.scaladsl.model.{HttpRequest, HttpResponse} import akka.http.scaladsl.settings.ConnectionPoolSettings import akka.http.{javadsl => jd} import akka.japi.Pair import akka.stream.scaladsl.{BidiFlow, Flow} import akka.stream.{javadsl => js} import scala.util.Try object JavaConverters { def fromJava(connectionContext: Optional[jd.HttpsConnectionContext], settings: Optional[jd.settings.ConnectionPoolSettings]): (Option[HttpsConnectionContext], Option[ConnectionPoolSettings]) = { import scala.compat.java8.OptionConverters._ val cCtx = connectionContext.asScala.asInstanceOf[Option[HttpsConnectionContext]] val sSettings = settings.asScala.asInstanceOf[Option[ConnectionPoolSettings]] (cCtx, sSettings) } def toJava[In1, Out1, In2, Out2, Context](bidiFlow: BidiFlow[(In1, Context), (Out1, Context), (In2, Context), (Out2, Context), NotUsed]): js.BidiFlow[Pair[In1, Context], Pair[Out1, Context], Pair[In2, Context], Pair[Out2, Context], NotUsed] = { implicit val sIn1Mapping = JavaMapping.identity[In1] implicit val sOut1Mapping = JavaMapping.identity[Out1] implicit val sIn2Mapping = JavaMapping.identity[In2] implicit val sOut2Mapping = JavaMapping.identity[Out2] implicit val contextMapping = JavaMapping.identity[Context] val javaToScalaAdapter = JavaMapping.adapterBidiFlow[Pair[In1, Context], (In1, Context), (Out2, Context), Pair[Out2, Context]] val scalaToJavaAdapter = JavaMapping.adapterBidiFlow[Pair[In2, Context], (In2, Context), (Out1, Context), Pair[Out1, Context]].reversed javaToScalaAdapter.atop(bidiFlow).atop(scalaToJavaAdapter).asJava } private def adaptTupleFlow[T](scalaFlow: Flow[(HttpRequest, T), (Try[HttpResponse], T), HostConnectionPool]): js.Flow[Pair[jm.HttpRequest, T], Pair[Try[jm.HttpResponse], T], jd.HostConnectionPool] = { implicit val _ = JavaMapping.identity[T] implicit object HostConnectionPoolMapping extends JavaMapping[jd.HostConnectionPool, HostConnectionPool] { def toScala(javaObject: jd.HostConnectionPool): HostConnectionPool = throw new UnsupportedOperationException("jd.HostConnectionPool cannot be converted to Scala") def toJava(scalaObject: HostConnectionPool): jd.HostConnectionPool = scalaObject.toJava } JavaMapping.toJava(scalaFlow)(JavaMapping.flowMapping[Pair[jm.HttpRequest, T], (HttpRequest, T), Pair[Try[jm.HttpResponse], T], (Try[HttpResponse], T), jd.HostConnectionPool, HostConnectionPool]) } def toJava[T](flow: Flow[(HttpRequest, T), (Try[HttpResponse], T), HostConnectionPool]): js.Flow[Pair[jm.HttpRequest, T], Pair[Try[jm.HttpResponse], T], jd.HostConnectionPool] = { adaptTupleFlow[T](flow) } def toScala(uri: akka.http.javadsl.model.Uri) = JavaMapping.toScala(uri) }
Example 11
Source File: AkkaHttpClient.scala From sttp with Apache License 2.0 | 5 votes |
package sttp.client.akkahttp import akka.actor.ActorSystem import akka.event.LoggingAdapter import akka.http.scaladsl.model.ws.{Message, WebSocketRequest, WebSocketUpgradeResponse} import akka.http.scaladsl.model.{HttpRequest, HttpResponse} import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler, Route, RoutingLog} import akka.http.scaladsl.settings.{ClientConnectionSettings, ConnectionPoolSettings, ParserSettings, RoutingSettings} import akka.http.scaladsl.{Http, HttpsConnectionContext} import akka.stream.Materializer import akka.stream.scaladsl.Flow import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future} trait AkkaHttpClient { def singleRequest( request: HttpRequest, settings: ConnectionPoolSettings ): Future[HttpResponse] def singleWebsocketRequest[WS_RESULT]( request: WebSocketRequest, clientFlow: Flow[Message, Message, WS_RESULT], settings: ClientConnectionSettings )(implicit ec: ExecutionContext, mat: Materializer): Future[(WebSocketUpgradeResponse, WS_RESULT)] } object AkkaHttpClient { def default( system: ActorSystem, connectionContext: Option[HttpsConnectionContext], customLog: Option[LoggingAdapter] ): AkkaHttpClient = new AkkaHttpClient { private val http = Http()(system) override def singleRequest( request: HttpRequest, settings: ConnectionPoolSettings ): Future[HttpResponse] = { http.singleRequest( request, connectionContext.getOrElse(http.defaultClientHttpsContext), settings, customLog.getOrElse(system.log) ) } override def singleWebsocketRequest[WS_RESULT]( request: WebSocketRequest, clientFlow: Flow[Message, Message, WS_RESULT], settings: ClientConnectionSettings )(implicit ec: ExecutionContext, mat: Materializer): Future[(WebSocketUpgradeResponse, WS_RESULT)] = { val (wsResponse, wsResult) = http.singleWebSocketRequest( request, clientFlow, connectionContext.getOrElse(http.defaultClientHttpsContext), None, settings, customLog.getOrElse(system.log) ) wsResponse.map((_, wsResult)) } } def stubFromAsyncHandler(run: HttpRequest => Future[HttpResponse]): AkkaHttpClient = new AkkaHttpClient { def singleRequest(request: HttpRequest, settings: ConnectionPoolSettings): Future[HttpResponse] = run(request) override def singleWebsocketRequest[WS_RESULT]( request: WebSocketRequest, clientFlow: Flow[Message, Message, WS_RESULT], settings: ClientConnectionSettings )(implicit ec: ExecutionContext, mat: Materializer): Future[(WebSocketUpgradeResponse, WS_RESULT)] = Future.failed(new RuntimeException("Websockets are not supported")) } def stubFromRoute(route: Route)(implicit routingSettings: RoutingSettings, parserSettings: ParserSettings, materializer: Materializer, routingLog: RoutingLog, executionContext: ExecutionContextExecutor = null, rejectionHandler: RejectionHandler = RejectionHandler.default, exceptionHandler: ExceptionHandler = null ): AkkaHttpClient = stubFromAsyncHandler(Route.asyncHandler(route)) }
Example 12
Source File: LongPollingPool.scala From skuber with Apache License 2.0 | 5 votes |
package skuber.api.watch import akka.NotUsed import akka.actor.ActorSystem import akka.http.scaladsl.settings.{ClientConnectionSettings, ConnectionPoolSettings} import akka.http.scaladsl.{Http, HttpsConnectionContext} import akka.stream.Materializer import skuber.api.client.Pool import scala.concurrent.duration._ private[api] object LongPollingPool { def apply[T](schema: String, host: String, port: Int, poolIdleTimeout: Duration, httpsConnectionContext: Option[HttpsConnectionContext], clientConnectionSettings: ClientConnectionSettings)(implicit mat: Materializer, system: ActorSystem): Pool[T] = { schema match { case "http" => Http().newHostConnectionPool[T]( host, port, buildHostConnectionPool(poolIdleTimeout, clientConnectionSettings, system) ).mapMaterializedValue(_ => NotUsed) case "https" => Http().newHostConnectionPoolHttps[T]( host, port, httpsConnectionContext.getOrElse(Http().defaultClientHttpsContext), buildHostConnectionPool(poolIdleTimeout, clientConnectionSettings, system) ).mapMaterializedValue(_ => NotUsed) case unsupported => throw new IllegalArgumentException(s"Schema $unsupported is not supported") } } private def buildHostConnectionPool[T](poolIdleTimeout: Duration, clientConnectionSettings: ClientConnectionSettings, system: ActorSystem) = { ConnectionPoolSettings(system) .withMaxConnections(1) // Limit number the of open connections to one .withPipeliningLimit(1) // Limit pipelining of requests to one .withMaxRetries(0) // Disables retries .withIdleTimeout(poolIdleTimeout) // Automatically shutdown connection pool after timeout .withConnectionSettings(clientConnectionSettings) } }
Example 13
Source File: SSLProviderSpec.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.http.security import akka.actor.Actor import akka.http.scaladsl.{HttpConnectionContext, HttpsConnectionContext} import akka.testkit.TestActorRef import com.github.vonnagy.service.container.AkkaTestkitSpecs2Support import org.specs2.mutable.SpecificationLike class SSLProviderSpec extends AkkaTestkitSpecs2Support with SpecificationLike { val act = TestActorRef(new SSLActor) class SSLActor extends Actor with SSLProvider { def receive = { case _ => } } "SSLProviderSpec" should { "allow for getting an SSL context" in { val ctx = act.underlyingActor.getContext(true) ctx.isInstanceOf[HttpsConnectionContext] must beTrue } "allow for getting an non-SSL context" in { val ctx = act.underlyingActor.getContext(false) ctx.isInstanceOf[HttpConnectionContext] must beTrue } } }