play.api.inject.Module Scala Examples

The following examples show how to use play.api.inject.Module. 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: ClusterShardingTypedModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.cluster.typed

import akka.actor.ActorSystem
import akka.cluster.sharding.typed.javadsl.ClusterSharding
import javax.inject.Inject
import javax.inject.Provider
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module

class ClusterShardingTypedModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[ClusterSharding].toProvider[ClusterShardingTypedProvider]
  )
}

private[lagom] class ClusterShardingTypedProvider @Inject() (system: ActorSystem) extends Provider[ClusterSharding] {
  private val instance: ClusterSharding = {
    import akka.actor.typed.scaladsl.adapter._
    val actorSystemTyped = system.toTyped
    ClusterSharding.get(actorSystemTyped)
  }

  override def get(): ClusterSharding = instance
} 
Example 2
Source File: SpringInjector.scala    From play-spring-loader   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.play.spring

import org.springframework.beans.BeanInstantiationException
import org.springframework.beans.factory.config.{ AutowireCapableBeanFactory, BeanDefinition }
import org.springframework.beans.factory.{ BeanCreationException, NoSuchBeanDefinitionException }
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
import org.springframework.beans.factory.support.{ GenericBeanDefinition, DefaultListableBeanFactory }
import play.api.inject.{ BindingKey, Injector, Modules, Module }
import play.api.{ PlayException, Configuration, Environment }

import scala.reflect.ClassTag

class SpringInjector(factory: DefaultListableBeanFactory) extends Injector {

  private val bpp = new AutowiredAnnotationBeanPostProcessor()
  bpp.setBeanFactory(factory)

  def instanceOf[T](implicit ct: ClassTag[T]) = instanceOf(ct.runtimeClass).asInstanceOf[T]

  def instanceOf[T](clazz: Class[T]) = {
    getBean(clazz)
  }

  def getBean[T](clazz: Class[T]): T = {
    try {
      factory.getBean(clazz)
    } catch {

      case e: NoSuchBeanDefinitionException =>
        // if the class is a concrete type, attempt to create a just in time binding
        if (!clazz.isInterface 
  def springable(module: Any): Module = module match {
    case playModule: Module => playModule
    //    case bin
    case unknown => throw new PlayException(
      "Unknown module type",
      s"Module [$unknown] is not a Play module")
  }
} 
Example 3
Source File: ScalinguaPlugin.scala    From scalingua   with Apache License 2.0 5 votes vote down vote up
package ru.makkarpov.scalingua.play

import javax.inject.Inject

import play.api.{Application, BuiltInComponentsFromContext, Configuration, Environment}
import play.api.inject.{Binding, Module}
import ru.makkarpov.scalingua.Messages

trait ScalinguaComponents {
  def configuration: Configuration
  def environment: Environment

  lazy val messages = new MessagesProvider(new ScalinguaConfigProvider(configuration).get(), environment).get()
}

class ScalinguaModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[ScalinguaConfig].toProvider[ScalinguaConfigProvider],
    bind[Messages].toProvider[MessagesProvider]
  )
} 
Example 4
Source File: PrometheusModule.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters

import io.prometheus.client.CollectorRegistry
import io.prometheus.client.hotspot._
import org.slf4j.LoggerFactory
import play.api.inject.{Binding, Module}
import play.api.{Configuration, Environment}

object PrometheusModule {
  val defaultExportsKey = "play-prometheus-filters.register-default-hotspot-collectors"
}

class PrometheusModule extends Module {
  import PrometheusModule._

  private val logger = LoggerFactory.getLogger(classOf[PrometheusModule])

  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    CollectorRegistry.defaultRegistry.clear()

    configuration.getOptional[Boolean](defaultExportsKey).foreach { enabled =>
      if (enabled) {
        logger.info("Default exports are enabled")
        DefaultExports.initialize()
        logger.info("Default exports registered")
      } else {
        logger.info("Default exports are disabled")
      }
    }

