com.google.inject.AbstractModule Scala Examples

The following examples show how to use com.google.inject.AbstractModule. 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: BasicSecurityModule.scala    From asura   with MIT License 5 votes vote down vote up
package asura.play.module

import com.google.inject.AbstractModule
import org.pac4j.play.LogoutController
import org.pac4j.play.scala.{DefaultSecurityComponents, SecurityComponents}
import org.pac4j.play.store.{PlayCacheSessionStore, PlaySessionStore}
import play.api.{Configuration, Environment}

class BasicSecurityModule(environment: Environment, configuration: Configuration) extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[PlaySessionStore]).to(classOf[PlayCacheSessionStore])
    // logout
    val logoutController = new LogoutController()
    logoutController.setDestroySession(true)
    logoutController.setLocalLogout(true)
    logoutController.setDefaultUrl("/")
    bind(classOf[LogoutController]).toInstance(logoutController)
    // security components used in controllers
    bind(classOf[SecurityComponents]).to(classOf[DefaultSecurityComponents])
  }
} 
Example 2
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.atlas.stream

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
          bind(classOf[Registry]).toInstance(new NoopRegistry)
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 3
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.atlas.druid

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple versions of registry
      // and config bindings. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Registry]).toInstance(new NoopRegistry)
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }
} 
Example 4
Source File: AppModuleSuite.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.atlas.aggregator

import javax.inject.Singleton
import com.google.inject.AbstractModule
import com.google.inject.Guice
import com.google.inject.Provider
import com.netflix.spectator.api.Clock
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.netflix.spectator.atlas.AtlasConfig
import com.netflix.spectator.atlas.AtlasRegistry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.scalatest.funsuite.AnyFunSuite

class AppModuleSuite extends AnyFunSuite {

  import AppModuleSuite._

  private val config = ConfigFactory.load()

  test("aggr service") {
    val injector = Guice.createInjector(
      new AppModule,
      new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(config)
          bind(classOf[Registry]).toProvider(classOf[RegistryProvider])
        }
      }
    )

    val aggr = injector.getInstance(classOf[AtlasAggregatorService])
    assert(aggr != null)
  }

  test("aggr config should use prefix") {
    val config = ConfigFactory.parseString("""
        |netflix.atlas.aggr.registry.atlas.uri = "test"
      """.stripMargin)
    val aggr = new AggrConfig(config, new NoopRegistry)
    assert(aggr.uri() === "test")
  }

  test("aggr config should use default for missing props") {
    val config = ConfigFactory.parseString("""
        |netflix.atlas.aggr.registry.atlas.uri = "test"
      """.stripMargin)
    val aggr = new AggrConfig(config, new NoopRegistry)
    assert(aggr.batchSize() === 10000)
  }
}

object AppModuleSuite {

  @Singleton
  class RegistryProvider extends Provider[Registry] {
    override def get(): Registry = {
      val cfg = new AtlasConfig {
        override def get(k: String): String = null
      }
      new AtlasRegistry(Clock.SYSTEM, cfg)
    }
  }
} 
Example 5
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.atlas.aggregator

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    modules.add(new AppModule)
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
          bind(classOf[Registry]).toInstance(new NoopRegistry)
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 6
Source File: ServiceInjector.scala    From BacklogMigration-Redmine   with MIT License 5 votes vote down vote up
package com.nulabinc.backlog.r2b.redmine.modules

import com.google.inject.{AbstractModule, Guice, Injector}
import com.nulabinc.backlog.r2b.redmine.conf.RedmineApiConfiguration
import com.nulabinc.backlog.r2b.redmine.service._
import com.taskadapter.redmineapi.{RedmineManager, RedmineManagerFactory}


object ServiceInjector {

  def createInjector(apiConfig: RedmineApiConfiguration): Injector = {
    Guice.createInjector(new AbstractModule() {
      override def configure(): Unit = {
        val transportConfig = RedmineManagerFactory.createShortTermConfig(RedmineManagerFactory.createInsecureConnectionManager())
        val redmine         = RedmineManagerFactory.createWithApiKey(apiConfig.url, apiConfig.key, transportConfig)

        bind(classOf[RedmineManager]).toInstance(redmine)
        bind(classOf[PriorityService]).to(classOf[PriorityServiceImpl])
        bind(classOf[StatusService]).to(classOf[StatusServiceImpl])
        bind(classOf[UserService]).to(classOf[UserServiceImpl])
        bind(classOf[ProjectService]).to(classOf[ProjectServiceImpl])
      }
    })
  }

} 
Example 7
Source File: Module.scala    From play-swagger   with Apache License 2.0 5 votes vote down vote up
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ ApplicationTimer, AtomicCounter, Counter }


class Module extends AbstractModule {

  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])
  }

} 
Example 8
Source File: DB.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package storage.db

import akka.actor.ActorSystem
import com.google.inject.AbstractModule
import java.sql.Connection
import javax.inject.{ Inject, Singleton }
import services.user.UserService
import services.user.Roles
import org.jooq.impl.DSL
import org.jooq.{ SQLDialect, DSLContext }
import play.api.Logger
import play.api.db.Database
import scala.collection.JavaConversions._
import scala.concurrent.{ ExecutionContext, Future }
import scala.io.Source

object DB {

  val CURRENT_SQLDIALECTT = SQLDialect.POSTGRES_9_4

}


  private def initDB(connection: Connection) = {

    // Splitting by ; is not 100% robust - but should be sufficient for our own schema file
    val statement = connection.createStatement

    Source.fromFile("conf/schema.sql", "UTF-8")
      .getLines().map(_.trim)
      .filter(line => !(line.startsWith("--") || line.isEmpty))
      .mkString(" ").split(";")
      .foreach(s => {
        statement.addBatch(s + ";")
      })

    statement.executeBatch()
    statement.close()
  }
  
  private def createDefaultUserIfEmpty() =
    userService.countUsers.map { count =>
      if (count == 0) {
        Logger.warn("#######################################################")
        Logger.warn("# Empty user table - creating default recogito/recogito")
        Logger.warn("#######################################################")
        
        val f = for {
          _ <- userService.insertUser("recogito", "[email protected]", "recogito", false)
          _ <- userService.insertUserRole("recogito", Roles.Admin)
        } yield()
  
        f.map { _ =>
          Logger.warn("# Done. Make sure to remove this user in production!")
          Logger.warn("#######################################################")
        } recover { case t: Throwable => t.printStackTrace() }
      }
    } recover { case t: Throwable =>
      t.printStackTrace()
    }

} 
Example 9
Source File: SecurityModule.scala    From asura   with MIT License 5 votes vote down vote up
package asura.app.modules

import asura.app.api.auth._
import asura.play.actions.SecurityHttpActionAdapter
import com.google.inject.{AbstractModule, Provides}
import org.pac4j.core.client.Clients
import org.pac4j.core.config.Config
import org.pac4j.http.client.direct.{DirectBasicAuthClient, DirectFormClient, HeaderClient}
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.play.LogoutController
import org.pac4j.play.scala.{DefaultSecurityComponents, SecurityComponents}
import org.pac4j.play.store.{PlayCacheSessionStore, PlaySessionStore}
import play.api.{Configuration, Environment}

class SecurityModule(environment: Environment, configuration: Configuration) extends AbstractModule {

  override def configure(): Unit = {
    bind(classOf[PlaySessionStore]).to(classOf[PlayCacheSessionStore])
    // logout
    val logoutController = new LogoutController()
    logoutController.setDestroySession(true)
    logoutController.setLocalLogout(true)
    logoutController.setDefaultUrl("/")
    bind(classOf[LogoutController]).toInstance(logoutController)
    // security components used in controllers
    bind(classOf[SecurityComponents]).to(classOf[DefaultSecurityComponents])
  }

  @Provides
  def directFormClient: DirectFormClient = {
    val client = if (configuration.getOptional[Boolean]("asura.ldap.enabled").getOrElse(false)) {
      new DirectFormClient(LdapAuthenticator(configuration))
    } else {
      new DirectFormClient(new SimpleTestUsernamePasswordAuthenticator(configuration))
    }
    // client.addAuthorizationGenerator(new RoleAdminAuthGenerator(configuration.get[Seq[String]]("asura.admin")))
    client
  }

  @Provides
  def directBasicAuthClient: DirectBasicAuthClient = {
    val client = if (configuration.getOptional[Boolean]("asura.ldap.enabled").getOrElse(false)) {
      new DirectBasicAuthClient(LdapAuthenticator(configuration))
    } else {
      new DirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator(configuration))
    }
    // client.addAuthorizationGenerator(new RoleAdminAuthGenerator(configuration.get[Seq[String]]("asura.admin")))
    client
  }

  @Provides
  def headerClient: HeaderClient = {
    val jwtAuthenticator = new JwtAuthenticator()
    jwtAuthenticator.addSignatureConfiguration(new SecretSignatureConfiguration(configuration.get[String]("asura.jwt.secret")))
    val client = new HeaderClient("Authorization", "Bearer ", jwtAuthenticator)
    // client.addAuthorizationGenerator(new RoleAdminAuthGenerator(configuration.get[Seq[String]]("asura.admin")))
    client
  }

  @Provides
  def provideConfig(directFormClient: DirectFormClient, headerClient: HeaderClient, directBasicAuthClient: DirectBasicAuthClient): Config = {
    val clients = new Clients(directFormClient, headerClient, directBasicAuthClient)
    val config = new Config(clients)
    config.setHttpActionAdapter(new SecurityHttpActionAdapter())
    // config.addAuthorizer(Authorizer.ADMIN, new RequireAnyRoleAuthorizer(Role.ADMIN))
    config
  }
} 
Example 10
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.lwc

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new AppModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 11
Source File: Module.scala    From elastiknn   with Apache License 2.0 5 votes vote down vote up
import java.util.concurrent.{ExecutorService, Executors, ThreadFactory}

