akka.actor.Extension Scala Examples
The following examples show how to use akka.actor.Extension.
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: CouchbaseReplayExtension.scala From akka-persistence-couchbase with Apache License 2.0 | 5 votes |
package akka.persistence.couchbase.replay import java.util.concurrent.TimeUnit import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.event.Logging import akka.persistence.couchbase.CouchbaseExtension import com.couchbase.client.java.document.JsonLongDocument import com.couchbase.client.java.document.json.JsonObject import com.couchbase.client.java.view._ import scala.util.{Failure, Try} trait CouchbaseReplay extends Extension { def replayConfig: CouchbaseReplayConfig def replay(callback: ReplayCallback, journalMessageIdOption: Option[Long] = None): Unit def storeMessageId(identifier: String, journalMessageId: Long): Unit def readMessageId(identifier: String): Option[Long] } private class DefaultCouchbaseReplay(val system: ExtendedActorSystem) extends CouchbaseReplay { private val log = Logging(system, getClass.getName) val couchbase = CouchbaseExtension(system) override val replayConfig = CouchbaseReplayConfig(system) val cluster = replayConfig.createCluster(couchbase.environment) val replayBucket = replayConfig.openBucket(cluster) updateJournalDesignDocs() private def updateJournalDesignDocs(): Unit = { val designDocs = JsonObject.create() .put("views", JsonObject.create() .put("commits", JsonObject.create() .put("map", replayConfig.replayViewCode) ) ) Try { val designDocument = DesignDocument.from("recovery", designDocs) couchbase.journalBucket.bucketManager.upsertDesignDocument(designDocument) } recoverWith { case e => log.error(e, "Updating design documents for recovery") Failure(e) } } override def replay(callback: ReplayCallback, journalMessageIdOption: Option[Long]): Unit = { system.actorOf(ReplayActor.props(callback)) ! ReplayActor.Recover(journalMessageIdOption) } override def storeMessageId(identifier: String, journalMessageId: Long): Unit = { Try { replayBucket.upsert( JsonLongDocument.create(s"replayId::$identifier", journalMessageId), replayConfig.persistTo, replayConfig.replicateTo, replayConfig.timeout.toSeconds, TimeUnit.SECONDS ) } recoverWith { case e => log.error(e, "Store replay id: {}", journalMessageId) Failure(e) } } override def readMessageId(identifier: String): Option[Long] = { Option( replayBucket.get( JsonLongDocument.create(s"replayId::$identifier"), replayConfig.timeout.toSeconds, TimeUnit.SECONDS ) ).map(_.content()) } } object CouchbaseReplayExtension extends ExtensionId[CouchbaseReplay] with ExtensionIdProvider { override def lookup(): ExtensionId[CouchbaseReplay] = CouchbaseReplayExtension override def createExtension(system: ExtendedActorSystem): CouchbaseReplay = { new DefaultCouchbaseReplay(system) } }
Example 2
Source File: AkkaSerializationMessageCodec.scala From eventuate with Apache License 2.0 | 5 votes |
package com.rbmhtechnology.eventuate.adapter.vertx import akka.actor.{ ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } import com.rbmhtechnology.eventuate.serializer.CommonFormats.PayloadFormat import com.rbmhtechnology.eventuate.serializer.DelegatingPayloadSerializer import io.vertx.core.buffer.Buffer import io.vertx.core.eventbus.MessageCodec object AkkaSerializationMessageCodec { val Name = "akka-serialization-message-codec" def apply(name: String)(implicit system: ActorSystem): MessageCodec[AnyRef, AnyRef] = new AkkaSerializationMessageCodec(name) def apply(clazz: Class[_])(implicit system: ActorSystem): MessageCodec[AnyRef, AnyRef] = new AkkaSerializationMessageCodec(s"${AkkaSerializationMessageCodec.Name}-${clazz.getName}") } class AkkaSerializationMessageCodec(override val name: String)(implicit system: ActorSystem) extends MessageCodec[AnyRef, AnyRef] { val serializer = PayloadSerializationExtension(system) override def transform(o: AnyRef): AnyRef = o override def encodeToWire(buffer: Buffer, o: AnyRef): Unit = { val payload = serializer.toBinary(o) buffer.appendInt(payload.length) buffer.appendBytes(payload) } override def decodeFromWire(pos: Int, buffer: Buffer): AnyRef = { val payloadLength = buffer.getInt(pos) val payload = buffer.getBytes(pos + Integer.BYTES, pos + Integer.BYTES + payloadLength) serializer.fromBinary(payload).asInstanceOf[AnyRef] } override def systemCodecID(): Byte = -1 } object PayloadSerializationExtension extends ExtensionId[PayloadSerializationExtension] with ExtensionIdProvider { override def lookup = PayloadSerializationExtension override def createExtension(system: ExtendedActorSystem): PayloadSerializationExtension = new PayloadSerializationExtension(system) override def get(system: ActorSystem): PayloadSerializationExtension = super.get(system) } class PayloadSerializationExtension(system: ExtendedActorSystem) extends Extension { val serializer = new DelegatingPayloadSerializer(system) def toBinary(o: AnyRef): Array[Byte] = serializer.payloadFormatBuilder(o).build().toByteArray def fromBinary(b: Array[Byte]): Any = serializer.payload(PayloadFormat.parseFrom(b)) }
Example 3
Source File: KafkaSettings.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.config import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } import com.typesafe.config.Config class KafkaSettings(config: Config) extends Extension { val bootstrapServers: String = config.getString("kafka.producer.bootstrapServers") val createEventsTopic: String = config.getString("kafka.producer.createTopic") val deleteEventsTopic: String = config.getString("kafka.producer.deleteTopic") val auditEventsTopic: String = config.getString("kafka.producer.auditTopic") val retries: String = config.getString("kafka.producer.retries") val retriesBackOff: String = config.getString("kafka.producer.backoff") val retriesBackOffMax: String = config.getString("kafka.producer.backoffMax") val requestTimeoutMs: String = config.getString("kafka.producer.requestTimeoutMs") val protocol: String = config.getString("kafka.producer.protocol") val maxblock: String = config.getString("kafka.producer.maxblock") val sslTruststoreLocation: String = config.getString("kafka.producer.ssl.truststore.location") val sslTruststorePassword: String = config.getString("kafka.producer.ssl.truststore.password") val sslKeystoreLocation: String = config.getString("kafka.producer.ssl.keystore.location") val sslKeystorePassword: String = config.getString("kafka.producer.ssl.keystore.password") val sslKeyPassword: String = config.getString("kafka.producer.ssl.key.password") val kafkaConfig: Config = config.getConfig("kafka.producer") } object KafkaSettings extends ExtensionId[KafkaSettings] with ExtensionIdProvider { override def createExtension(system: ExtendedActorSystem): KafkaSettings = new KafkaSettings(system.settings.config) override def lookup(): ExtensionId[KafkaSettings] = KafkaSettings }
Example 4
Source File: StorageS3Settings.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.config import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } import akka.http.scaladsl.model.Uri import com.ing.wbaa.rokku.proxy.data.HealthCheck.{ HCMethod, RGWListBuckets, S3ListBucket } import com.typesafe.config.Config class StorageS3Settings(config: Config) extends Extension { private val storageS3Host: String = config.getString("rokku.storage.s3.host") private val storageS3Port: Int = config.getInt("rokku.storage.s3.port") val storageS3Authority = Uri.Authority(Uri.Host(storageS3Host), storageS3Port) val storageS3AdminAccesskey: String = config.getString("rokku.storage.s3.admin.accesskey") val storageS3AdminSecretkey: String = config.getString("rokku.storage.s3.admin.secretkey") val awsRegion: String = config.getString("rokku.storage.s3.region") val v2SignatureEnabled: Boolean = config.getBoolean("rokku.storage.s3.v2SignatureEnabled") val isRequestUserQueueEnabled: Boolean = config.getBoolean("rokku.storage.s3.request.queue.enable") private val hcMethodString = config.getString("rokku.storage.s3.healthCheck.method") val hcMethod: HCMethod = hcMethodString match { case "rgwListBuckets" => RGWListBuckets case "s3ListBucket" => S3ListBucket } val hcInterval: Long = config.getLong("rokku.storage.s3.healthCheck.interval") val bucketName: String = config.getString("rokku.storage.s3.healthCheck.bucketName") val isCacheEnabled: Boolean = config.getBoolean("rokku.storage.s3.enabledCache") val eligibleCachePaths: Array[String] = config.getString("rokku.storage.s3.eligibleCachePaths").trim().split(",") val maxEligibleCacheObjectSizeInBytes: Long = config.getLong("rokku.storage.s3.maxEligibleCacheObjectSizeInBytes") val strictCacheDownloadTimeoutInSeconds: Int = config.getInt("rokku.storage.s3.strictCacheDownloadTimeoutInSeconds") } object StorageS3Settings extends ExtensionId[StorageS3Settings] with ExtensionIdProvider { override def createExtension(system: ExtendedActorSystem): StorageS3Settings = new StorageS3Settings(system.settings.config) override def lookup(): ExtensionId[StorageS3Settings] = StorageS3Settings }
Example 5
Source File: RangerSettings.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.config import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } import com.typesafe.config.Config class RangerSettings(config: Config) extends Extension { val serviceType: String = config.getString("rokku.ranger.service_type") val appId: String = config.getString("rokku.ranger.app_id") val listBucketsEnabled: Boolean = config.getBoolean("rokku.ranger.allow-list-buckets") val userDomainPostfix: String = config.getString("rokku.ranger.user-domain-postfix") val auditEnabled: Boolean = config.getBoolean("rokku.ranger.enabled-audit") val rolePrefix: String = config.getString("rokku.ranger.role-prefix") } object RangerSettings extends ExtensionId[RangerSettings] with ExtensionIdProvider { override def createExtension(system: ExtendedActorSystem): RangerSettings = new RangerSettings(system.settings.config) override def lookup(): ExtensionId[RangerSettings] = RangerSettings }
Example 6
Source File: ActiveMqExtension.scala From reactive-activemq with Apache License 2.0 | 5 votes |
package akka.stream.integration.activemq.extension import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } import akka.camel.CamelExtension import akka.stream.integration.activemq.extension.config.{ ActiveMqConfig, ConsumerConfig, ProducerConfig } import org.apache.activemq.ActiveMQConnectionFactory import org.apache.activemq.camel.component.ActiveMQComponent import org.apache.camel.component.jms.JmsConfiguration object ActiveMqExtension extends ExtensionId[ActiveMqExtensionImpl] with ExtensionIdProvider { override def createExtension(system: ExtendedActorSystem): ActiveMqExtensionImpl = new ActiveMqExtensionImpl(system) override def lookup(): ExtensionId[_ <: Extension] = ActiveMqExtension } trait ActiveMqExtension { def consumerEndpointUri(consumerName: String): String def producerEndpointUri(producerName: String): String } class ActiveMqExtensionImpl(val system: ExtendedActorSystem) extends Extension with ActiveMqExtension { import scala.collection.JavaConversions._ system.settings.config.getStringList("reactive-activemq.connections").foreach { componentName => val amqConfig = ActiveMqConfig(system.settings.config.getConfig(componentName)) createComponent(componentName, amqConfig) } private def createComponent(componentName: String, amqConfig: ActiveMqConfig): Unit = { val connectionFactory = new ActiveMQConnectionFactory(amqConfig.user, amqConfig.pass, amqConfig.url) val jmsConfiguration: JmsConfiguration = new JmsConfiguration() jmsConfiguration.setConnectionFactory(connectionFactory) val ctx = CamelExtension(system).context val component = ctx.getComponent("activemq").asInstanceOf[ActiveMQComponent] component.setConfiguration(jmsConfiguration) component.setTransacted(true) ctx.addComponent(componentName, component) } override def consumerEndpointUri(consumerName: String): String = ConsumerConfig(system.settings.config.getConfig(consumerName), consumerName).endpoint override def producerEndpointUri(producerName: String): String = ProducerConfig(system.settings.config.getConfig(producerName)).endpoint }
Example 7
Source File: VisualMailboxMetricClient.scala From akka-visualmailbox with Apache License 2.0 | 5 votes |
package de.aktey.akka.visualmailbox import java.net.InetSocketAddress import akka.actor.{Actor, ActorRef, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider, Props} import akka.io.{IO, Udp} import akka.util.ByteString import de.aktey.akka.visualmailbox.packing.Packing object VisualMailboxMetricClient extends ExtensionId[VisualMailboxMetricClient] with ExtensionIdProvider { override def createExtension(system: ExtendedActorSystem): VisualMailboxMetricClient = { new VisualMailboxMetricClient( system, VisualMailboxMetricClientConfig.fromConfig(system.settings.config) ) } override def lookup(): ExtensionId[_ <: Extension] = VisualMailboxMetricClient } class VisualMailboxMetricClient(system: ExtendedActorSystem, config: VisualMailboxMetricClientConfig) extends Extension { private val udpSender = system.systemActorOf( Props(new UdpSender(config.serverAddress)).withDispatcher("de.aktey.akka.visualmailbox.client.dispatcher"), "de-aktey-akka-visualmailbox-sender" ) system.systemActorOf( Props(new VisualMailboxMetricListener(udpSender)).withDispatcher("de.aktey.akka.visualmailbox.client.dispatcher"), "de-aktey-akka-visualmailbox-receiver" ) } class VisualMailboxMetricListener(udpSender: ActorRef) extends Actor { import context._ import concurrent.duration._ var buffer: List[VisualMailboxMetric] = Nil system.eventStream.subscribe(self, classOf[VisualMailboxMetric]) system.scheduler.schedule(1.second, 1.second, self, "flush") @scala.throws[Exception](classOf[Exception]) override def postStop(): Unit = { system.eventStream.unsubscribe(self) } def receive: Receive = { case v: VisualMailboxMetric => buffer ::= v if (buffer.size > 40) self ! "flush" case "flush" if buffer.nonEmpty => udpSender ! Packing.pack(MetricEnvelope(1, Packing.pack(buffer))) buffer = Nil } } class UdpSender(remote: InetSocketAddress) extends Actor { import context._ IO(Udp) ! Udp.SimpleSender def receive = { case Udp.SimpleSenderReady => context.become(ready(sender())) } def ready(send: ActorRef): Receive = { case msg: Array[Byte] => send ! Udp.Send(ByteString(msg), remote) } }
Example 8
Source File: AddressTerminatedTopic.scala From perf_tester with Apache License 2.0 | 5 votes |
package akka.event import java.util.concurrent.atomic.AtomicReference import scala.annotation.tailrec import akka.actor.ActorRef import akka.actor.ActorSystem import akka.actor.AddressTerminated import akka.actor.ExtendedActorSystem import akka.actor.Extension import akka.actor.ExtensionId import akka.actor.ExtensionIdProvider private[akka] final class AddressTerminatedTopic extends Extension { private val subscribers = new AtomicReference[Set[ActorRef]](Set.empty[ActorRef]) @tailrec def subscribe(subscriber: ActorRef): Unit = { val current = subscribers.get if (!subscribers.compareAndSet(current, current + subscriber)) subscribe(subscriber) // retry } @tailrec def unsubscribe(subscriber: ActorRef): Unit = { val current = subscribers.get if (!subscribers.compareAndSet(current, current - subscriber)) unsubscribe(subscriber) // retry } def publish(msg: AddressTerminated): Unit = { subscribers.get foreach { _.tell(msg, ActorRef.noSender) } } }
Example 9
Source File: ClusterBootstrap.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.management.cluster.bootstrap import java.util.concurrent.atomic.AtomicReference import akka.AkkaVersion import scala.concurrent.{ Future, Promise, TimeoutException } import scala.concurrent.duration._ import akka.actor.ActorSystem import akka.actor.ClassicActorSystemProvider import akka.actor.ExtendedActorSystem import akka.actor.Extension import akka.actor.ExtensionId import akka.actor.ExtensionIdProvider import akka.annotation.InternalApi import akka.cluster.Cluster import akka.discovery.{ Discovery, ServiceDiscovery } import akka.event.Logging import akka.http.scaladsl.model.Uri import akka.http.scaladsl.server.Route import akka.management.cluster.bootstrap.contactpoint.HttpClusterBootstrapRoutes import akka.management.cluster.bootstrap.internal.BootstrapCoordinator import akka.management.scaladsl.ManagementRouteProviderSettings import akka.management.scaladsl.ManagementRouteProvider final class ClusterBootstrap(implicit system: ExtendedActorSystem) extends Extension with ManagementRouteProvider { import ClusterBootstrap.Internal._ import system.dispatcher private val log = Logging(system, classOf[ClusterBootstrap]) private final val bootstrapStep = new AtomicReference[BootstrapStep](NotRunning) AkkaVersion.require("cluster-bootstrap", "2.5.27") val settings: ClusterBootstrapSettings = ClusterBootstrapSettings(system.settings.config, log) // used for initial discovery of contact points lazy val discovery: ServiceDiscovery = settings.contactPointDiscovery.discoveryMethod match { case "akka.discovery" => val discovery = Discovery(system).discovery log.info("Bootstrap using default `akka.discovery` method: {}", Logging.simpleName(discovery)) discovery case otherDiscoveryMechanism => log.info("Bootstrap using `akka.discovery` method: {}", otherDiscoveryMechanism) Discovery(system).loadServiceDiscovery(otherDiscoveryMechanism) } private val joinDecider: JoinDecider = { system.dynamicAccess .createInstanceFor[JoinDecider]( settings.joinDecider.implClass, List((classOf[ActorSystem], system), (classOf[ClusterBootstrapSettings], settings)) ) .get } private[this] val _selfContactPointUri: Promise[Uri] = Promise() override def routes(routeProviderSettings: ManagementRouteProviderSettings): Route = { log.info(s"Using self contact point address: ${routeProviderSettings.selfBaseUri}") this.setSelfContactPoint(routeProviderSettings.selfBaseUri) new HttpClusterBootstrapRoutes(settings).routes } def start(): Unit = if (Cluster(system).settings.SeedNodes.nonEmpty) { log.warning( "Application is configured with specific `akka.cluster.seed-nodes`: {}, bailing out of the bootstrap process! " + "If you want to use the automatic bootstrap mechanism, make sure to NOT set explicit seed nodes in the configuration. " + "This node will attempt to join the configured seed nodes.", Cluster(system).settings.SeedNodes.mkString("[", ", ", "]") ) } else if (bootstrapStep.compareAndSet(NotRunning, Initializing)) { log.info("Initiating bootstrap procedure using {} method...", settings.contactPointDiscovery.discoveryMethod) ensureSelfContactPoint() val bootstrapProps = BootstrapCoordinator.props(discovery, joinDecider, settings) val bootstrap = system.systemActorOf(bootstrapProps, "bootstrapCoordinator") // Bootstrap already logs in several other execution points when it can't form a cluster, and why. selfContactPoint.foreach { uri => bootstrap ! BootstrapCoordinator.Protocol.InitiateBootstrapping(uri) } } else log.warning("Bootstrap already initiated, yet start() method was called again. Ignoring.") private[bootstrap] object Internal { sealed trait BootstrapStep case object NotRunning extends BootstrapStep case object Initializing extends BootstrapStep } }
Example 10
Source File: CassandraHealth.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.service.routes import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.event.Logging import akka.stream.alpakka.cassandra.CassandraSessionSettings import akka.stream.alpakka.cassandra.scaladsl.CassandraSessionRegistry import ch.epfl.bluebrain.nexus.sourcing.projections.Projections._ import scala.concurrent.{ExecutionContext, Future} trait CassandraHealth extends Extension { def check: Future[Boolean] } object CassandraHealth extends ExtensionId[CassandraHealth] with ExtensionIdProvider { override def lookup(): ExtensionId[_ <: Extension] = CassandraHealth override def createExtension(as: ExtendedActorSystem): CassandraHealth = { implicit val ec: ExecutionContext = as.dispatcher val log = Logging(as, "CassandraHeathCheck") val keyspace: String = journalConfig(as).getString("keyspace") val session = CassandraSessionRegistry.get(as).sessionFor(CassandraSessionSettings(cassandraDefaultConfigPath)) new CassandraHealth { private val query = s"SELECT now() FROM $keyspace.messages;" override def check: Future[Boolean] = { session.selectOne(query).map(_ => true).recover { case err => log.error("Error while attempting to query for health check", err) false } } } } }
Example 11
Source File: Settings.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.service.config import java.nio.file.{Path, Paths} import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.Uri import ch.epfl.bluebrain.nexus.iam.auth.AccessToken import ch.epfl.bluebrain.nexus.iam.types.Permission import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import com.typesafe.config.Config import pureconfig.generic.auto._ import pureconfig.ConvertHelpers.{catchReadError, optF} import pureconfig.{ConfigConvert, ConfigSource} import scala.annotation.nowarn @SuppressWarnings(Array("LooksLikeInterpolatedString")) class Settings(config: Config) extends Extension { @nowarn("cat=unused") implicit private val uriConverter: ConfigConvert[Uri] = ConfigConvert.viaString[Uri](catchReadError(Uri(_)), _.toString) @nowarn("cat=unused") implicit private val permissionConverter: ConfigConvert[Permission] = ConfigConvert.viaString[Permission](optF(Permission(_)), _.toString) @nowarn("cat=unused") implicit val absoluteIriConverter: ConfigConvert[AbsoluteIri] = ConfigConvert.viaString[AbsoluteIri](catchReadError(s => url"$s"), _.toString) @nowarn("cat=unused") implicit private val pathConverter: ConfigConvert[Path] = ConfigConvert.viaString[Path](catchReadError(s => Paths.get(s)), _.toString) @nowarn("cat=unused") implicit private val authTokenConverter: ConfigConvert[AccessToken] = ConfigConvert.viaString[AccessToken](catchReadError(s => AccessToken(s)), _.value) val serviceConfig: ServiceConfig = ConfigSource.fromConfig(config).at("app").loadOrThrow[ServiceConfig] } object Settings extends ExtensionId[Settings] with ExtensionIdProvider { override def lookup(): ExtensionId[_ <: Extension] = Settings override def createExtension(system: ExtendedActorSystem): Settings = apply(system.settings.config) def apply(config: Config): Settings = new Settings(config) }
Example 12
Source File: Settings.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage.config import java.nio.file.{Path, Paths} import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.Uri import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import scala.annotation.nowarn import com.typesafe.config.Config import pureconfig.generic.auto._ import pureconfig.ConvertHelpers._ import pureconfig._ @SuppressWarnings(Array("LooksLikeInterpolatedString", "OptionGet")) class Settings(config: Config) extends Extension { @nowarn("cat=unused") val appConfig: AppConfig = { implicit val uriConverter: ConfigConvert[Uri] = ConfigConvert.viaString[Uri](catchReadError(s => Uri(s)), _.toString) implicit val pathConverter: ConfigConvert[Path] = ConfigConvert.viaString[Path](catchReadError(s => Paths.get(s)), _.toString) implicit val absoluteIriConverter: ConfigConvert[AbsoluteIri] = ConfigConvert.viaString[AbsoluteIri](catchReadError(s => url"$s"), _.toString) ConfigSource.fromConfig(config).at("app").loadOrThrow[AppConfig] } } object Settings extends ExtensionId[Settings] with ExtensionIdProvider { override def lookup(): ExtensionId[_ <: Extension] = Settings override def createExtension(system: ExtendedActorSystem): Settings = apply(system.settings.config) def apply(config: Config): Settings = new Settings(config) }
Example 13
Source File: ExternalAddressExt.scala From ForestFlow with Apache License 2.0 | 5 votes |
package ai.forestflow.akka.extensions import akka.actor.{ActorRef, ActorSystem, Address, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} //noinspection TypeAnnotation object ExternalAddress extends ExtensionId[ExternalAddressExt] with ExtensionIdProvider { //The lookup method is required by ExtensionIdProvider, // so we return ourselves here, this allows us // to configure our extension to be loaded when // the ActorSystem starts override def lookup = ExternalAddress //This method will be called by Akka // to instantiate our Extension override def createExtension(system: ExtendedActorSystem): ExternalAddressExt = new ExternalAddressExt(system) override def get(system: ActorSystem): ExternalAddressExt = super.get(system) } class ExternalAddressExt(system: ExtendedActorSystem) extends Extension { def addressForAkka: Address = system.provider.getDefaultAddress def akkaActorRefFromString(refString: String): ActorRef = system.provider.resolveActorRef(refString) }
Example 14
Source File: ApplicationStatus.scala From reactive-lib with Apache License 2.0 | 5 votes |
package com.lightbend.rp.status import akka.actor.{ ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider } import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server._ import akka.management.http.{ ManagementRouteProvider, ManagementRouteProviderSettings } import scala.collection.immutable.Seq import scala.concurrent.{ ExecutionContext, Future } import Directives._ class ApplicationStatus(system: ExtendedActorSystem) extends Extension with ManagementRouteProvider { private val settings = Settings(system) private val healthChecks = settings .healthChecks .map(c => system .dynamicAccess .createInstanceFor[HealthCheck](c, Seq.empty) .getOrElse(throw new IllegalArgumentException(s"Incompatible HealthCheck class definition: $c"))) private val readinessChecks = settings .readinessChecks .map(c => system .dynamicAccess .createInstanceFor[ReadinessCheck](c, Seq.empty) .getOrElse(throw new IllegalArgumentException(s"Incompatible ReadinessCheck class definition: $c"))) def routes(settings: ManagementRouteProviderSettings): Route = pathPrefix("platform-tooling") { import system.dispatcher concat( path("ping")(complete("pong!")), path("healthy")(complete(isHealthy.map(h => if (h) StatusCodes.OK else StatusCodes.ServiceUnavailable))), path("ready")(complete(isReady.map(r => if (r) StatusCodes.OK else StatusCodes.ServiceUnavailable)))) } def isHealthy(implicit ec: ExecutionContext): Future[Boolean] = Future .sequence(healthChecks.map(_.healthy(system))) .map(_.forall(identity)) def isReady(implicit ec: ExecutionContext): Future[Boolean] = Future .sequence(readinessChecks.map(_.ready(system))) .map(_.forall(identity)) } object ApplicationStatus extends ExtensionId[ApplicationStatus] with ExtensionIdProvider { override def lookup: ApplicationStatus.type = ApplicationStatus override def get(system: ActorSystem): ApplicationStatus = super.get(system) override def createExtension(system: ExtendedActorSystem): ApplicationStatus = new ApplicationStatus(system) }
Example 15
Source File: CassandraHeath.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.routes import akka.Done import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.event.Logging import akka.persistence.cassandra.CassandraPluginConfig import akka.persistence.cassandra.session.scaladsl.CassandraSession import scala.concurrent.Future trait CassandraHeath extends Extension { def check: Future[Boolean] } object CassandraHeath extends ExtensionId[CassandraHeath] with ExtensionIdProvider { override def lookup(): ExtensionId[_ <: Extension] = CassandraHeath override def createExtension(as: ExtendedActorSystem): CassandraHeath = { implicit val ec = as.dispatcher val log = Logging(as, "CassandraHeathCheck") val config = new CassandraPluginConfig(as, as.settings.config.getConfig("cassandra-journal")) val (p, s) = (config.sessionProvider, config.sessionSettings) val session = new CassandraSession(as, p, s, ec, log, "health", _ => Future.successful(Done.done())) new CassandraHeath { private val query = s"SELECT now() FROM ${config.keyspace}.messages;" override def check: Future[Boolean] = { session.selectOne(query).map(_ => true).recover { case err => log.error("Error while attempting to query for health check", err) false } } } } }
Example 16
Source File: Settings.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.config import akka.actor.{ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.Uri import ch.epfl.bluebrain.nexus.iam.types.Permission import com.github.ghik.silencer.silent import com.typesafe.config.Config import pureconfig.generic.auto._ import pureconfig.ConvertHelpers._ import pureconfig._ @SuppressWarnings(Array("LooksLikeInterpolatedString")) class Settings(config: Config) extends Extension { @silent // not recognized as used... but it is below private implicit val uriConverter: ConfigConvert[Uri] = ConfigConvert.viaString[Uri](catchReadError(Uri(_)), _.toString) @silent // not recognized as used... but it is below private implicit val permissionConverter: ConfigConvert[Permission] = ConfigConvert.viaString[Permission](optF(Permission(_)), _.toString) val appConfig: AppConfig = ConfigSource.fromConfig(config).at("app").loadOrThrow[AppConfig] } object Settings extends ExtensionId[Settings] with ExtensionIdProvider { override def lookup(): ExtensionId[_ <: Extension] = Settings override def createExtension(system: ExtendedActorSystem): Settings = apply(system.settings.config) def apply(config: Config): Settings = new Settings(config) }