    Seq(
      bind[CollectorRegistry].to(CollectorRegistry.defaultRegistry)
    )
  }
} 
Example 5
Source File: HoconMessagesApi.scala    From play-i18n-hocon   with Apache License 2.0 5 votes vote down vote up
package com.marcospereira.play.i18n

import java.net.URL
import java.util.Properties
import javax.inject.{ Inject, Singleton }

import com.typesafe.config.ConfigFactory
import play.api.http.HttpConfiguration
import play.api.i18n._
import play.api.inject.Module
import play.api.{ Configuration, Environment }
import play.utils.Resources

import scala.collection.JavaConverters._

@Singleton
class HoconMessagesApiProvider @Inject() (
  environment: Environment,
  config: Configuration,
  langs: Langs,
  httpConfiguration: HttpConfiguration
)
    extends DefaultMessagesApiProvider(environment, config, langs, httpConfiguration) {

  override lazy val get: MessagesApi = {
    new DefaultMessagesApi(
      loadAllMessages,
      langs,
      langCookieName = langCookieName,
      langCookieSecure = langCookieSecure,
      langCookieHttpOnly = langCookieHttpOnly,
      httpConfiguration = httpConfiguration
    )
  }

  override protected def loadMessages(file: String): Map[String, String] = {
    getResources(file)
      .filterNot(url => Resources.isDirectory(environment.classLoader, url)).reverse
      .map(getMessages)
      .foldLeft(Map.empty[String, String]) { _ ++ _ }
  }

  override protected def loadAllMessages: Map[String, Map[String, String]] = {
    langs.availables.map(_.code).map { lang =>
      (lang, loadMessages(s"messages.$lang.conf"))
    }.toMap ++ Map(
      "default" -> loadMessages("messages.conf"),
      "default.play" -> loadMessages("messages.default")
    )
  }

  override protected def joinPaths(first: Option[String], second: String) = first match {
    case Some(parent) => new java.io.File(parent, second).getPath
    case None => second
  }

  private def getResources(file: String): List[URL] = {
    environment.classLoader.getResources(joinPaths(messagesPrefix, file)).asScala.toList
  }

  private def getMessages(url: URL): Map[String, String] = {
    // messages.default is bundled with play and it is a properties file
    val config = if (url.toString.endsWith("messages.default")) {
      ConfigFactory.parseProperties(getProperties(url))
    } else {
      ConfigFactory.parseURL(url)
    }

    config.resolve().entrySet().asScala
      .map(e => e.getKey -> String.valueOf(e.getValue.unwrapped()))
      .toMap
  }

  private def getProperties(url: URL): Properties = {
    val properties = new Properties()
    val input = url.openStream()
    try {
      properties.load(input)
    } finally {
      input.close()
    }
    properties
  }
}


trait HoconI18nComponents extends I18nComponents {

  def environment: Environment
  def configuration: Configuration
  def httpConfiguration: HttpConfiguration
  def langs: Langs

  override lazy val messagesApi: MessagesApi = new HoconMessagesApiProvider(environment, configuration, langs, httpConfiguration).get
} 
Example 6
Source File: CouchbasePersistenceModule.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.couchbase

import java.net.URI

import akka.actor.ActorSystem
import akka.event.Logging
import akka.stream.alpakka.couchbase.javadsl.CouchbaseSession
import akka.stream.alpakka.couchbase.CouchbaseSessionSettings
import com.google.inject.Provider
import com.lightbend.lagom.internal.javadsl.persistence.couchbase.{
  CouchbasePersistentEntityRegistry,
  CouchbaseReadSideImpl,
  JavadslCouchbaseOffsetStore
}
import com.lightbend.lagom.internal.persistence.couchbase.{
  CouchbaseConfigValidator,
  CouchbaseOffsetStore,
  ServiceLocatorAdapter,
  ServiceLocatorHolder
}
import com.lightbend.lagom.javadsl.api.ServiceLocator
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.spi.persistence.OffsetStore
import com.typesafe.config.Config
import javax.inject.Inject
import play.api.inject.{Binding, Injector, Module}
import play.api.{Configuration, Environment}