import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.google.inject.{AbstractModule, TypeLiteral}
import com.klibisz.elastiknn.client.{ElastiknnClient, ElastiknnFutureClient}
import javax.inject.Provider
import play.api.{Configuration, Environment}

import scala.concurrent.ExecutionContext

class Module(environment: Environment, configuration: Configuration) extends AbstractModule {

  val eknnProvider = new Provider[ElastiknnFutureClient] {
    override def get(): ElastiknnFutureClient = {
      val tfac: ThreadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("elastiknn-%d").build()
      val exec: ExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime.availableProcessors(), tfac)
      implicit val ec: ExecutionContext = ExecutionContext.fromExecutor(exec)
      val host = configuration.underlying.getString("elastiknn.elasticsearch.host")
      val port = configuration.underlying.getInt("elastiknn.elasticsearch.port")
      ElastiknnClient.futureClient(host, port)
    }
  }

  override def configure(): Unit = {
    // Weird that you have to use this constructor, but it works.
    bind(new TypeLiteral[ElastiknnFutureClient]() {}).toProvider(eknnProvider)
  }
} 
Example 12
Source File: TestModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.config

import com.google.inject.AbstractModule
import com.typesafe.config.Config

class TestModule(config: Config) extends AbstractModule {
  def configure(): Unit = {
    bind(classOf[TestInjectable])
    install(new ConfigModule {
      override def loadConfig(): Config = {
        config
      }
    })
  }
} 
Example 13
Source File: RestModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.rest

import scala.concurrent.Await
import scala.concurrent.duration._

import akka.actor.{ActorRef, ActorSystem}
import akka.pattern.ask
import akka.util.Timeout
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}

import ai.deepsense.commons.akka.GuiceAkkaExtension


class RestModule extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[RestServer])
  }

  @Provides
  @Singleton
  @Named("ApiRouterActorRef")
  def provideApiRouterActorRef(
      @Named("server.startup.timeout") startupTimeout: Long,
      system: ActorSystem): ActorRef = {
    val supervisor =
      system.actorOf(GuiceAkkaExtension(system).props[RestServiceSupervisor], "RestSupervisor")
    val restServiceActorProps = GuiceAkkaExtension(system).props[RestServiceActor]
    implicit val timeout: Timeout = startupTimeout.seconds
    val actorRef = supervisor.ask((restServiceActorProps, "RestServiceActor")).mapTo[ActorRef]
    Await.result(actorRef, timeout.duration)
  }
} 
Example 14
Source File: AuthModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.auth

import com.google.inject.AbstractModule
import com.google.inject.assistedinject.FactoryModuleBuilder

import ai.deepsense.commons.auth.usercontext.{KeystoneTokenTranslator, MockedTokenTranslator, TokenTranslator}

class AuthModule(useMockSecurity: Boolean) extends AbstractModule {
  override def configure(): Unit = {
    if (useMockSecurity) {
      bind(classOf[TokenTranslator]).to(classOf[MockedTokenTranslator])
    } else {
      bind(classOf[TokenTranslator]).to(classOf[KeystoneTokenTranslator])
    }
    install(new FactoryModuleBuilder()
      .implement(classOf[Authorizator], classOf[UserContextAuthorizator])
      .build(classOf[AuthorizatorProvider]))
  }
} 
Example 15
Source File: TokenApiModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.jclouds

import com.google.inject.{AbstractModule, Injector, Provides}
import org.jclouds.openstack.keystone.v2_0.KeystoneApi
import org.jclouds.openstack.keystone.v2_0.features.TokenApi

class TokenApiModule extends AbstractModule {
  override def configure(): Unit = {
    // All done by defining ProvidesMethods
  }

  @Provides
  def provideTokenApi(injector: Injector): TokenApi = {
    val keystoneApi = injector.getInstance(classOf[KeystoneApi])
    keystoneApi.getTokenApi.get()
  }
} 
Example 16
Source File: KeystoneApiModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.commons.jclouds

import java.util.Properties

import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}
import org.jclouds.Constants.{PROPERTY_CONNECTION_TIMEOUT, PROPERTY_SO_TIMEOUT}
import org.jclouds.ContextBuilder
import org.jclouds.openstack.keystone.v2_0.KeystoneApi

class KeystoneApiModule extends AbstractModule {
  override def configure(): Unit = {
    // Configuration not needed - everything is done by the methods annotated with "Provides".
  }

  @Provides
  @Singleton
  def provideKeystoneApi(
      @Named("auth-service.endpoint") endpoint: String,
      @Named("auth-service.identity") identity: String,
      @Named("auth-service.password") password: String,
      @Named("auth-service.timeout.connection") connectionTimeout: Long,
      @Named("auth-service.timeout.socket") socketTimeout: Long): KeystoneApi = {
    val overrides = new Properties()
    overrides.setProperty(PROPERTY_CONNECTION_TIMEOUT, connectionTimeout.toString)
    overrides.setProperty(PROPERTY_SO_TIMEOUT, socketTimeout.toString)
    ContextBuilder.newBuilder("openstack-keystone")
      .endpoint(endpoint)
      .credentials(identity, password)
      .overrides(overrides)
      .buildApi(classOf[KeystoneApi])
  }
} 
Example 17
Source File: ApisModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager.rest

import com.google.inject.AbstractModule
import com.google.inject.binder.LinkedBindingBuilder
import com.google.inject.multibindings.Multibinder
import com.google.inject.name.Names._

import ai.deepsense.commons.auth.AuthModule
import ai.deepsense.commons.rest.{RestComponent, VersionApi}

class ApisModule extends AbstractModule {
  private lazy val apiBinder = Multibinder.newSetBinder(binder(), classOf[RestComponent])

  protected[this] def bindApi: LinkedBindingBuilder[RestComponent] = {
    apiBinder.addBinding()
  }

  override def configure(): Unit = {
    bind(classOf[String]).annotatedWith(named("componentName")).toInstance("sessionmanager")
    install(new AuthModule(useMockSecurity = true))
    bindApi.to(classOf[SessionsApi])
    bindApi.to(classOf[VersionApi])
  }
} 
Example 18
Source File: ServiceModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager.service

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}

import ai.deepsense.commons.akka.GuiceAkkaExtension
import ai.deepsense.sessionmanager.service.actors.SessionServiceActor
import ai.deepsense.sessionmanager.service.sessionspawner.SessionSpawner
import ai.deepsense.sessionmanager.service.sessionspawner.sparklauncher.SparkLauncherSessionSpawner

class ServiceModule extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[SessionSpawner]).to(classOf[SparkLauncherSessionSpawner])
  }

  @Provides
  @Singleton
  @Named("SessionService.Actor")
  def sessionServiceActor(system: ActorSystem): ActorRef = {
    system.actorOf(GuiceAkkaExtension(system).props[SessionServiceActor], "SessionService.Actor")
  }
} 
Example 19
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.lwc

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new AppModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 20
Source File: AppModule.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.lwc

import com.amazonaws.services.cloudwatch.AmazonCloudWatch
import com.google.inject.AbstractModule
import com.google.inject.Provides
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.aws.AwsClientFactory
import com.netflix.iep.service.Service

class AppModule extends AbstractModule {
  override def configure(): Unit = {
    val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
    serviceBinder.addBinding().to(classOf[ForwardingService])
  }

  // Visibility of protected to avoid unused method warning from scala compiler
  @Provides
  protected def awsCloudWatchClient(factory: AwsClientFactory): AmazonCloudWatch = {
    factory.newInstance(classOf[AmazonCloudWatch])
  }
} 
Example 21
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.atlas.slotting

import com.amazonaws.services.autoscaling.AmazonAutoScaling
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB
import com.amazonaws.services.ec2.AmazonEC2
import com.google.inject.AbstractModule
import com.google.inject.Module
import com.google.inject.Provides
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.aws.AwsClientFactory
import com.netflix.iep.guice.BaseModule
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.Service
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.StrictLogging
import javax.inject.Singleton

object Main extends StrictLogging {

  private def isLocalEnv: Boolean = !sys.env.contains("EC2_INSTANCE_ID")

  private def getBaseModules: java.util.List[Module] = {
    val modules = {
      GuiceHelper.getModulesUsingServiceLoader
    }

    if (isLocalEnv) {
      // If we are running in a local environment, provide simple versions of registry
      // and config bindings. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Registry]).toInstance(new NoopRegistry)
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }

    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new ServerModule)

      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

  class ServerModule extends BaseModule {
    override def configure(): Unit = {
      val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
      serviceBinder.addBinding().to(classOf[SlottingService])
    }

    @Provides
    @Singleton
    protected def providesAmazonDynamoDB(factory: AwsClientFactory): AmazonDynamoDB = {
      factory.getInstance(classOf[AmazonDynamoDB])
    }

    @Provides
    @Singleton
    protected def providesAmazonEC2(factory: AwsClientFactory): AmazonEC2 = {
      factory.getInstance(classOf[AmazonEC2])
    }

