net.codingwell.scalaguice.ScalaModule Scala Examples

The following examples show how to use net.codingwell.scalaguice.ScalaModule. 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: ContactsModule.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.contacts.modules

import com.dataengi.crm.contacts.daos._
import com.dataengi.crm.contacts.repositories._
import com.dataengi.crm.contacts.services._
import com.dataengi.crm.contacts.slick.InitiateContactsTables
import net.codingwell.scalaguice.ScalaModule

class ContactsModule extends ScalaModule {

  override def configure() = {

    // Init
    bind[InitiateContactsTables].asEagerSingleton()

    // Services
    bind[ContactsService].to[ContactsServiceImplementation]
    bind[ContactsBooksService].to[ContactsBooksServiceImplementation]
    bind[GroupsService].to[GroupsServiceImplementation]

    // Repositories
    bind[ContactsRepository].to[ContactsRepositoryImplementation]
    bind[ContactsBooksRepository].to[ContactsBooksRepositoryImplementation]
    bind[GroupsRepository].to[GroupsRepositoryImplementation]

    // DAOs
    bind[GroupsDAO].to[GroupsSlickDAOImplementation]
    bind[ContactsSlickDAO].to[ContactsSlickDAOImplementation]
    bind[ContactsBooksDAO].to[ContactsBooksSlickDAOImplementation]

  }

} 
Example 2
Source File: SilhouetteModule.scala    From crm-seed   with Apache License 2.0 5 votes vote down vote up
package com.dataengi.crm.identities.modules

import com.dataengi.crm.configurations.{CompaniesConfiguration, RolesConfiguration, RootConfiguration, SilhouetteConfiguration}
import com.dataengi.crm.identities.actions.{ActionsProvider, ActionsProviderImplementation}
import com.google.inject.name.Named
import com.google.inject.{Provides, Singleton}
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import com.mohiva.play.silhouette.api.crypto.{AuthenticatorEncoder, Crypter, CrypterAuthenticatorEncoder}
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.services._
import com.mohiva.play.silhouette.api.util._
import com.mohiva.play.silhouette.api.{Environment, EventBus, Silhouette, SilhouetteProvider}
import com.mohiva.play.silhouette.crypto.{JcaCrypter, JcaCrypterSettings}
import com.mohiva.play.silhouette.impl.authenticators._
import com.mohiva.play.silhouette.impl.providers._
import com.mohiva.play.silhouette.impl.services._
import net.ceedubs.ficus.readers.EnumerationReader._
import com.mohiva.play.silhouette.impl.util._
import com.mohiva.play.silhouette.password.BCryptPasswordHasher
import com.mohiva.play.silhouette.persistence.daos.DelegableAuthInfoDAO
import com.mohiva.play.silhouette.persistence.repositories.DelegableAuthInfoRepository
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import net.codingwell.scalaguice.ScalaModule
import play.api.Configuration
import play.api.libs.ws.WSClient
import com.dataengi.crm.identities.daos._
import com.dataengi.crm.identities.repositories._
import com.dataengi.crm.identities.services._
import com.dataengi.crm.identities.slick.initiation.InitiateTables
import com.dataengi.crm.identities.utils.auth.DefaultEnv

import scala.concurrent.ExecutionContext

class SilhouetteModule extends ScalaModule {

  def configure() = {
    // Initiation ORDER make sense
    bind[InitiateTables].asEagerSingleton()
    bind[IdentitiesInitiation].asEagerSingleton()

    // Silhouette
    bind[SecuredErrorHandler].to[CustomSecuredErrorHandler]
    bind[Silhouette[DefaultEnv]].to[SilhouetteProvider[DefaultEnv]]
    bind[CacheLayer].to[PlayCacheLayer]
    bind[PasswordHasher].toInstance(new BCryptPasswordHasher)
    bind[FingerprintGenerator].toInstance(new DefaultFingerprintGenerator(false))
    bind[EventBus].toInstance(EventBus())
    bind[Clock].toInstance(Clock())

    // Replace this with the bindings to your concrete DAOs
    bind[PasswordInfoDAO].to[PasswordInfoDAOSlickImplementation]
    bind[DelegableAuthInfoDAO[PasswordInfo]].to[PasswordInfoDAO]

    // Repository
    bind[RolesRepository].to[RolesRepositoryImplementation]
    bind[CompaniesRepository].to[CompaniesRepositoryImplementation]
    bind[InvitesRepository].to[InvitesRepositoryImplementation]
    bind[JWTAuthenticatorRepository].to[JWTAuthenticatorCacheRepositoryImplementation]
    bind[UsersRepository].to[UsersRepositoryImplementation]
    bind[RecoverPasswordInfoRepository].to[RecoverPasswordInfoRepositoryImplementation]

    // DAOs
    bind[CompaniesDAO].to[CompaniesSlickDAOImplementation]
    bind[RolesDAO].to[RolesSlickDAOImplementation]
    bind[InvitesDAO].to[InvitesSlickDAOImplementation]
    bind[JWTAuthenticatorDAO].to[JWTAuthenticatorSlickDAOImplementation]
    bind[UsersDAO].to[UsersSlickDAOImplementation]
    bind[RecoverPasswordInfoDAO].to[RecoverPasswordInfoSlickDAOImplementation]

    // Services
    bind[UsersService].to[UsersServiceImplementation]
    bind[CompaniesService].to[CompaniesServiceImplementation]
    bind[RolesService].to[RolesServiceImplementation]
    bind[InvitesService].to[InvitesServiceImplementation]
    bind[AuthenticationService].to[AuthenticationServiceImplementation]
    bind[UsersManagementService].to[UsersManagementServiceImplementation]

    // Actions
    bind[ActionsProvider].to[ActionsProviderImplementation]

    // Configuration
    bind[RolesConfiguration].asEagerSingleton()
    bind[CompaniesConfiguration].asEagerSingleton()
    bind[RootConfiguration].asEagerSingleton()
    bind[SilhouetteConfiguration].asEagerSingleton()

  }

  
  @Provides
  def provideCredentialsProvider(authInfoRepository: AuthInfoRepository,
                                 passwordHasherRegistry: PasswordHasherRegistry,
                                 executionContext: ExecutionContext): CredentialsProvider = {

    new CredentialsProvider(authInfoRepository, passwordHasherRegistry)(executionContext)
  }

} 
Example 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
Source File: DevHatInitializationModule.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.modules