import scala.compat.java8.FutureConverters._
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.Try


class CouchbasePersistenceModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[CouchbasePersistenceModule.InitServiceLocatorHolder].toSelf.eagerly(),
    bind[PersistentEntityRegistry].to[CouchbasePersistentEntityRegistry],
    bind[CouchbaseSession].toProvider[CouchbaseProvider],
    bind[CouchbaseReadSide].to[CouchbaseReadSideImpl],
    //TODO: add other modules similar to Cassandra
    //    bind[CassandraReadSideSettings].toSelf,
    bind[CouchbaseOffsetStore].to(bind[JavadslCouchbaseOffsetStore]),
    bind[OffsetStore].to(bind[CouchbaseOffsetStore])
  )
}

private[lagom] class CouchbaseProvider @Inject() (system: ActorSystem, cfg: Config) extends Provider[CouchbaseSession] {
  private val log = Logging(system, classOf[CouchbaseProvider])

  CouchbaseConfigValidator.validateBucket("lagom.persistence.read-side.couchbase", cfg, log)

  private val readSideCouchbaseConfig: Config =
    cfg.getConfig("lagom.persistence.read-side.couchbase")

  private val sessionSettings = CouchbaseSessionSettings(
    readSideCouchbaseConfig.getConfig("connection")
  )

  private val bucket = readSideCouchbaseConfig.getString("bucket")

  // FIXME is there a way to have async component creation in lagom instead of letting every component know that the thing is async?
  // if not we should pass Future[CouchbaseSession] around and let the use sites mix in AsyncCouchbaseSession - but if we use
  // that from Lagom it needs to be made public API
  // FIXME this should be the Java API of CouchbaseSession, when there is one
  lazy val couchbase: CouchbaseSession =
    Await.result(CouchbaseSession.create(sessionSettings, bucket, system.dispatcher).toScala, 30.seconds)

  override def get(): CouchbaseSession = couchbase
}

private[lagom] object CouchbasePersistenceModule {
  class InitServiceLocatorHolder @Inject() (system: ActorSystem, injector: Injector) {
    def init(): Unit =
      Try(injector.instanceOf[ServiceLocator]).foreach { locator =>
        ServiceLocatorHolder(system).setServiceLocator(new ServiceLocatorAdapter {
          override def locateAll(name: String): Future[List[URI]] = {
            import system.dispatcher

            import scala.collection.JavaConverters._
            import scala.compat.java8.FutureConverters._
            locator.locateAll(name).toScala.map(_.asScala.toList)
          }
        })
      }
  }
} 
Example 7
Source File: AkkaManagementModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.server

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import com.lightbend.lagom.internal.akka.management.AkkaManagementTrigger
import com.typesafe.config.Config
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Mode

import scala.concurrent.ExecutionContext

private[lagom] class AkkaManagementModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    // The trigger must be eager because it's often not required by anyone as a dependency to
    // be injected and yet it must be started anyway
    Seq(bind[AkkaManagementTrigger].toProvider[AkkaManagementProvider].eagerly())
  }
}

@Singleton
private[lagom] class AkkaManagementProvider @Inject() (
    config: Config,
    actorSystem: ActorSystem,
    coordinatedShutdown: CoordinatedShutdown,
    environment: Environment,
    executionContext: ExecutionContext
) extends Provider[AkkaManagementTrigger] {
  override def get(): AkkaManagementTrigger = {
    val instance = new AkkaManagementTrigger(config, actorSystem, coordinatedShutdown)(executionContext)
    if (environment.mode == Mode.Prod) {
      instance.start()
    }
    instance
  }
} 
Example 8
Source File: JacksonModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.jackson