    @Provides
    @Singleton
    protected def providesAmazonAutoScaling(factory: AwsClientFactory): AmazonAutoScaling = {
      factory.getInstance(classOf[AmazonAutoScaling])
    }
  }
} 
Example 22
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.atlas.persistence

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.StrictLogging

object Main extends StrictLogging {

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
          bind(classOf[Registry]).toInstance(new NoopRegistry)
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new AppModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }
} 
Example 23
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.clienttest

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.Service
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private val config = ConfigFactory.load()

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple versions of registry
      // and config bindings. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Registry]).toInstance(new NoopRegistry)
          bind(classOf[Config]).toInstance(config)
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new InstrumentationModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

  class InstrumentationModule extends AbstractModule {
    override def configure(): Unit = {
      val cls = Class.forName(config.getString("netflix.iep.clienttest.class"))
      bind(classOf[MetricLibrary]).to(cls.asInstanceOf[Class[MetricLibrary]])

      val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
      serviceBinder.addBinding().to(classOf[InstrumentationService])
      bind(classOf[InstrumentationService])
    }
  }
} 
Example 24
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.archaius

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB
import com.google.inject.AbstractModule
import com.google.inject.Module
import com.google.inject.Provides
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.aws.AwsClientFactory
import com.netflix.iep.guice.BaseModule
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.Service
import com.netflix.iep.service.ServiceManager
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spectator.api.Registry
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple versions of registry
      // and config bindings. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Registry]).toInstance(new NoopRegistry)
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new ServerModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

  class ServerModule extends BaseModule {
    override def configure(): Unit = {
      val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
      serviceBinder.addBinding().toConstructor(getConstructor(classOf[DynamoService]))
      bind(classOf[DynamoService])
      bind(classOf[PropertiesContext])
    }

    // Visibility of protected to avoid unused method warning from scala compiler
    @Provides
    protected def providesDynamoDBClient(factory: AwsClientFactory): AmazonDynamoDB = {
      factory.newInstance(classOf[AmazonDynamoDB])
    }
  }
} 
Example 25
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.lwc.fwd.admin

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the
      // config binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new AppModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent
      // for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 26
Source File: AppModule.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.lwc.fwd.admin

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB
import com.google.inject.AbstractModule
import com.google.inject.Provides
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.aws.AwsClientFactory
import com.netflix.iep.service.Service

class AppModule extends AbstractModule {
  override def configure(): Unit = {
    val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
    serviceBinder.addBinding().to(classOf[MarkerServiceImpl])
    bind(classOf[MarkerService]).to(classOf[MarkerServiceImpl])
    bind(classOf[Purger]).to(classOf[PurgerImpl])
    bind(classOf[ExpressionDetailsDao]).to(classOf[ExpressionDetailsDaoImpl])
    bind(classOf[ScalingPoliciesDao]).to(classOf[ScalingPoliciesDaoImpl])
  }

  // Visibility of protected to avoid unused method warning from scala compiler
  @Provides
  protected def awsDynamoDBClient(factory: AwsClientFactory): AmazonDynamoDB = {
    factory.newInstance(classOf[AmazonDynamoDB])
  }
} 
Example 27
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.loadgen

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new AppModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 28
Source File: Main.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.ses

import com.google.inject.AbstractModule
import com.google.inject.Module
import com.netflix.iep.guice.GuiceHelper
import com.netflix.iep.service.ServiceManager
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

object Main {

  private val logger = LoggerFactory.getLogger(getClass)

  private def getBaseModules: java.util.List[Module] = {
    val modules = GuiceHelper.getModulesUsingServiceLoader
    if (!sys.env.contains("NETFLIX_ENVIRONMENT")) {
      // If we are running in a local environment provide simple version of the config
      // binding. These bindings are normally provided by the final package
      // config for the app in the production setup.
      modules.add(new AbstractModule {
        override def configure(): Unit = {
          bind(classOf[Config]).toInstance(ConfigFactory.load())
        }
      })
    }
    modules
  }

  def main(args: Array[String]): Unit = {
    try {
      val modules = getBaseModules
      modules.add(new AppModule)
      val guice = new GuiceHelper
      guice.start(modules)
      guice.getInjector.getInstance(classOf[ServiceManager])
      guice.addShutdownHook()
    } catch {
      // Send exceptions to main log file instead of wherever STDERR is sent for the process
      case t: Throwable => logger.error("fatal error on startup", t)
    }
  }

} 
Example 29
Source File: AppModule.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.ses

import com.google.inject.AbstractModule
import com.google.inject.Provides
import com.google.inject.Singleton
import com.google.inject.multibindings.Multibinder
import com.netflix.iep.aws2.AwsClientFactory
import com.netflix.iep.service.Service
import software.amazon.awssdk.services.sqs.SqsAsyncClient

class AppModule extends AbstractModule {
  override def configure(): Unit = {
    val serviceBinder = Multibinder.newSetBinder(binder(), classOf[Service])
    serviceBinder.addBinding().to(classOf[SesMonitoringService])
  }

  @Singleton
  @Provides
  def provideAwsSqsAsyncClient(factory: AwsClientFactory): SqsAsyncClient = {
    System.setProperty(
      "software.amazon.awssdk.http.async.service.impl",
      "software.amazon.awssdk.http.nio.netty.NettySdkAsyncHttpService"
    )
    factory.newInstance(classOf[SqsAsyncClient])
  }

  @Provides
  def providesNotificationLogger(): NotificationLogger = {
    SesNotificationLogger
  }
} 
Example 30
Source File: StackConfig.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Named
import com.google.inject.{AbstractModule, Provides, Singleton}
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils
import software.amazon.awssdk.services.cloudformation.CloudFormationClient
import software.amazon.awssdk.services.cloudformation.model.{
  DescribeStackResourceRequest,
  DescribeStacksRequest
}
import software.amazon.awssdk.services.ec2.Ec2Client
import software.amazon.awssdk.services.ec2.model.DescribeTagsRequest
import software.amazon.awssdk.services.ec2.model.Filter

class StackConfig extends AbstractModule {

  override def configure() = {}

  @Provides
  @Named("cfnStackName")
  @Singleton
  def cfnStackName(ec2Client: Ec2Client): String = {
    import scala.collection.JavaConverters._
    val instanceId = EC2MetadataUtils.getInstanceId
    val resourceTypeFilter =
      Filter.builder.name("resource-type").values("instance").build()
    val resourceIdFilter =
      Filter.builder().name("resource-id").values(instanceId).build()
    val stackIdFilter =
      Filter.builder().name("key").values("aws:cloudformation:stack-id").build()
    val describeTagsRequest = DescribeTagsRequest
      .builder()
      .filters(resourceTypeFilter, resourceIdFilter, stackIdFilter)
      .build()
    val tags = ec2Client.describeTags(describeTagsRequest).tags().asScala
    tags
      .find(_.key() == "aws:cloudformation:stack-id")
      .getOrElse(sys.error("aws:cloudformation:stack-id tag is compulsory"))
      .value()
  }

  @Provides
  @Named("s3Bucket")
  @Singleton
  def s3Bucket(cfnClient: CloudFormationClient,
               @Named("cfnStackName") cfnStackName: String): String = {
    val describeStackRequest = DescribeStackResourceRequest
      .builder()
      .stackName(cfnStackName)
      .logicalResourceId("S3Bucket")
      .build()
    cfnClient
      .describeStackResource(describeStackRequest)
      .stackResourceDetail()
      .physicalResourceId()
  }
  @Provides
  @Named("sundialUrl")
  @Singleton
  def sundialUrl(cfnClient: CloudFormationClient,
                 @Named("cfnStackName") cfnStackName: String) = {
    import scala.collection.JavaConverters._
    val describeStackRequest =
      DescribeStacksRequest.builder().stackName(cfnStackName).build()
    val stack =
      cfnClient.describeStacks(describeStackRequest).stacks().get(0)
    stack
      .outputs()
      .asScala
      .find(_.outputKey() == "WebAddress")
      .get
      .outputValue()
  }

} 
Example 31
Source File: DevelopmentConfig.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Named

import com.google.inject.{AbstractModule, Provides, Singleton}
import play.api.{Configuration, Environment}

class DevelopmentConfig(environment: Environment, configuration: Configuration)
    extends AbstractModule {

  override def configure() = {}

  @Provides
  @Named("cfnStackName")
  @Singleton
  def cfnStackName: String = "dumm-stack-name"

  @Provides
  @Named("s3Bucket")
  @Singleton
  def s3Bucket: String = configuration.get[String]("s3.bucket")

  @Provides
  @Named("sdbDomain")
  @Singleton
  def sdbDomain: String = "dummy-sdb-domain"

  @Provides
  @Named("sundialUrl")
  @Singleton
  def sundialUrl: String = "http://localhost:9000"

} 
Example 32
Source File: Config.scala    From sundial   with MIT License 5 votes vote down vote up
package config

import javax.inject.Inject
import com.google.inject.{AbstractModule, Provides, Singleton}
import dao.SundialDaoFactory
import dto.DisplayModels
import org.lyranthe.prometheus.client.{DefaultRegistry, Registry, jmx}
import play.api.libs.ws.WSClient
import play.api.{Configuration, Environment, Logging}
import service._
import service.notifications.{
  DevelopmentEmailNotifications,
  EmailNotifications,
  Notification,
  PagerdutyNotifications
}
import software.amazon.awssdk.services.batch.BatchClient
import software.amazon.awssdk.services.cloudformation.CloudFormationClient
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient
import software.amazon.awssdk.services.ec2.Ec2Client
import software.amazon.awssdk.services.emr.EmrClient
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.ses.SesClient