import java.util.UUID

import com.typesafe.config.Config
import javax.inject.Inject
import net.codingwell.scalaguice.ScalaModule
import org.hatdex.hat.api.models.{ Owner, Platform }
import org.hatdex.hat.api.service.{ DalExecutionContext, UsersService }
import org.hatdex.hat.authentication.models.HatUser
import org.hatdex.hat.dal.HatDbSchemaMigration
import org.hatdex.hat.resourceManagement.{ HatServer, HatServerProvider }
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{ ConfigLoader, Configuration, Logger }

import scala.concurrent.Future

class DevHatInitializationModule extends ScalaModule with AkkaGuiceSupport {

  
  override protected def configure(): Unit = {
    bind[DevHatInitializer].asEagerSingleton()
  }
}

class DevHatInitializer @Inject() (
    configuration: Configuration,
    serverProvider: HatServerProvider,
    usersService: UsersService)(implicit ec: DalExecutionContext) {
  val logger = Logger(this.getClass)

  import DevHatConfig.configLoader

  val devHats = configuration.get[Map[String, DevHatConfig]]("devhats")
  val devHatMigrations = configuration.get[Seq[String]]("devhatMigrations")

  logger.info(s"Initializing HATs: $devHats")
  devHats.values.map(initializeHat)

  def initializeHat(hat: DevHatConfig) = {
    val hatServer: Future[HatServer] = serverProvider.retrieve(hat.domain).map(_.get)

    val eventuallyMigrated = for {
      server ← hatServer
      _ ← new HatDbSchemaMigration(configuration, server.db, ec).run(devHatMigrations)
      _ ← setupCredentials(hat)(server)
    } yield ()

    eventuallyMigrated map { _ =>
      logger.info(s"Database successfully initialized for ${hat.owner}")
    } recover {
      case e =>
        logger.error(s"Database initialisation failed for ${hat.owner}: ${e.getMessage}", e)
    } map { _ =>
      logger.debug(s"Shutting down connection to database for ${hat.owner}")
      //      hatServer.map(_.db.shutdown)
    }
  }

  def setupCredentials(hat: DevHatConfig)(implicit server: HatServer): Future[Unit] = {
    logger.debug(s"Setup credentials for ${hat.owner}")
    val ownerId = UUID.fromString("694dd8ed-56ae-4910-abf1-6ec4887b4c42")
    val platformId = UUID.fromString("6507ae16-13d7-479b-8ebc-65c28fec1634")
    for {
      savedOwner <- usersService.saveUser(HatUser(ownerId, hat.owner, Some(hat.ownerPasswordHash), hat.ownerName, Seq(Owner()), enabled = true))
      savedPlatform <- usersService.saveUser(HatUser(platformId, hat.platform, Some(hat.platformPasswordHash), hat.platformName, Seq(Platform()), enabled = true))
    } yield {
      logger.info(s"Saved owner: $savedOwner")
      logger.info(s"Saved platform: $savedPlatform")
      ()
    }
  }
}

case class DevHatConfig(
    owner: String,
    domain: String,
    ownerName: String,
    ownerPasswordHash: String,
    platform: String,
    platformName: String,
    platformPasswordHash: String,
    database: Config)

object DevHatConfig {
  implicit val configLoader: ConfigLoader[DevHatConfig] = new ConfigLoader[DevHatConfig] {
    def load(rootConfig: Config, path: String): DevHatConfig = {
      val config = ConfigLoader.configurationLoader.load(rootConfig, path)
      DevHatConfig(
        owner = config.get[String]("owner"),
        domain = config.get[String]("domain"),
        ownerName = config.get[String]("ownerName"),
        ownerPasswordHash = config.get[String]("ownerPasswordHash"),
        platform = config.get[String]("platform"),
        platformName = config.get[String]("platformName"),
        platformPasswordHash = config.get[String]("platformPasswordHash"),
        database = config.get[Config]("database"))
    }
  }
} 
Example 13
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 14
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 15
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 16
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)))
}