import akka.actor.ActorSystem
import akka.serialization.jackson.JacksonMigration
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module
import javax.inject.Inject


class JacksonModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[JacksonMigrationCheck].toSelf.eagerly(),
    bind[JacksonSerializerFactory].toSelf,
    bind[JacksonExceptionSerializer].toSelf
  )
}

private[lagom] class JacksonMigrationCheck @Inject() (system: ActorSystem) {
  if (system.settings.config.hasPath("lagom.serialization.json.migrations")) {
    throw new IllegalStateException(
      "JacksonJsonSerializer migrations defined in " +
        s"'lagom.serialization.json.migrations' must be rewritten as [${classOf[JacksonMigration].getName}] " +
        "and defined in config 'akka.serialization.jackson.migrations'."
    )
  }
} 
Example 9
Source File: JoinCluster.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.cluster

import akka.actor.ActorSystem
import com.lightbend.lagom.internal.akka.management.AkkaManagementTrigger
import com.lightbend.lagom.internal.cluster.JoinClusterImpl
import javax.inject.Inject
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module

class JoinClusterModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[JoinCluster].toSelf.eagerly()
  )
}

private[lagom] class JoinCluster @Inject() (
    system: ActorSystem,
    environment: Environment,
    akkaManagementTrigger: AkkaManagementTrigger
) {
  JoinClusterImpl.join(system, environment, akkaManagementTrigger)
} 
Example 10
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 11
Source File: JdbcPersistenceModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.jdbc

import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import com.lightbend.lagom.internal.javadsl.persistence.jdbc._
import com.lightbend.lagom.internal.persistence.jdbc.SlickDbProvider
import com.lightbend.lagom.internal.persistence.jdbc.SlickOffsetStore
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.spi.persistence.OffsetStore
import play.api.Configuration
import play.api.Environment
import play.api.db.DBApi
import play.api.inject.Binding
import play.api.inject.Module

import scala.concurrent.ExecutionContext

class JdbcPersistenceModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[SlickProvider].toProvider[GuiceSlickProvider],
    bind[JdbcReadSide].to[JdbcReadSideImpl],
    bind[PersistentEntityRegistry].to[JdbcPersistentEntityRegistry],
    bind[JdbcSession].to[JdbcSessionImpl],
    bind[SlickOffsetStore].to[JavadslJdbcOffsetStore],
    bind[OffsetStore].to(bind[SlickOffsetStore])
  )
}

@Singleton
class GuiceSlickProvider @Inject() (
    dbApi: DBApi,
    actorSystem: ActorSystem,
    coordinatedShutdown: CoordinatedShutdown
)(
    implicit ec: ExecutionContext
) extends Provider[SlickProvider] {
  lazy val get = {
    // Ensures JNDI bindings are made before we build the SlickProvider
    SlickDbProvider.buildAndBindSlickDatabases(
      dbApi,
      actorSystem.settings.config,
      coordinatedShutdown
    )
    new SlickProvider(actorSystem, coordinatedShutdown)
  }
} 
Example 12
Source File: CircuitBreakerModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.javadsl.client

import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import akka.actor.ActorSystem
import com.lightbend.lagom.internal.client.CircuitBreakerConfig
import com.lightbend.lagom.internal.client.CircuitBreakerMetricsProviderImpl
import com.lightbend.lagom.internal.client.CircuitBreakerMetricsProviderProvider
import com.lightbend.lagom.internal.spi.CircuitBreakerMetricsProvider
import com.lightbend.lagom.javadsl.client.CircuitBreakersPanel
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment

class CircuitBreakerModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[CircuitBreakersPanel].to[CircuitBreakersPanelImpl],
      bind[CircuitBreakerMetricsProvider].toProvider[CircuitBreakerMetricsProviderProvider],
      bind[CircuitBreakerConfig].toSelf,
      bind[CircuitBreakerMetricsProviderImpl].toSelf
    )
  }
} 
Example 13
Source File: ProjectionRegistryModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.projection