@Singleton
class PrometheusJmxInstrumentation @Inject()(implicit val registry: Registry) {
  jmx.register
}

class Config(environment: Environment, configuration: Configuration)
    extends AbstractModule
    with Logging {

  override def configure(): Unit = {

    logger.info(s" *** Starting Sundial *** ")

    logger.info("Env Variables:")
    sys.env.foreach {
      case (key, value) => logger.info(s"Key($key), Value($value)")
    }

    logger.info("Sundial Configuration:")
    configuration.entrySet.foreach { entry =>
      logger.info(s"Key(${entry._1}), Value[${entry._2.toString}]")
    }

    bind(classOf[Registry]).toInstance(DefaultRegistry())

    // AWS Clients
    bind(classOf[BatchClient]).toInstance(BatchClient.create())
    bind(classOf[S3Client]).toInstance(S3Client.create())
    bind(classOf[CloudWatchLogsClient])
      .toInstance(CloudWatchLogsClient.create())
    bind(classOf[Ec2Client]).toInstance(Ec2Client.create())
    bind(classOf[EmrClient]).toInstance(EmrClient.create())
    bind(classOf[CloudFormationClient])
      .toInstance(CloudFormationClient.create())
    bind(classOf[SesClient])
      .toInstance(SesClient.create())

    bind(classOf[PrometheusJmxInstrumentation]).asEagerSingleton()

    bind(classOf[Sundial]).asEagerSingleton()

  }

  @Provides
  @Singleton
  def notifications(wsClient: WSClient,
                    daoFactory: SundialDaoFactory,
                    displayModels: DisplayModels,
                    sesClient: SesClient): Seq[Notification] = {
    configuration.getOptional[String]("notifications.mode") match {
      case Some("browser") =>
        Seq(
          new DevelopmentEmailNotifications(daoFactory,
                                            displayModels,
                                            sesClient))
      case Some("email") =>
        Seq(
          new EmailNotifications(
            daoFactory,
            configuration.get[String]("notifications.from"),
            displayModels,
            sesClient))
      case Some("all") =>
        Seq(
          new EmailNotifications(
            daoFactory,
            configuration.get[String]("notifications.from"),
            displayModels,
            sesClient),
          new PagerdutyNotifications(wsClient, daoFactory)
        )
      case _ => Seq.empty
    }
  }

} 
Example 33
Source File: GraphReaderModule.scala    From seahorse-workflow-executor   with Apache License 2.0 5 votes vote down vote up
package io.deepsense.models.json.workflow

import com.google.inject.{AbstractModule, Provides, Singleton}

import io.deepsense.deeplang.catalogs.doperations.DOperationsCatalog
import io.deepsense.models.json.graph.GraphJsonProtocol.GraphReader

class GraphReaderModule extends AbstractModule {
  override def configure(): Unit = {
    // Done by 'provides' methods.
  }

  @Singleton
  @Provides
  def provideGraphReader(dOperationsCatalog: DOperationsCatalog): GraphReader = {
    new GraphReader(dOperationsCatalog)
  }
} 
Example 34
Source File: CassandraPersistenceGuiceModule.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.cassandra

import com.google.inject.matcher.AbstractMatcher
import com.google.inject.spi.InjectionListener
import com.google.inject.spi.TypeEncounter
import com.google.inject.spi.TypeListener
import com.google.inject.AbstractModule
import com.google.inject.TypeLiteral


class CassandraPersistenceGuiceModule extends AbstractModule {
  override def configure(): Unit = {
    initServiceLocatorHolder()
  }

  private def initServiceLocatorHolder(): Unit = {
    val listener: TypeListener = new TypeListener {
      override def hear[I](typeLiteral: TypeLiteral[I], typeEncounter: TypeEncounter[I]): Unit = {
        typeEncounter.register(new InjectionListener[I] {
          override def afterInjection(i: I): Unit = {
            i.asInstanceOf[CassandraPersistenceModule.InitServiceLocatorHolder].init()
          }
        })
      }
    }
    val matcher = new AbstractMatcher[TypeLiteral[_]] {
      override def matches(typeLiteral: TypeLiteral[_]): Boolean = {
        classOf[CassandraPersistenceModule.InitServiceLocatorHolder] == typeLiteral.getRawType
      }
    }
    binder.bindListener(matcher, listener)
  }
} 
Example 35
Source File: JinjavaModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.templates.jinjava

import javax.inject.Singleton

import com.google.inject.{AbstractModule, Provides}
import com.hubspot.jinjava.JinjavaConfig
import de.frosner.broccoli.BroccoliConfiguration
import net.codingwell.scalaguice.ScalaModule


class JinjavaModule extends AbstractModule with ScalaModule {
  override def configure(): Unit = {}
  @Provides
  @Singleton
  def provideJinjavaConfig(broccoliConfiguration: BroccoliConfiguration): JinjavaConfig = {
    val config = broccoliConfiguration.templates.jinjava
    JinjavaConfig
      .newBuilder()
      .withMaxRenderDepth(config.maxRenderDepth)
      .withTrimBlocks(config.trimBlocks)
      .withLstripBlocks(config.lstripBlocks)
      .withEnableRecursiveMacroCalls(config.enableRecursiveMacroCalls)
      .withReadOnlyResolver(config.readOnlyResolver)
      .withMaxOutputSize(config.maxOutputSize)
      .withNestedInterpretationEnabled(config.nestedInterpretationEnabled)
      .withFailOnUnknownTokens(config.failOnUnknownTokens)
      .build()
  }
} 
Example 36
Source File: TemplateModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.templates

import javax.inject.Singleton

import com.google.inject.{AbstractModule, Provides}
import de.frosner.broccoli.BroccoliConfiguration
import de.frosner.broccoli.signal.UnixSignalManager
import net.codingwell.scalaguice.ScalaModule


  @Provides
  @Singleton
  def provideTemplateSource(config: BroccoliConfiguration,
                            signalManager: UnixSignalManager,
                            templateRenderer: TemplateRenderer): TemplateSource =
    new SignalRefreshedTemplateSource(
      new CachedTemplateSource(new DirectoryTemplateSource(config.templates.path, templateRenderer)),
      signalManager
    )
} 
Example 37
Source File: Module.scala    From sbt-header   with Apache License 2.0 5 votes vote down vote up
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ApplicationTimer, AtomicCounter, Counter}


class Module extends AbstractModule {

  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])
  }

} 
Example 38
Source File: AsyncAnalysisActorInitialiser.scala    From tap   with Apache License 2.0 5 votes vote down vote up
package modules

import com.google.inject.AbstractModule
import com.typesafe.scalalogging.Logger
import io.heta.tap.analysis.batch.BatchActor
import io.heta.tap.analysis.clu.CluAnnotatorActor
import play.api.libs.concurrent.AkkaGuiceSupport

class AsyncAnalysisActorInitialiser extends AbstractModule with AkkaGuiceSupport {

  val logger: Logger = Logger(this.getClass)

    override def configure():Unit = {
      logger.info("Binding BatchActor")
      bindActor[BatchActor]("batch")
      logger.info("Binding CluAnnotatorActor")
      bindActor[CluAnnotatorActor]("cluAnnotator")
      //bindActor[AffectLexiconActor]("affectlexicon")
      //bindActor[WordVectorActor]("wordvector")
    }

} 
Example 39
Source File: BaseModule.scala    From silhouette-vuejs-app   with Apache License 2.0 5 votes vote down vote up
package modules

import com.google.inject.{AbstractModule, Provides}
import javax.inject.Named
import models.daos.{LoginInfoDAO, LoginInfoDAOImpl}
import models.services.captcha.{CaptchaService, ReCaptchaConfig, ReCaptchaService}
import models.services.{AuthTokenService, AuthTokenServiceImpl, BruteForceDefenderActor, BruteForceDefenderConf}
import net.codingwell.scalaguice.ScalaModule
import play.api.Configuration
import play.api.libs.concurrent.AkkaGuiceSupport

import scala.concurrent.duration._
import scala.concurrent.duration.FiniteDuration


  override def configure(): Unit = {
    bind[AuthTokenService].to[AuthTokenServiceImpl]
    bind[LoginInfoDAO].to[LoginInfoDAOImpl]
    bind[CaptchaService].to[ReCaptchaService]
    bindActor[BruteForceDefenderActor]("brute-force-defender")
  }

  @Named("SendGridApiKey")
  @Provides
  def providesSendGridApiKey(conf: Configuration): String = {
    conf.get[String]("sendgrid.api.key")
  }

  @Provides
  def providesReCaptchaConfig(conf: Configuration): ReCaptchaConfig = {
    ReCaptchaConfig(conf.get[String]("recaptcha.secretKey"))
  }

  @Provides
  def providesBruteForceDefenderConf(conf: Configuration): BruteForceDefenderConf = {
    val attempts = conf.getOptional[Int]("signin.limit.attempts").getOrElse(5)
    val period = conf.getOptional[FiniteDuration]("signin.limit.period").getOrElse(30.minutes)
    BruteForceDefenderConf(attempts, period)
  }
} 
Example 40
Source File: CouchbasePersistenceGuiceModule.scala    From akka-persistence-couchbase   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.persistence.couchbase

