com.google.inject.Provides Scala Examples

The following examples show how to use com.google.inject.Provides. 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
Source File: FinatraHttpServer.scala    From the-finagle-docs   with MIT License 5 votes vote down vote up
package net.gutefrage.basic

import javax.inject.{Inject, Singleton}

import com.google.inject.{Module, Provides}
import com.twitter.finagle.Dtab
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finatra.http.{Controller, HttpServer}
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter, TraceIdMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter
import com.twitter.finatra.response.Mustache
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import net.gutefrage.Dtabs
import net.gutefrage.temperature.thrift.TemperatureService

object FinatraHttpServer extends HttpServer {

  premain {
    Dtabs.init()
  }

  override def modules: Seq[Module] = Seq(TemperatureServiceModule)

  override def defaultFinatraHttpPort = ":9000"

  override protected def configureHttp(router: HttpRouter): Unit =
    router
      .filter[LoggingMDCFilter[Request, Response]]
      .filter[TraceIdMDCFilter[Request, Response]]
      .filter[CommonFilters]
      .add[WeatherController]
}


class WeatherController @Inject()(
  temperatureService: TemperatureService.FutureIface,
  @Flag("local.doc.root") localDocRoot: String,
  @Flag("doc.root") docRoot: String
) extends Controller {

  private val docConfig = DocConfig(localDocRoot, docRoot)

  get("/") { request: Request =>
    temperatureService.mean().map { meanTemperature =>
      DashboardData(meanTemperature, Some("local"), docConfig)
    }
  }

  // Change dtab according to the environment
  get("/:env") { request: Request =>
    val environment = request.params("env")

    Dtab.unwind {
      Dtab.local = Dtab.read(s"/env => /s#/$environment")
      temperatureService.mean().map { meanTemperature =>
        DashboardData(meanTemperature, Some(environment), docConfig)
      }
    }
  }

  // Asset route (for styles.css)
  get("/assets/:*") { request: Request =>
    response.ok.file("/assets/" + request.params("*"))
  }
}

@Mustache("dashboard")
case class DashboardData(
  meanTemperature: Double,
  environment: Option[String],
  docConfig: DocConfig
)
case class DocConfig(localDocRoot: String, docRoot: String)