import java.util.concurrent.CompletionStage

import akka.actor.ActorSystem
import akka.annotation.ApiMayChange
import akka.annotation.InternalApi
import com.lightbend.lagom.internal.projection.ProjectionRegistry
import com.lightbend.lagom.internal.projection.ProjectionRegistryActor.WorkerCoordinates
import com.lightbend.lagom.projection.State
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import play.api.Configuration
import play.api.Environment
import play.api.inject.Binding
import play.api.inject.Module

import scala.compat.java8.FutureConverters
import scala.concurrent.ExecutionContext


private class ProjectionsImpl @Inject() (registry: ProjectionRegistry)(
    implicit executionContext: ExecutionContext
) extends Projections {
  import FutureConverters._

  override def getStatus(): CompletionStage[State] =
    registry.getState().toJava

  override def stopAllWorkers(projectionName: String): Unit =
    registry.stopAllWorkers(projectionName)

  override def stopWorker(projectionName: String, tagName: String): Unit =
    registry.stopWorker(WorkerCoordinates(projectionName, tagName))

  override def startAllWorkers(projectionName: String): Unit =
    registry.startAllWorkers(projectionName)

  override def startWorker(projectionName: String, tagName: String): Unit =
    registry.startWorker(WorkerCoordinates(projectionName, tagName))
} 
Example 14
Source File: LagomPlayModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.play

import java.util.{ List => JList }
import java.util.Optional
import javax.inject.Inject

import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistry
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistryService
import com.lightbend.lagom.devmode.internal.registry.serviceDnsRecords
import com.lightbend.lagom.javadsl.api.ServiceAcl
import com.lightbend.lagom.javadsl.api.ServiceInfo
import com.lightbend.lagom.javadsl.api.transport.Method
import com.typesafe.config.Config
import play.api.inject.ApplicationLifecycle
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Logger

import scala.collection.JavaConverters._
import scala.compat.java8.FutureConverters._
import scala.util.Success
import scala.util.Try

class LagomPlayModule extends Module {
  private val logger = Logger(this.getClass)

  override def bindings(environment: Environment, config: Configuration): Seq[Binding[_]] = {
    val maybeServiceInfoBinding: Option[Binding[ServiceInfo]] = prepareServiceInfoBinding(config.underlying)
    val playRegistry                                          = bind[PlayRegisterWithServiceRegistry].toSelf.eagerly()

    Seq(
      playRegistry
    ) ++ maybeServiceInfoBinding.toList
  }

  private def prepareServiceInfoBinding(config: Config) = {
    val triedServiceName                   = Try(config.getString("lagom.play.service-name"))
    val triedAcls: Try[JList[_ <: Config]] = Try(config.getConfigList("lagom.play.acls"))

    val warning = "Service setup via 'application.conf' is deprecated. Remove 'lagom.play.service-name' and/or " +
      "'lagom.play.acls' and use 'bindServiceInfo' on your Guice's Module class."

    val maybeServiceInfoBinding = (triedServiceName, triedAcls) match {
      case (Success(serviceName), Success(aclList)) => {
        logger.warn(warning)
        // create a ServiceInfo in case user doesn't see the warning
        val acls = parseAclList(aclList)
        Some(bind[ServiceInfo].toInstance(ServiceInfo.of(serviceName, acls: _*)))
      }
      case (Success(serviceName), _) => {
        logger.warn(warning)
        // create a ServiceInfo in case user doesn't see the warning
        Some(bind[ServiceInfo].toInstance(ServiceInfo.of(serviceName)))
      }
      case (_, Success(_)) => {
        logger.warn(warning)
        // can't create a ServiceInfo because service-name is missing
        None
      }
      case _ => None
    }
    maybeServiceInfoBinding
  }