import com.google.inject.matcher.AbstractMatcher
import com.google.inject.spi.{InjectionListener, TypeEncounter, TypeListener}
import com.google.inject.{AbstractModule, TypeLiteral}


class CouchbasePersistenceGuiceModule extends AbstractModule {
  override def configure(): Unit =
    initServiceLocatorHolder()

  private def initServiceLocatorHolder(): Unit = {
    val listener: TypeListener = new TypeListener {
      override def hear[I](typeLiteral: TypeLiteral[I], typeEncounter: TypeEncounter[I]): Unit =
        typeEncounter.register(new InjectionListener[I] {
          override def afterInjection(i: I): Unit =
            i.asInstanceOf[CouchbasePersistenceModule.InitServiceLocatorHolder].init()
        })
    }
    val matcher = new AbstractMatcher[TypeLiteral[_]] {
      override def matches(typeLiteral: TypeLiteral[_]): Boolean =
        classOf[CouchbasePersistenceModule.InitServiceLocatorHolder] == typeLiteral.getRawType
    }
    binder.bindListener(matcher, listener)
  }
} 
Example 41
Source File: Module.scala    From play-webpack-typescript-react   with MIT License 5 votes vote down vote up
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ApplicationTimer, AtomicCounter, Counter}


@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements"))
class Module extends AbstractModule {

  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])

    ()
  }

} 
Example 42
Source File: ServiceTestSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.javadsl.testkit

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

import javax.inject.Inject
import akka.japi.function.Procedure
import com.google.inject.AbstractModule
import com.lightbend.lagom.javadsl.api.Descriptor
import com.lightbend.lagom.javadsl.api.Service
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry
import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport
import com.lightbend.lagom.javadsl.testkit.ServiceTest.Setup
import com.lightbend.lagom.javadsl.testkit.ServiceTest.TestServer
import play.inject.guice.GuiceApplicationBuilder

import scala.collection.JavaConverters._
import scala.compat.java8.FunctionConverters._
import scala.util.Properties
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class ServiceTestSpec extends AnyWordSpec with Matchers {
  "ServiceTest" when {
    "started with Cassandra" should {
      "create a temporary directory" in {
        val temporaryFileCountBeforeRun = listTemporaryFiles().size

        withServer(ServiceTest.defaultSetup.withCassandra()) { _ =>
          val temporaryFilesDuringRun = listTemporaryFiles()

          temporaryFilesDuringRun should have size (temporaryFileCountBeforeRun + 1)
        }
      }
    }

    "stopped after starting" should {
      "remove its temporary directory" in {
        val temporaryFileCountBeforeRun = listTemporaryFiles().size

        withServer(ServiceTest.defaultSetup.withCassandra()) { _ =>
          ()
        }

        val temporaryFilesAfterRun = listTemporaryFiles()

        temporaryFilesAfterRun should have size temporaryFileCountBeforeRun
      }
    }

    "started with JDBC" should {
      "start successfully" in {
        withServer(ServiceTest.defaultSetup.withJdbc()) { _ =>
          ()
        }
      }
    }
  }

  def withServer(setup: Setup)(block: TestServer => Unit): Unit = {
    ServiceTest.withServer(setup.configureBuilder((registerService _).asJava), block(_))
  }

  def registerService(builder: GuiceApplicationBuilder): GuiceApplicationBuilder =
    builder.bindings(new TestServiceModule)

  def listTemporaryFiles(): Iterator[Path] = {
    val tmpDir = Paths.get(Properties.tmpDir)
    Files
      .newDirectoryStream(tmpDir, "ServiceTest_*")
      .iterator()
      .asScala
  }
}

trait TestService extends Service {
  import Service._

  final override def descriptor: Descriptor = named("test")
}

class TestServiceImpl @Inject() (persistentEntityRegistry: PersistentEntityRegistry) extends TestService

class TestServiceModule extends AbstractModule with ServiceGuiceSupport {
  override def configure(): Unit = bindService(classOf[TestService], classOf[TestServiceImpl])
} 
Example 43
Source File: AuthModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.auth

import com.google.inject.{AbstractModule, Provides, Singleton}
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services.IdentityService
import com.mohiva.play.silhouette.api.util.{Credentials, PasswordHasherRegistry, PasswordInfo}
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import com.mohiva.play.silhouette.password.BCryptPasswordHasher
import com.mohiva.play.silhouette.persistence.daos.InMemoryAuthInfoDAO
import com.mohiva.play.silhouette.persistence.repositories.DelegableAuthInfoRepository
import de.frosner.broccoli.BroccoliConfiguration
import net.codingwell.scalaguice.ScalaModule

import scala.concurrent.{ExecutionContext, Future}


  @Provides
  @Singleton
  def providesAuthInfoRepository(
      config: AuthConfiguration,
      passwordHasherRegistry: PasswordHasherRegistry
  )(implicit ec: ExecutionContext): AuthInfoRepository =
    new DelegableAuthInfoRepository(config.mode match {
      case AuthMode.Conf =>
        // Create an in-memory DAO and add all accounts from configuration to it
        val dao = new InMemoryAuthInfoDAO[PasswordInfo]()
        config.conf.accounts.foreach { account =>
          dao.add(LoginInfo(CredentialsProvider.ID, account.username),
                  passwordHasherRegistry.current.hash(account.password))
        }
        dao
      case _ =>
        // Use an empty DAO
        new InMemoryAuthInfoDAO[PasswordInfo]()
    })
} 
Example 44
Source File: Module.scala    From akka-http-test   with Apache License 2.0 5 votes vote down vote up
import javax.inject.Inject

import akka.actor.ActorSystem
import akka.pattern.CircuitBreaker
import akka.stream.Materializer
import com.github.dnvriend.component.repository.PersonRepository
import com.github.dnvriend.component.simpleserver.SimpleServer
import com.google.inject.{ AbstractModule, Provider, Provides }
import play.api.Configuration
import play.api.libs.concurrent.AkkaGuiceSupport

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

class Module extends AbstractModule with AkkaGuiceSupport {
  override def configure(): Unit = {
    bind(classOf[SimpleServer])
      .toProvider(classOf[SimpleServerProvider])
      .asEagerSingleton()
  }

  @Provides
  def circuitBreakerProvider(system: ActorSystem)(implicit ec: ExecutionContext): CircuitBreaker = {
    val maxFailures: Int = 3
    val callTimeout: FiniteDuration = 1.seconds
    val resetTimeout: FiniteDuration = 10.seconds
    new CircuitBreaker(system.scheduler, maxFailures, callTimeout, resetTimeout)
  }
}

// alternative way to provide services
class SimpleServerProvider @Inject() (personRepository: PersonRepository, cb: CircuitBreaker, config: Configuration)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext) extends Provider[SimpleServer] {
  override def get(): SimpleServer =
    new SimpleServer(personRepository, cb, config.getString("http.interface").getOrElse("0.0.0.0"), config.getInt("http.port").getOrElse(8080))
} 
Example 45
Source File: ActorsModule.scala    From dependency   with MIT License 5 votes vote down vote up
package io.flow.dependency.actors

import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport

class ActorsModule extends AbstractModule with AkkaGuiceSupport {
  override def configure(): Unit = {
    bindActor[BinaryActor]("binary-actor")
    bindActor[EmailActor]("email-actor")
    bindActor[LibraryActor]("library-actor")
    bindActor[PeriodicActor]("periodic-actor")
    bindActor[ProjectActor]("project-actor")
    bindActor[ResolverActor]("resolver-actor")
    bindActor[SearchActor]("search-actor")
    bindActor[UserActor]("user-actor")

    bindActor[TaskActor]("task-actor")
    bindActor[TaskActorUpserted]("task-actor-upserted")
    bindActor[TaskActorSyncAll]("task-actor-sync-all")
    bindActor[TaskActorSyncOneBinary]("task-actor-sync-one-binary")
    bindActor[TaskActorSyncOneLibrary]("task-actor-sync-one-library")
    bindActor[TaskActorSyncOrganizationLibraries]("task-actor-sync-organization-libraries")
    bindActor[TaskActorSyncLibrariesByPrefix](name = "task-actor-sync-libraries-by-prefix")
    bindActor[TaskActorSyncOneProject]("task-actor-sync-one-project")
  }
} 
Example 46
Source File: Module.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ApplicationTimer, AtomicCounter, Counter}


class Module extends AbstractModule {
  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])
  }

} 
Example 47
Source File: Module.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ApplicationTimer, AtomicCounter, Counter}


class Module extends AbstractModule {
  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])
  }

} 
Example 48
Source File: Module.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex

import java.lang.reflect.Modifier

import com.google.inject.AbstractModule
import net.codingwell.scalaguice.{ScalaModule, ScalaMultibinder}
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{Configuration, Environment, Logger, Mode}
import scala.collection.JavaConverters._

import com.google.inject.name.Names
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner
import org.reflections.util.ConfigurationBuilder
import org.thp.cortex.models.{AuditedModel, Migration}
import org.thp.cortex.services._

import org.elastic4play.models.BaseModelDef
import org.elastic4play.services.auth.MultiAuthSrv
import org.elastic4play.services.{UserSrv ⇒ EUserSrv, AuthSrv, MigrationOperations}
import org.thp.cortex.controllers.{AssetCtrl, AssetCtrlDev, AssetCtrlProd}
import services.mappers.{MultiUserMapperSrv, UserMapper}

class Module(environment: Environment, configuration: Configuration) extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  private lazy val logger = Logger(s"module")

  override def configure(): Unit = {
    val modelBindings        = ScalaMultibinder.newSetBinder[BaseModelDef](binder)
    val auditedModelBindings = ScalaMultibinder.newSetBinder[AuditedModel](binder)
    val reflectionClasses = new Reflections(
      new ConfigurationBuilder()
        .forPackages("org.elastic4play")
        .addClassLoader(getClass.getClassLoader)
        .addClassLoader(environment.getClass.getClassLoader)
        .forPackages("org.thp.cortex")
        .setExpandSuperTypes(false)
        .setScanners(new SubTypesScanner(false))
    )

    reflectionClasses
      .getSubTypesOf(classOf[BaseModelDef])
      .asScala
      .filterNot(c ⇒ Modifier.isAbstract(c.getModifiers))
      .foreach { modelClass ⇒
        logger.info(s"Loading model $modelClass")
        modelBindings.addBinding.to(modelClass)
        if (classOf[AuditedModel].isAssignableFrom(modelClass)) {
          auditedModelBindings.addBinding.to(modelClass.asInstanceOf[Class[AuditedModel]])
        }
      }

    val authBindings = ScalaMultibinder.newSetBinder[AuthSrv](binder)
    reflectionClasses
      .getSubTypesOf(classOf[AuthSrv])
      .asScala
      .filterNot(c ⇒ Modifier.isAbstract(c.getModifiers) || c.isMemberClass)
      .filterNot(c ⇒ c == classOf[MultiAuthSrv] || c == classOf[CortexAuthSrv])
      .foreach { authSrvClass ⇒
        logger.info(s"Loading authentication module $authSrvClass")
        authBindings.addBinding.to(authSrvClass)
      }

    val ssoMapperBindings = ScalaMultibinder.newSetBinder[UserMapper](binder)
    reflectionClasses
      .getSubTypesOf(classOf[UserMapper])
      .asScala
      .filterNot(c ⇒ Modifier.isAbstract(c.getModifiers) || c.isMemberClass)
      .filterNot(c ⇒ c == classOf[MultiUserMapperSrv])
      .foreach(mapperCls ⇒ ssoMapperBindings.addBinding.to(mapperCls))

    if (environment.mode == Mode.Prod)
      bind[AssetCtrl].to[AssetCtrlProd]
    else
      bind[AssetCtrl].to[AssetCtrlDev]

    bind[EUserSrv].to[UserSrv]
    bind[Int].annotatedWith(Names.named("databaseVersion")).toInstance(models.modelVersion)
    bind[UserMapper].to[MultiUserMapperSrv]

    bind[AuthSrv].to[CortexAuthSrv]
    bind[MigrationOperations].to[Migration]
    bindActor[AuditActor]("audit")
  }
} 
Example 49
Source File: Global.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
import play._

import javax.inject.Inject
import com.google.inject.{ AbstractModule, Singleton }
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
import modules._

@Singleton
class Global @Inject() (lifecycle: ApplicationLifecycle) {

  @Inject
  def onStart() {
    Logger.info("#### Application START")
  }

  // REVIEW here
  lifecycle.addStopHook { () =>
    Future.successful({
      Logger.info("#### Application STOP")
    })
  }

  // TODO: plug a servicefactory for repository

}

@Singleton
class StartModule extends AbstractModule {

  def configure() = {
    bind(classOf[KBModule]).to(classOf[KBModuleBase]).asEagerSingleton()
  }

} 
Example 50
Source File: Global.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
import play._

import javax.inject.Inject
import com.google.inject.{ AbstractModule, Singleton }
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
import modules.ClientsModule
import modules.ClientsModuleBase

@Singleton
class Global @Inject() (lifecycle: ApplicationLifecycle) {

  @Inject
  def onStart() {
    Logger.info("#### Application START")
  }

  // REVIEW here
  lifecycle.addStopHook { () =>
    Future.successful({
      Logger.info("#### Application STOP")
    })
  }

  // TODO: plug a servicefactory for repository

}

@Singleton
class StartModule extends AbstractModule {

  def configure() = {

    bind(classOf[ClientsModule]).to(classOf[ClientsModuleBase]).asEagerSingleton()
  }

} 
Example 51
Source File: Module.scala    From phantom-activator-template   with Apache License 2.0 5 votes vote down vote up
import javax.inject.{Inject, Provider, Singleton}

import com.google.inject.AbstractModule
import com.outworkers.phantom.connectors.{CassandraConnection, ContactPoint}
import models.AppDatabase
import net.codingwell.scalaguice.ScalaModule

class Module extends AbstractModule  with ScalaModule {
  override def configure(): Unit = {
    bind[CassandraConnection].toProvider[ConnectionProvider]
    bind[AppDatabase].asEagerSingleton()
  }
}

@Singleton
class ConnectionProvider @Inject()(env: play.api.Environment) extends Provider[CassandraConnection] {
  lazy val get: CassandraConnection = {
    val builder = env.mode match {
      case play.api.Mode.Test => ContactPoint.embedded
      case _ => ContactPoint.local
    }
    builder.keySpace("outworkers")
  }
} 
Example 52
Source File: CouchDBStorageModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.instances.storage.couchdb

import com.google.inject.{AbstractModule, Provides, Singleton}
import de.frosner.broccoli.BroccoliConfiguration
import de.frosner.broccoli.instances.storage.InstanceStorage
import net.codingwell.scalaguice.ScalaModule
import play.api.inject.ApplicationLifecycle
import play.api.libs.ws.WSClient

import scala.concurrent.Future


  @Provides
  @Singleton
  def provideCouchDBInstanceStorage(
      config: BroccoliConfiguration,
      client: WSClient,
      applicationLifecycle: ApplicationLifecycle
  ): InstanceStorage = {
    val couchdbConfig = config.instances.storage.couchdb
    val storage = new CouchDBInstanceStorage(couchdbConfig.url, couchdbConfig.database, client)
    applicationLifecycle.addStopHook(() => {
      if (!storage.isClosed) {
        storage.close()
      }
      Future.successful({})
    })
    storage
  }
} 
Example 53
Source File: FileSystemStorageModule.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.instances.storage.filesystem

import com.google.inject.{AbstractModule, Provides, Singleton}
import de.frosner.broccoli.BroccoliConfiguration
import de.frosner.broccoli.instances.storage.InstanceStorage
import net.codingwell.scalaguice.ScalaModule
import play.api.inject.ApplicationLifecycle

import scala.concurrent.Future


  @Provides
  @Singleton
  def provideFileSystemInstanceStorage(
      config: BroccoliConfiguration,
      applicationLifecycle: ApplicationLifecycle
  ): InstanceStorage = {
    val storage = new FileSystemInstanceStorage(config.instances.storage.fs.path.toAbsolutePath.toFile)
    applicationLifecycle.addStopHook(() => {
      if (!storage.isClosed) {
        storage.close()
      }
      Future.successful({})
    })
    storage
  }
} 
Example 54
Source File: ParserModule.scala    From apalache   with Apache License 2.0 5 votes vote down vote up
package at.forsyte.apalache.tla.imp.passes

import at.forsyte.apalache.infra.{DefaultExceptionAdapter, ExceptionAdapter}
import at.forsyte.apalache.infra.passes.{Pass, PassOptions, TerminalPassWithTlaModule, WriteablePassOptions}
import com.google.inject.AbstractModule
import com.google.inject.name.Names


class ParserModule extends AbstractModule {
  override def configure(): Unit = {
    // the options singleton
    bind(classOf[PassOptions])
      .to(classOf[WriteablePassOptions])
    // exception handler
    bind(classOf[ExceptionAdapter])
      .to(classOf[DefaultExceptionAdapter])

    // SanyParserPassImpl is the default implementation of SanyParserPass
    bind(classOf[SanyParserPass])
      .to(classOf[SanyParserPassImpl])
    // and it also the initial pass for PassChainExecutor
    bind(classOf[Pass])
      .annotatedWith(Names.named("InitialPass"))
      .to(classOf[SanyParserPass])
    // the next pass after SanyParserPass is the terminal pass
    bind(classOf[Pass])
      .annotatedWith(Names.named("AfterParser"))
      .to(classOf[TerminalPassWithTlaModule])
  }
} 
Example 55
Source File: KubeServiceRegistryModule.scala    From lagom-on-kube   with Apache License 2.0 5 votes vote down vote up
package me.alexray.lagom.kube.discovery.impl

import java.util.{Map => JMap}

import com.google.inject.AbstractModule
import com.lightbend.lagom.discovery.impl.ServiceRegistryImpl
import com.lightbend.lagom.discovery.UnmanagedServices
import com.lightbend.lagom.gateway.ServiceGatewayConfig
import com.lightbend.lagom.internal.javadsl.registry.{NoServiceLocator, ServiceRegistry}
import com.lightbend.lagom.javadsl.api.ServiceLocator
import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport
import me.alexray.lagom.kube.discovery.KubeServiceRegistryActor
import me.alexray.lagom.kube.gateway.KubeServiceGatewayConfig
import play.libs.akka.AkkaGuiceSupport


object KubeServiceRegistryModule {
  final val KUBE_SERVICE_REGISTRY_ACTOR = "kubeServiceRegistryActor"
}