  private def parseAclList(aclList: JList[_ <: Config]): Seq[ServiceAcl] = {
    aclList.asScala.map { aclConfig =>
      val method = if (aclConfig.hasPath("method")) {
        Optional.of(new Method(aclConfig.getString("method")))
      } else Optional.empty[Method]
      val pathRegex = if (aclConfig.hasPath("path-regex")) {
        Optional.of(aclConfig.getString("path-regex"))
      } else Optional.empty[String]
      new ServiceAcl(method, pathRegex)
    }.toSeq
  }
}

class PlayRegisterWithServiceRegistry @Inject() (
    config: Config,
    serviceInfo: ServiceInfo,
    serviceRegistry: ServiceRegistry,
    applicationLifecycle: ApplicationLifecycle
) {
  val uris = serviceDnsRecords(config)

  private val serviceAcls = serviceInfo.getAcls
  private val service     = ServiceRegistryService.of(uris.asJava, serviceAcls)
  // TODO: fix -> this register operation is registering all ACLs under the microservice name, not under each locatable service name. Will lead to unlocatable.
  serviceRegistry.register(serviceInfo.serviceName()).invoke(service)

  applicationLifecycle.addStopHook(() => serviceRegistry.unregister(serviceInfo.serviceName()).invoke().toScala)
} 
Example 15
Source File: ServiceRegistrationModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.internal.server

import java.net.URI
import java.util.function.{ Function => JFunction }

import akka.actor.CoordinatedShutdown
import akka.Done
import akka.NotUsed
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistry
import com.lightbend.lagom.internal.javadsl.registry.ServiceRegistryService
import com.lightbend.lagom.internal.javadsl.server.ResolvedServices
import com.lightbend.lagom.devmode.internal.registry.serviceDnsRecords
import com.typesafe.config.Config
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import play.api.inject.Binding
import play.api.inject.Module
import play.api.Configuration
import play.api.Environment
import play.api.Logger

import scala.compat.java8.FutureConverters.CompletionStageOps
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.collection.JavaConverters._
import scala.collection.immutable

class ServiceRegistrationModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[ServiceRegistrationModule.RegisterWithServiceRegistry].toSelf.eagerly(),
    bind[ServiceRegistrationModule.ServiceConfig].toProvider[ServiceRegistrationModule.ServiceConfigProvider]
  )
}

object ServiceRegistrationModule {
  class ServiceConfigProvider @Inject() (config: Config) extends Provider[ServiceConfig] {
    override lazy val get = ServiceConfig(serviceDnsRecords(config))
  }

  case class ServiceConfig(uris: immutable.Seq[URI])

  
  @Singleton
  private class RegisterWithServiceRegistry @Inject() (
      coordinatedShutdown: CoordinatedShutdown,
      resolvedServices: ResolvedServices,
      config: ServiceConfig,
      registry: ServiceRegistry
  )(implicit ec: ExecutionContext) {
    private lazy val logger: Logger = Logger(this.getClass())

    private val locatableServices = resolvedServices.services.filter(_.descriptor.locatableService)

    coordinatedShutdown.addTask(
      CoordinatedShutdown.PhaseBeforeServiceUnbind,
      "unregister-services-from-service-locator-javadsl"
    ) { () =>
      Future
        .sequence(locatableServices.map { service =>
          registry.unregister(service.descriptor.name).invoke().toScala
        })
        .map(_ => Done)
    }

    locatableServices.foreach { service =>
      val c = ServiceRegistryService.of(config.uris.asJava, service.descriptor.acls)
      registry
        .register(service.descriptor.name)
        .invoke(c)
        .exceptionally(new JFunction[Throwable, NotUsed] {
          def apply(t: Throwable) = {
            logger
              .error(s"Service name=[${service.descriptor.name}] couldn't register itself to the service locator.", t)
            NotUsed.getInstance()
          }
        })
    }
  }
} 
Example 16
Source File: Bindings.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.api.lib