case class KubeServiceRegistryModule(serviceGatewayConfig: KubeServiceGatewayConfig,
                                     unmanagedServices: JMap[String, String])
  extends AbstractModule with ServiceGuiceSupport with AkkaGuiceSupport
{

  println("created kubeServiceRegistryActor")

  import KubeServiceRegistryModule._

  override protected def configure(): Unit = {
    bindService(classOf[ServiceRegistry], classOf[KubeServiceRegistryImpl])
    bindActor(classOf[KubeServiceRegistryActor], KUBE_SERVICE_REGISTRY_ACTOR)
    bind(classOf[KubeServiceGatewayConfig]).toInstance(serviceGatewayConfig)
    bind(classOf[UnmanagedServices]).toInstance(UnmanagedServices.apply(unmanagedServices))
    bind(classOf[ServiceLocator]).to(classOf[NoServiceLocator])
  }
} 
Example 56
Source File: HatTestServerProviderModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import akka.actor.ActorSystem
import com.google.inject.{ AbstractModule, Provides }
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.api.service.applications.{ TrustedApplicationProvider, TrustedApplicationProviderDex }
import org.hatdex.hat.resourceManagement._
import org.hatdex.hat.resourceManagement.actors.{ HatServerActor, HatServerProviderActor }
import play.api.cache.AsyncCacheApi
import play.api.cache.ehcache.EhCacheComponents
import play.api.inject.ApplicationLifecycle
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{ Configuration, Environment }

class HatTestServerProviderModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  override def configure() = {
    bindActor[HatServerProviderActor]("hatServerProviderActor")
    bindActorFactory[HatServerActor, HatServerActor.Factory]

    bind[HatDatabaseProvider].to[HatDatabaseProviderConfig]
    bind[HatKeyProvider].to[HatKeyProviderConfig]
    bind[HatServerProvider].to[HatServerProviderImpl]

    bind[TrustedApplicationProvider].to[TrustedApplicationProviderDex]
    ()
  }

  @Provides @play.cache.NamedCache("hatserver-cache")
  def provideHatServerCache(env: Environment, config: Configuration, lifecycle: ApplicationLifecycle, system: ActorSystem)(implicit ec: RemoteExecutionContext): AsyncCacheApi = {
    val cacheComponents = new EhCacheComponents {
      def environment: Environment = env
      def configuration: Configuration = config.get[Configuration]("hat.serverProvider")
      def applicationLifecycle: ApplicationLifecycle = lifecycle
      def actorSystem: ActorSystem = system
      implicit def executionContext = ec
    }
    cacheComponents.cacheApi("hatserver-cache", create = true)
  }

} 
Example 57
Source File: SHEModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import com.google.inject.{ AbstractModule, Provides }
import com.typesafe.config.Config
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.models.applications.Version
import org.hatdex.hat.she.models.LambdaFunctionLoader
import org.hatdex.hat.she.service.{ FunctionExecutableRegistry, FunctionExecutionTriggerHandler }
import org.hatdex.hat.utils.FutureTransformations
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{ ConfigLoader, Configuration, Logger }

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import scala.concurrent.{ Await, ExecutionContext, Future }

class SHEModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {
  val logger = Logger(this.getClass)

  override def configure() = {
    bind[FunctionExecutionTriggerHandler].asEagerSingleton()
    ()
  }

  implicit val seqFunctionConfigLoader: ConfigLoader[Seq[FunctionConfig]] = new ConfigLoader[Seq[FunctionConfig]] {
    def load(config: Config, path: String): Seq[FunctionConfig] = {
      val configs = config.getConfigList(path).asScala
      logger.info(s"Got SHE function configs: $configs")
      configs.map { config ⇒
        FunctionConfig(
          config.getString("id"),
          Version(config.getString("version")),
          config.getString("baseUrl"),
          config.getString("namespace"),
          config.getString("endpoint"),
          config.getBoolean("experimental"))
      }
    }
  }

  @Provides
  def provideFunctionExecutableRegistry(
    config: Configuration,
    loader: LambdaFunctionLoader)(implicit ec: ExecutionContext): FunctionExecutableRegistry = {

    val includeExperimental: Boolean = config.getOptional[Boolean]("she.beta").getOrElse(false)

    val eventuallyFunctionsLoaded = Future.sequence(
      config.get[Seq[FunctionConfig]]("she.functions")
        .filter(c => !c.experimental || (includeExperimental && c.experimental))
        .map(c ⇒ FutureTransformations.futureToFutureTry(loader.load(c.id, c.version, c.baseUrl, c.namespace, c.endpoint))))

    val functionsLoaded = Await.result(eventuallyFunctionsLoaded, 30.seconds)

    // ignore any functions that failed to load without stopping the whole application
    new FunctionExecutableRegistry(functionsLoaded.filter(_.isSuccess).flatMap(_.toOption))
  }

  case class FunctionConfig(id: String, version: Version, baseUrl: String, namespace: String, endpoint: String, experimental: Boolean)
} 
Example 58
Source File: HatServerProviderModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import akka.actor.ActorSystem
import com.google.inject.{ AbstractModule, Provides }
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.api.service.applications.{ TrustedApplicationProvider, TrustedApplicationProviderDex }
import org.hatdex.hat.resourceManagement._
import org.hatdex.hat.resourceManagement.actors.{ HatServerActor, HatServerProviderActor }
import play.api.cache.AsyncCacheApi
import play.api.cache.ehcache._
import play.api.inject.ApplicationLifecycle
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{ Configuration, Environment }

class HatServerProviderModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  override def configure() = {
    bindActor[HatServerProviderActor]("hatServerProviderActor")
    bindActorFactory[HatServerActor, HatServerActor.Factory]

    bind[HatDatabaseProvider].to[HatDatabaseProviderMilliner]
    bind[HatKeyProvider].to[HatKeyProviderMilliner]
    bind[HatServerProvider].to[HatServerProviderImpl]

    bind[TrustedApplicationProvider].to[TrustedApplicationProviderDex]
    ()
  }

  @Provides @play.cache.NamedCache("hatserver-cache")
  def provideHatServerCache(env: Environment, config: Configuration, lifecycle: ApplicationLifecycle, system: ActorSystem)(implicit ec: RemoteExecutionContext): AsyncCacheApi = {
    val cacheComponents = new EhCacheComponents {
      def environment: Environment = env
      def configuration: Configuration = config.get[Configuration]("hat.serverProvider")
      def applicationLifecycle: ApplicationLifecycle = lifecycle
      def actorSystem: ActorSystem = system
      implicit def executionContext = ec
    }
    cacheComponents.cacheApi("hatserver-cache", create = true)
  }

} 
Example 59
Source File: FileManagerModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import com.amazonaws.auth.{ AWSStaticCredentialsProvider, BasicAWSCredentials }
import com.amazonaws.services.s3.{ AmazonS3, AmazonS3ClientBuilder }
import com.google.inject.name.Named
import com.google.inject.{ AbstractModule, Provides }
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.service.{ AwsS3Configuration, FileManager, FileManagerS3 }
import play.api.Configuration
import play.api.libs.concurrent.AkkaGuiceSupport

class FileManagerModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  override def configure() = {
    bind[FileManager].to[FileManagerS3]
    ()
  }

  @Provides
  def provideCookieAuthenticatorService(configuration: Configuration): AwsS3Configuration = {
    import AwsS3Configuration.configLoader
    configuration.get[AwsS3Configuration]("storage.s3Configuration")
  }

  @Provides @Named("s3client-file-manager")
  def provides3Client(configuration: AwsS3Configuration): AmazonS3 = {
    val awsCreds: BasicAWSCredentials = new BasicAWSCredentials(configuration.accessKeyId, configuration.secretKey)
    AmazonS3ClientBuilder.standard()
      .withRegion(configuration.region)
      .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
      .build()
  }

} 
Example 60
Source File: HatDataStatsProcessorSpec.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.service.monitoring

import java.util.UUID

import akka.stream.Materializer
import com.google.inject.AbstractModule
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.models.{ EndpointData, Owner }
import org.hatdex.hat.api.service.applications.{ TestApplicationProvider, TrustedApplicationProvider }
import org.hatdex.hat.api.service.monitoring.HatDataEventBus.DataCreatedEvent
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.dal.ModelTranslation
import org.hatdex.hat.resourceManagement.FakeHatConfiguration
import org.joda.time.DateTime
import org.specs2.mock.Mockito
import org.specs2.specification.Scope
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{ JsValue, Json }
import play.api.test.PlaySpecification
import play.api.{ Application, Logger }

class HatDataStatsProcessorSpec extends PlaySpecification with Mockito with HatDataStatsProcessorContext {

  val logger = Logger(this.getClass)

  sequential

  "The `computeInboundStats` method" should {
    "Correctly count numbers of values for simple objects" in {
      val service = application.injector.instanceOf[HatDataStatsProcessor]
      val stats = service.computeInboundStats(simpleDataCreatedEvent)

      import org.hatdex.hat.api.json.DataStatsFormat._
      logger.debug(s"Got back stats: ${Json.prettyPrint(Json.toJson(stats))}")

      stats.logEntry must be equalTo "test item"
      stats.statsType must be equalTo "inbound"
      stats.stats.length must be equalTo 1
      val endpointStats = stats.stats.head
      endpointStats.endpoint must be equalTo "testendpoint"

      endpointStats.propertyStats("field") must equalTo(1)
      endpointStats.propertyStats("date") must equalTo(1)
      endpointStats.propertyStats("date_iso") must equalTo(1)
      endpointStats.propertyStats("anotherField") must equalTo(1)
      endpointStats.propertyStats("object.objectField") must equalTo(1)
      endpointStats.propertyStats("object.objectFieldArray[]") must equalTo(3)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName") must equalTo(2)
      endpointStats.propertyStats("object.objectFieldObjectArray[].subObjectName2") must equalTo(2)
    }
  }

}