import play.api.inject.Module
import play.api.{Configuration, Environment, Mode}

class GithubModule extends Module {

  def bindings(env: Environment, conf: Configuration) = {
    env.mode match {
      case Mode.Prod | Mode.Dev => Seq(
        bind[Github].to[DefaultGithub]
      )
      case Mode.Test => Seq(
        bind[Github].to[MockGithub]
      )
    }
  }

} 
Example 17
Source File: Bindings.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.www.lib

import play.api.{Configuration, Environment, Mode}
import play.api.inject.Module

class DependencyClientProviderModule extends Module {

  def bindings(env: Environment, conf: Configuration) = {
    env.mode match {
      case Mode.Prod | Mode.Dev => Seq(
        bind[DependencyClientProvider].to[DefaultDependencyClientProvider]
      )
      case Mode.Test => Seq(
        // TODO: Add mock
        bind[DependencyClientProvider].to[DependencyClientProvider]
      )
    }
  }

} 
Example 18
Source File: DatabaseModule.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package modules

import com.github.mauricio.async.db.SSLConfiguration
import com.github.mauricio.async.db.pool.{PartitionedConnectionPool, PoolConfiguration}
import com.github.mauricio.async.db.postgresql.pool.PostgreSQLConnectionFactory
import com.github.mauricio.async.db.postgresql.util.URLParser
import io.getquill.{PostgresAsyncContext, SnakeCase}
import javax.inject.{Inject, Singleton}
import org.slf4j.LoggerFactory
import play.api.inject.{ApplicationLifecycle, Binding, Module}
import play.api.{Configuration, Environment}

import scala.concurrent.ExecutionContext

class DatabaseModule extends Module {
  def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[Database].to[DatabaseImpl]
    )
  }
}

trait Database {
  val ctx: PostgresAsyncContext[SnakeCase]
}

@Singleton
class DatabaseImpl @Inject()(lifecycle: ApplicationLifecycle, playConfig: Configuration) (implicit ec: ExecutionContext) extends Database {

  private val log = LoggerFactory.getLogger(this.getClass)

  private val maybeDbUrl = playConfig.getOptional[String]("db.default.url")

  private val config = maybeDbUrl.map(URLParser.parse(_)).getOrElse(URLParser.DEFAULT)

  private val configWithMaybeSsl = playConfig.getOptional[String]("db.default.sslmode").fold(config) { sslmode =>
    val sslConfig = SSLConfiguration(Map("sslmode" -> sslmode))
    config.copy(ssl = sslConfig)
  }

  private val connectionFactory = new PostgreSQLConnectionFactory(configWithMaybeSsl)

  private val defaultPoolConfig = PoolConfiguration.Default

  private val maxObjects = playConfig.getOptional[Int]("db.default.max-objects").getOrElse(defaultPoolConfig.maxObjects)
  private val maxIdleMillis = playConfig.getOptional[Long]("db.default.max-idle-millis").getOrElse(defaultPoolConfig.maxIdle)
  private val maxQueueSize = playConfig.getOptional[Int]("db.default.max-queue-size").getOrElse(defaultPoolConfig.maxQueueSize)
  private val validationInterval = playConfig.getOptional[Long]("db.default.max-queue-size").getOrElse(defaultPoolConfig.validationInterval)

  private val poolConfig = new PoolConfiguration(maxObjects, maxIdleMillis, maxQueueSize, validationInterval)

  private val numberOfPartitions = playConfig.getOptional[Int]("db.default.number-of-partitions").getOrElse(4)

  private val pool = new PartitionedConnectionPool(
    connectionFactory,
    poolConfig,
    numberOfPartitions,
    ec
  )

  lifecycle.addStopHook { () =>
    pool.close
  }

  val ctx = new PostgresAsyncContext(SnakeCase, pool)

}