trait HatDataStatsProcessorContext extends Scope {
  import scala.concurrent.ExecutionContext.Implicits.global
  // Setup default users for testing
  val owner = HatUser(UUID.randomUUID(), "hatuser", Some("pa55w0rd"), "hatuser", Seq(Owner()), enabled = true)

  class ExtrasModule extends AbstractModule with ScalaModule {
    override def configure(): Unit = {
      bind[TrustedApplicationProvider].toInstance(new TestApplicationProvider(Seq()))
    }
  }

  lazy val application: Application = new GuiceApplicationBuilder()
    .configure(FakeHatConfiguration.config)
    .overrides(new ExtrasModule)
    .build()

  implicit lazy val materializer: Materializer = application.materializer

  val simpleJson: JsValue = Json.parse(
    """
      | {
      |   "field": "value",
      |   "date": 1492699047,
      |   "date_iso": "2017-04-20T14:37:27+00:00",
      |   "anotherField": "anotherFieldValue",
      |   "object": {
      |     "objectField": "objectFieldValue",
      |     "objectFieldArray": ["objectFieldArray1", "objectFieldArray2", "objectFieldArray3"],
      |     "objectFieldObjectArray": [
      |       {"subObjectName": "subObject1", "subObjectName2": "subObject1-2"},
      |       {"subObjectName": "subObject2", "subObjectName2": "subObject2-2"}
      |     ]
      |   }
      | }
    """.stripMargin)

  val simpleDataCreatedEvent = DataCreatedEvent(
    "testhat.hubofallthings.net",
    ModelTranslation.fromInternalModel(owner).clean,
    DateTime.now(), "test item",
    Seq(
      EndpointData("testendpoint", Option(UUID.randomUUID()), None, None, simpleJson, None)))
} 
Example 61
Source File: Module.scala    From Full-Stack-Scala-Starter   with Apache License 2.0 5 votes vote down vote up
import com.google.inject.AbstractModule
import java.time.Clock

import services.{ApplicationTimer, AtomicCounter, Counter}


class Module extends AbstractModule {

  override def configure() = {
    // Use the system clock as the default implementation of Clock
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
    // Ask Guice to create an instance of ApplicationTimer when the
    // application starts.
    bind(classOf[ApplicationTimer]).asEagerSingleton()
    // Set AtomicCounter as the implementation for Counter.
    bind(classOf[Counter]).to(classOf[AtomicCounter])
  }
} 
Example 62
Source File: ApisModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.workflowmanager

import com.google.inject.AbstractModule
import com.google.inject.binder.LinkedBindingBuilder
import com.google.inject.multibindings.Multibinder
import com.google.inject.name.Names.named

import ai.deepsense.commons.auth.AuthModule
import ai.deepsense.commons.rest.{RestComponent, VersionApi}
import ai.deepsense.models.json.workflow.GraphReaderModule
import ai.deepsense.workflowmanager.deeplang.DeepLangModule
import ai.deepsense.workflowmanager.rest._


class ApisModule(withMockedSecurity: Boolean) extends AbstractModule {
  private lazy val apiBinder = Multibinder.newSetBinder(binder(), classOf[RestComponent])

  protected[this] def bindApi: LinkedBindingBuilder[RestComponent] = {
    apiBinder.addBinding()
  }

  override def configure(): Unit = {
    bind(classOf[String]).annotatedWith(named("componentName")).toInstance("workflowmanager")

    install(new AuthModule(withMockedSecurity))
    install(new GraphReaderModule)
    install(new DeepLangModule)

    bindApi.to(classOf[InsecureWorkflowApi])
    bindApi.to(classOf[InsecureOperationsApi])
    bindApi.to(classOf[VersionApi])
  }
} 
Example 63
Source File: WorkflowManagerAppModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.workflowmanager

import com.google.inject.AbstractModule

import ai.deepsense.commons.akka.AkkaModule
import ai.deepsense.commons.config.ConfigModule
import ai.deepsense.commons.jclouds.{KeystoneApiModule, TokenApiModule}
import ai.deepsense.commons.rest.RestModule


class WorkflowManagerAppModule(withMockedSecurity: Boolean) extends AbstractModule {
  override def configure(): Unit = {
    installCore()
    installServices()
    installServer()
  }

  private def installCore(): Unit = {
    install(new ConfigModule)
    install(new AkkaModule)
    install(new KeystoneApiModule)
    install(new TokenApiModule)
  }

  private def installServices(): Unit = {
    install(new ServicesModule)
  }

  private def installServer(): Unit = {
    install(new RestModule)
    install(new ApisModule(withMockedSecurity))
  }
} 
Example 64
Source File: GraphReaderModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.models.json.workflow

import com.google.inject.{AbstractModule, Provides, Singleton}

import ai.deepsense.deeplang.catalogs.doperations.DOperationsCatalog
import ai.deepsense.models.json.graph.GraphJsonProtocol.GraphReader

class GraphReaderModule extends AbstractModule {
  override def configure(): Unit = {
    // Done by 'provides' methods.
  }

  @Singleton
  @Provides
  def provideGraphReader(dOperationsCatalog: DOperationsCatalog): GraphReader = {
    new GraphReader(dOperationsCatalog)
  }
} 
Example 65
Source File: MqModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager.mq

import java.util.concurrent.TimeoutException

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Provides, Singleton}
import com.rabbitmq.client.ConnectionFactory
import com.thenewmotion.akka.rabbitmq.ConnectionActor

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal

import ai.deepsense.commons.utils.Logging
import ai.deepsense.sessionmanager.service.executor.SessionExecutorClients
import ai.deepsense.sparkutils.AkkaUtils
import ai.deepsense.workflowexecutor.communication.mq.MQCommunication
import ai.deepsense.workflowexecutor.communication.mq.json.Global.{GlobalMQDeserializer, GlobalMQSerializer}
import ai.deepsense.workflowexecutor.rabbitmq.MQCommunicationFactory

class MqModule extends AbstractModule with Logging {
  override def configure(): Unit = {}

  @Provides
  @Singleton
  def communicationFactory(
      actorSystem: ActorSystem,
      @Named("MQConnectionActor") connection: ActorRef): MQCommunicationFactory = {
    MQCommunicationFactory(actorSystem, connection, GlobalMQSerializer, GlobalMQDeserializer)
  }

  @Provides
  @Singleton
  @Named("MQConnectionActor")
  def createConnection(
      system: ActorSystem,
      @Named("queue.host") host: String,
      @Named("queue.port") port: Int,
      @Named("queue.user") user: String,
      @Named("queue.pass") pass: String): ActorRef = {
    val factory = new ConnectionFactory()
    factory.setHost(host)
    factory.setPort(port)
    factory.setUsername(user)
    factory.setPassword(pass)
    system.actorOf(
      ConnectionActor.props(factory),
      MQCommunication.mqActorSystemName)
  }

  @Provides
  @Singleton
  def createSessionExecutorClients(
      communicationFactory: MQCommunicationFactory): SessionExecutorClients = {
    new SessionExecutorClients(communicationFactory)
  }

  @Provides
  @Singleton
  @Named("SessionService.HeartbeatSubscribed")
  def heartbeatSubscriber(
      system: ActorSystem,
      communicationFactory: MQCommunicationFactory,
      @Named("SessionService.Actor") sessionServiceActor: ActorRef,
      @Named("queue.heartbeat.subscription.timeout") timeout: Long): Future[Unit] = {
    import ai.deepsense.sessionmanager.mq.MQCommunicationFactoryEnrichments._
    implicit val ec: ExecutionContext = system.dispatcher
    val subscribed = communicationFactory
      .registerBroadcastSubscriber("seahorse_heartbeats_all", sessionServiceActor)

    val subscribedWithTimeout = Future.firstCompletedOf(List(subscribed, Future {
      Thread.sleep(timeout)
      throw new TimeoutException
    }))

    subscribedWithTimeout.onFailure {
      case NonFatal(e) =>
        logger.error(s"Haven't subscribed to Heartbeats after '$timeout' millis." +
          " Shutting down!")
        AkkaUtils.terminate(system)
    }

    subscribedWithTimeout.map(_.data)
  }
} 
Example 66
Source File: SessionManagerAppModule.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.sessionmanager

import com.google.inject.AbstractModule

import ai.deepsense.commons.akka.AkkaModule
import ai.deepsense.commons.config.ConfigModule
import ai.deepsense.commons.rest.RestModule
import ai.deepsense.sessionmanager.mq.MqModule
import ai.deepsense.sessionmanager.rest.ApisModule
import ai.deepsense.sessionmanager.service.ServiceModule

class SessionManagerAppModule extends AbstractModule {
  override def configure(): Unit = {
    installCore()
    installServices()
    installServer()
  }

  private def installCore(): Unit = {
    install(new ConfigModule)
    install(new AkkaModule)
    install(new MqModule)
  }

  private def installServices(): Unit = {
    install(new ServiceModule)
  }

  private def installServer(): Unit = {
    install(new RestModule)
    install(new ApisModule)
  }
}