本文整理汇总了Scala中com.google.inject.Provides类的典型用法代码示例。如果您正苦于以下问题:Scala Provides类的具体用法?Scala Provides怎么用?Scala Provides使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Provides类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: SNSClientModule
//设置package包名称以及导入依赖的类
package uk.ac.wellcome.finatra.modules
import javax.inject.Singleton
import com.amazonaws.auth.{AWSStaticCredentialsProvider, BasicAWSCredentials}
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
import com.amazonaws.services.sns._
import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import uk.ac.wellcome.models.aws.AWSConfig
object SNSClientModule extends TwitterModule {
val snsEndpoint = flag[String](
"aws.sns.endpoint",
"",
"Endpoint of AWS SNS. The region will be used if the enpoint is not provided")
@Singleton
@Provides
def providesSNSClient(awsConfig: AWSConfig): AmazonSNS = {
val standardSnsClient = AmazonSNSClientBuilder.standard
if (snsEndpoint().isEmpty)
standardSnsClient
.withRegion(awsConfig.region)
.build()
else
standardSnsClient
.withCredentials(
new AWSStaticCredentialsProvider(
new BasicAWSCredentials(awsConfig.accessKey.get,
awsConfig.secretKey.get)))
.withEndpointConfiguration(
new EndpointConfiguration(snsEndpoint(), awsConfig.region))
.build()
}
}
开发者ID:wellcometrust,项目名称:platform-api,代码行数:36,代码来源:SNSClientModule.scala
示例2: CtxBasicModule
//设置package包名称以及导入依赖的类
package context.di
import javax.inject.Singleton
import com.google.inject.{AbstractModule, Provides}
import context.propagation.threadlocal.CurrentCtxLocalThread
import context.{CtxFactory, CtxFactorySpanOnly, CurrentCtx}
class CtxBasicModule extends AbstractModule {
def configure() = {
bind(classOf[CtxFactory]).to(classOf[CtxFactorySpanOnly]).asEagerSingleton()
}
@Provides
@Singleton
def currentCtx(): CurrentCtx = {
CurrentCtx.instance = CurrentCtxLocalThread.instance
CurrentCtx.instance
}
}
开发者ID:davidB,项目名称:sandbox_context_scala,代码行数:22,代码来源:CtxBasicModule.scala
示例3: HawkularModule
//设置package包名称以及导入依赖的类
package di
import javax.inject.{Named, Singleton}
import com.google.inject.{AbstractModule, Provides}
import io.opentracing.Tracer
import org.hawkular.apm.api.utils.PropertyUtil
import org.hawkular.apm.client.api.recorder.BatchTraceRecorder.BatchTraceRecorderBuilder
import org.hawkular.apm.client.api.recorder.TraceRecorder
import org.hawkular.apm.client.api.recorder.BatchTraceRecorder
import org.hawkular.apm.trace.publisher.rest.client.TracePublisherRESTClient
class HawkularModule extends AbstractModule {
def configure() = {
}
//Hawkular seems to failed to load TracePublisher via ServiceLoader, so Made a explicit
@Provides
@Singleton
@Named("backend")
def traceRecorder(): TraceRecorder = {
val publisher = new TracePublisherRESTClient(
PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_USERNAME, "jdoe"),
PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_PASSWORD, "password"),
PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI, "http://localhost:8080")
)
val builder = new BatchTraceRecorderBuilder()
builder.withTracePublisher(publisher)
Option(PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_COLLECTOR_BATCHSIZE)).foreach { batchSize =>
builder.withBatchSize(Integer.parseInt(batchSize))
}
Option(PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_COLLECTOR_BATCHTIME)).foreach { batchTime =>
builder.withBatchTime(Integer.parseInt(batchTime))
}
Option(PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_COLLECTOR_BATCHTHREADS)).foreach { threadPoolSize =>
builder.withBatchPoolSize(Integer.parseInt(threadPoolSize))
}
builder.withTenantId(PropertyUtil.getProperty("HAWKULAR_APM_TENANTID"))
new BatchTraceRecorder(builder)
}
@Provides
@Singleton
def tracer(traceRecorder: TraceRecorder): Tracer = {
val tracer0 = new org.hawkular.apm.client.opentracing.APMTracer(traceRecorder)
//GlobalTracer.register(tracer0)
//GlobalTracer.get()
tracer0
}
}
开发者ID:davidB,项目名称:sandbox_context_scala,代码行数:53,代码来源:HawkularModule.scala
示例4: NoopTracerModule
//设置package包名称以及导入依赖的类
package di
import javax.inject.{Named, Singleton}
import com.google.inject.{AbstractModule, Provides}
import io.opentracing.{NoopTracerFactory, Tracer}
class NoopTracerModule extends AbstractModule {
def configure() = {
}
@Provides
@Singleton
@Named("backend")
def tracer(): Tracer = {
return NoopTracerFactory.create()
}
}
开发者ID:davidB,项目名称:sandbox_context_scala,代码行数:19,代码来源:NoopTracerModule.scala
示例5: Modules
//设置package包名称以及导入依赖的类
package com.bob.reservefund.scala
import com.bob.reservefund.scala.Service.UserService
import com.bob.reservefund.scala.Util.EnvironmentContext
import com.google.gson.JsonParser
import com.google.inject.{Provides, Singleton}
import com.twitter.finatra.annotations.Flag
import com.twitter.inject.TwitterModule
import com.typesafe.config.ConfigFactory
import scala.collection.JavaConversions._
import scala.io.Source
object Modules extends TwitterModule {
val config = ConfigFactory.load()
val test = config.getString("config.testurl")
val default = config.getString("config.defaulturl")
val env = System.getProperty("active.environment", "default")
val url = env match {
case "test" => test
case _ => default
}
val jsons = Source.fromURL(url).mkString
val parser = new JsonParser()
val jsonobj = parser.parse(jsons).getAsJsonObject.getAsJsonArray("propertySources").get(0).getAsJsonObject.getAsJsonObject("source")
jsonobj.entrySet().foreach(x => {
flag(x.getKey, x.getValue.getAsString, "")
EnvironmentContext.put(x.getKey, x.getValue.getAsString)
})
flag("dbusername", "root", "the username of the database")
flag("active.environment", env, "which environment now is run")
@Singleton
@Provides
def providesUserService(@Flag("dbusername") dbusername: String): UserService = {
new UserService(dbusername)
}
}
开发者ID:bobxwang,项目名称:ReserveFundService,代码行数:44,代码来源:Modules.scala
示例6: DataSource
//设置package包名称以及导入依赖的类
package io.github.mijicd.prezi.modules
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject.{Provides, Singleton}
import com.twitter.inject.TwitterModule
import io.github.mijicd.prezi.domain.Presentation
import scala.collection.JavaConverters._
import scala.io.BufferedSource
object DataSource extends TwitterModule with Managed with DateConversion {
@Singleton
@Provides
def provideSource: Seq[Presentation] = {
val resource = getClass.getResource("/prezis.json")
using(scala.io.Source.fromURL(resource)) { source =>
val items = loadFrom(source)
sortSeq(items)
}
}
private def loadFrom(source: BufferedSource): Seq[Presentation] = {
val json = source.getLines().mkString
val mapper = new ObjectMapper()
val factory = mapper.getTypeFactory
val items: java.util.List[Presentation] =
mapper.readValue(json,
factory.constructCollectionType(classOf[java.util.List[Presentation]],
classOf[Presentation]))
items.asScala
}
private def sortSeq(seq: Seq[Presentation]) = seq.sortWith(compare)
private def compare(first: Presentation, second: Presentation): Boolean = {
val firstDate = dateOf(first.createdAt)
val secondDate = dateOf(second.createdAt)
firstDate.isAfter(secondDate)
}
}
开发者ID:mijicd,项目名称:finatra-demo,代码行数:45,代码来源:DataSource.scala
示例7: MetricsReporterModule
//设置package包名称以及导入依赖的类
package mesosphere.marathon.metrics
import com.google.inject.{ AbstractModule, Provides, Scopes, Singleton }
import org.apache.hadoop.metrics.util.MetricsRegistry
class MetricsReporterModule(metricsReporterConf: MetricsReporterConf) extends AbstractModule {
override def configure(): Unit = {
bind(classOf[MetricsReporterConf]).toInstance(metricsReporterConf)
bind(classOf[MetricsReporterService]).in(Scopes.SINGLETON)
}
@Provides
@Singleton
def provideMetricsRegistry(): MetricsRegistry = {
new MetricsRegistry()
}
}
开发者ID:xiaozai512,项目名称:marathon,代码行数:20,代码来源:MetricsReporterModule.scala
示例8: SwaggerModule
//设置package包名称以及导入依赖的类
package com.github.ikhoon.modules
import javax.inject.Singleton
import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import io.swagger.models.{ Info, Swagger }
object SwaggerModule extends TwitterModule {
flag(name = "swagger.docs.endpoint", default = "/api-docs", help = "The key to use")
lazy val swagger = {
val swag = new Swagger()
val info = new Info()
.description("The Finatra Mysql Seed API, this is a sample for swagger document generation")
.version("1.0.1")
.title("Finatra Mysql Seed API")
swag
.info(info)
swag
}
@Singleton
@Provides
def provideSwagger: Swagger = swagger
}
开发者ID:ikhoon,项目名称:finatra-mysql-seed,代码行数:30,代码来源:SwaggerModule.scala
示例9: HttpClientModules
//设置package包名称以及导入依赖的类
package com.github.ikhoon.modules
import javax.inject.{ Named, Singleton }
import com.google.inject.Provides
import com.twitter.finatra.httpclient.HttpClient
import com.twitter.finatra.httpclient.modules.HttpClientModule
import com.twitter.finatra.json.FinatraObjectMapper
import com.twitter.inject.TwitterModule
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
object HttpClientModules {
val modules = Seq(FakeHttpClientModule())
}
abstract class BasicHttpClientModule() extends TwitterModule {
protected def provideHttpClient(mapper: FinatraObjectMapper, host: String, port: Int = 80): HttpClient = {
val httpClientModule = new HttpClientModule {
override def dest: String = s"$host:$port"
override def defaultHeaders: Map[String, String] = Map("Host" -> host)
}
httpClientModule.provideHttpClient(mapper, httpClientModule.provideHttpService)
}
}
object FakeHttpClientModule {
def apply() = new BasicHttpClientModule {
@Named("fake") @Provides @Singleton
def provideHttpClient(mapper: FinatraObjectMapper, config: Config) =
super.provideHttpClient(mapper, config.as[String]("fake.host"), config.as[Int]("fake.port"))
}
}
开发者ID:ikhoon,项目名称:finatra-mysql-seed,代码行数:36,代码来源:HttpClientModules.scala
示例10: DocumentWishListsRepositoryModule
//设置package包名称以及导入依赖的类
package me.kamkor.wishlists.repository.document
import java.net.URL
import com.google.inject.{Provides, Singleton}
import com.twitter.finatra.json.FinatraObjectMapper
import com.twitter.inject.TwitterModule
import me.kamkor.finatra.httpclient.HttpClient
import me.kamkor.wishlists.repository.WishListsRepository
import me.kamkor.yaas.oauth2.OAuthService
import me.kamkor.yaas.oauth2.model.ClientCredentials
import me.kamkor.yaas.proxy.YaasProxyClient
object DocumentWishListsRepositoryModule extends TwitterModule {
val documentUrl = flag("document.url", "https://api.yaas.io/hybris/document/v1", "destination of the yaas document service")
val documentClientId = flag("document.clientId", "clientId", "client id for the document service")
val documentClientSecret = flag("document.clientSecret", "clientSecret", "client secret for the document service")
@Singleton
@Provides
@DocumentClient
def provideDocumentClient(oauthService: OAuthService): YaasProxyClient = {
val httpClient = HttpClient(new URL(documentUrl()))
val proxyClient = new YaasProxyClient(oauthService, httpClient)
proxyClient
}
@Singleton
@Provides
def providesWishListsRepository(oauthService: OAuthService, mapper: FinatraObjectMapper): WishListsRepository = {
val httpClient = HttpClient(new URL(documentUrl()))
val proxyClient = new YaasProxyClient(oauthService, httpClient)
val clientCredentials = ClientCredentials(
documentClientId(), documentClientSecret(), Seq("hybris.document_view", "hybris.document_manage"))
new DocumentWishListsRepository(proxyClient, mapper, clientCredentials)
}
}
开发者ID:kamkor,项目名称:yaas-wishlist-service,代码行数:41,代码来源:DocumentWishListsRepositoryModule.scala
示例11: AppDependencyModule
//设置package包名称以及导入依赖的类
package modules
import com.google.inject.name.Named
import com.google.inject.{AbstractModule, Singleton, Provides}
import com.redis.RedisClientPool
import infrastructures.SomeModelDAO
import play.api.Configuration
import services.SomeModelStore
class AppDependencyModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[SomeModelStore]).to(classOf[SomeModelDAO])
}
@Provides
@Singleton
@Named("some_model")
def provideStoreDetailRedisClientPool(
configuration: Configuration
): RedisClientPool = new RedisClientPool(
configuration.getString("redis.host").get,
configuration.getInt("redis.port").get,
database = 1
)
}
开发者ID:UsrNameu1,项目名称:RedisDISample,代码行数:28,代码来源:AppDependencyModule.scala
示例12: Module
//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api
import java.nio.file.Paths
import au.id.tmm.senatedb.api.persistence.population.DbPopulationActor
import au.id.tmm.senatedb.core.engine.{ParsedDataStore, TallyEngine}
import au.id.tmm.senatedb.core.model.flyweights.PostcodeFlyweight
import au.id.tmm.senatedb.core.rawdata.{AecResourceStore, RawDataStore}
import com.google.inject.{AbstractModule, Provides, Singleton}
import play.api.libs.concurrent.AkkaGuiceSupport
import scalikejdbc.{ConnectionPool, ConnectionPoolContext, MultipleConnectionPoolContext}
class Module extends AbstractModule with AkkaGuiceSupport {
override def configure(): Unit = {
bindActor[DbPopulationActor]("dbPopulationActor")
}
@Provides
def provideConnectionPoolContext(): ConnectionPoolContext =
MultipleConnectionPoolContext(ConnectionPool.DEFAULT_NAME -> ConnectionPool())
@Provides
@Singleton
def providePostcodeFlyweight: PostcodeFlyweight = PostcodeFlyweight()
@Provides
@Singleton
def provideParsedDataStore(rawDataStore: RawDataStore): ParsedDataStore = ParsedDataStore(rawDataStore)
@Provides
@Singleton
def provideRawDataStore(aecResourceStore: AecResourceStore): RawDataStore = RawDataStore(aecResourceStore)
@Provides
@Singleton
def provideAecResourceStore: AecResourceStore = AecResourceStore.at(Paths.get("rawData"))
@Provides
def provideTallyEngine: TallyEngine = TallyEngine
}
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:43,代码来源:Module.scala
示例13: Module
//设置package包名称以及导入依赖的类
import java.time.Clock
import com.google.inject.{AbstractModule, Provides}
import models.daos.{AbstractBaseDAO, BaseDAO}
import models.entities.{ParkingSlot, User}
import models.persistence.SlickTables
import models.persistence.SlickTables.{ParkingSlotTable, UsersTable}
class Module extends AbstractModule {
override def configure() = {
// Use the system clock as the default implementation of Clock
bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
}
@Provides
def provideUsersDAO: AbstractBaseDAO[UsersTable, User] = new BaseDAO[UsersTable, User] {
override protected val tableQ: dbConfig.driver.api.TableQuery[UsersTable] = SlickTables.usersTableQ
}
@Provides
def provideParkingSlotDAO: AbstractBaseDAO[ParkingSlotTable, ParkingSlot] = new BaseDAO[ParkingSlotTable, ParkingSlot] {
override protected val tableQ: dbConfig.driver.api.TableQuery[ParkingSlotTable] = SlickTables.parkingSlotTableQ
}
}
开发者ID:mathissimo,项目名称:parkingSLot,代码行数:29,代码来源:Module.scala
示例14: DIConfiguration
//设置package包名称以及导入依赖的类
package com.wunder.pets.web
import javax.inject.Inject
import com.google.inject.{AbstractModule, Provides}
import com.wunder.pets.entity.Entity.{All, Create, Find}
import com.wunder.pets.pets._
import scala.concurrent.ExecutionContext
class DIConfiguration extends AbstractModule {
override def configure() = {
bind(classOf[PetRepository]).to(classOf[PersistentPetRepository])
}
@Provides
def provideCreatePet(@Inject petRepository: PetRepository)(implicit ec: ExecutionContext): Create[CreatePetForm, Pet] =
Pet.create(petRepository)
@Provides
def provideFindPet(@Inject petRepository: PetRepository)(implicit ec: ExecutionContext): Find[Pet] =
Pet.find(petRepository)
@Provides
def provideAllPets(@Inject petRepository: PetRepository)(implicit ec: ExecutionContext): All[Pet] =
Pet.all(petRepository)
}
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:29,代码来源:DIConfiguration.scala
示例15: Module
//设置package包名称以及导入依赖的类
package com.github.dnvriend
import com.google.inject.{AbstractModule, Provides}
import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer}
import org.springframework.kafka.core.{DefaultKafkaConsumerFactory, DefaultKafkaProducerFactory, KafkaTemplate}
import org.springframework.kafka.listener.config.ContainerProperties
import org.springframework.kafka.listener.{KafkaMessageListenerContainer, MessageListener}
import scala.collection.JavaConversions._
class Module extends AbstractModule {
protected def configure(): Unit = {
}
@Provides
def createProducerTemplate: KafkaTemplate[String, String] = {
val senderProps: java.util.Map[String, Any] = Map(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG -> "localhost:9092",
ProducerConfig.RETRIES_CONFIG -> 0,
ProducerConfig.BATCH_SIZE_CONFIG -> 16384,
ProducerConfig.LINGER_MS_CONFIG -> 1,
ProducerConfig.BUFFER_MEMORY_CONFIG -> 33554432,
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG -> classOf[StringSerializer],
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG -> classOf[StringSerializer]
)
val producerFactory = new DefaultKafkaProducerFactory[String, String](senderProps.mapValues(_.asInstanceOf[AnyRef]))
new KafkaTemplate[String, String](producerFactory)
}
@Provides
def createKafkaMessageListenerContainer(messageListener: MessageListener[String, String]): KafkaMessageListenerContainer[String, String] = {
val consumerProps: java.util.Map[String, Any] = Map(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG -> "localhost:9092",
ConsumerConfig.GROUP_ID_CONFIG -> "group",
ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG -> true,
ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG -> "100",
ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG -> "15000",
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG -> classOf[StringDeserializer],
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG -> classOf[StringDeserializer]
)
val containerProperties = new ContainerProperties("test")
containerProperties.setMessageListener(messageListener)
val consumerFactory = new DefaultKafkaConsumerFactory[String, String](consumerProps.mapValues(_.asInstanceOf[AnyRef]))
val container = new KafkaMessageListenerContainer[String, String](consumerFactory, containerProperties)
container.setBeanName("testAuto")
container.start()
container
}
@Provides
def messageListener: MessageListener[String, String] = new MessageListener[String, String] {
override def onMessage(message: ConsumerRecord[String, String]): Unit = {
println(s"received: $message")
}
}
}
开发者ID:dnvriend,项目名称:spring-kafka-test,代码行数:61,代码来源:Module.scala
示例16: UserModule
//设置package包名称以及导入依赖的类
package com.clemble.loveit.user
import com.clemble.loveit.user.service._
import com.clemble.loveit.user.service.repository._
import com.clemble.loveit.user.service.repository.mongo.{MongoInvitationRepository, MongoUserRepository}
import javax.inject.{Named, Singleton}
import com.clemble.loveit.common.mongo.JSONCollectionFactory
import com.google.inject.Provides
import net.codingwell.scalaguice.ScalaModule
import org.joda.time.DateTimeZone
import play.api.libs.ws.WSClient
import play.api.{Configuration, Environment, Mode}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.ExecutionContext
class UserModule(env: Environment, conf: Configuration) extends ScalaModule {
override def configure(): Unit = {
DateTimeZone.setDefault(DateTimeZone.UTC)
bind(classOf[UserService]).to(classOf[SimpleUserService])
bind(classOf[UserRepository]).to(classOf[MongoUserRepository])
bind(classOf[InvitationRepository]).to(classOf[MongoInvitationRepository])
bind(classOf[InvitationService]).to(classOf[SimpleInvitationService])
}
@Provides
@Named("user")
@Singleton
def userMongoCollection(mongoApi: ReactiveMongoApi, ec: ExecutionContext): JSONCollection = {
JSONCollectionFactory.create("user", mongoApi, ec, env)
}
@Provides
@Named("invitation")
@Singleton
def inviteMongoCollection(mongoApi: ReactiveMongoApi, ec: ExecutionContext): JSONCollection = {
JSONCollectionFactory.create("invitation", mongoApi, ec, env)
}
@Provides
@Singleton
def subscriptionManager(ws: WSClient, ec: ExecutionContext): SubscriptionManager = {
if (env.mode == Mode.Test) {
TestSubscriptionManager
} else {
val apiKey = conf.getString("email.mailgun.api.key").get
MailgunSubscriptionManager(apiKey, ws, ec)
}
}
}
开发者ID:thankyo,项目名称:thank,代码行数:61,代码来源:UserModule.scala
示例17: ApiModule
//设置package包名称以及导入依赖的类
package org.globalnames
package index
package api
import com.google.inject.{Provides, Singleton}
import com.twitter.app.Flag
import com.twitter.finagle.ThriftMux
import com.twitter.inject.TwitterModule
import thrift.nameresolver.{Service => NameResolverService}
import scala.util.Properties
object ApiModule extends TwitterModule {
val nameresolverServiceAddress: Flag[String] = flag(
name = "nameresolverServiceAddress",
help = "Host and port of nameresolver service",
default = Properties.envOrElse("NAMERESOLVER_ADDRESS", "")
)
@Singleton
@Provides
def provideNameResolverClient: NameResolverService.FutureIface =
ThriftMux.client.newIface[NameResolverService.FutureIface](nameresolverServiceAddress())
}
开发者ID:GlobalNamesArchitecture,项目名称:gnindex,代码行数:26,代码来源:ApiModule.scala
示例18: MatcherModule
//设置package包名称以及导入依赖的类
package org.globalnames
package index
package matcher
import java.io.File
import com.google.inject.{Provides, Singleton}
import com.twitter.app.Flag
import com.twitter.inject.{Logging, TwitterModule}
import org.globalnames.{matcher => matcherlib}
import scala.io.Source
import scalaz._
import Scalaz._
object MatcherModule extends TwitterModule with Logging {
val namesFileKey: Flag[File] = flag(
name = "names-path",
help = "Path to file that contains canonical names for matcher"
)
val namesWithDatasourcesFileKey: Flag[File] = flag(
name = "names-datasources-path",
help = "Path to file that contains canonical names with datasources for matcher"
)
@Singleton
@Provides
def prodiveMatcherLib: matcherlib.Matcher = {
val names = namesFileKey().exists ?
Source.fromFile(namesFileKey()).getLines.toVector |
{ logger.error(s"${namesFileKey()} file doesn't exist"); Vector.empty[String] }
matcherlib.Matcher(names)
}
@Singleton
@Provides
def provideCanonicalNames: CanonicalNames = {
def create(): CanonicalNames = {
val nameToDatasourceIdsMap =
Source.fromFile(namesWithDatasourcesFileKey()).getLines.zipWithIndex
.foldLeft(Map.empty[String, Set[Int]].withDefaultValue(Set.empty)) {
case (mp, (line, idx)) =>
if (idx % 100000 == 0) {
logger.info(s"Names with datasources loaded in total: $idx")
}
val Array(canonicalName, dataSourceId) = line.split('\t')
mp + (canonicalName -> (mp(canonicalName) + dataSourceId.toInt))
}
CanonicalNames(nameToDatasourceIdsMap)
}
namesWithDatasourcesFileKey().exists ? create() |
{ logger.error(s"${namesWithDatasourcesFileKey()} file doesn't exist")
CanonicalNames(Map.empty.withDefaultValue(Set.empty)) }
}
}
开发者ID:GlobalNamesArchitecture,项目名称:gnindex,代码行数:60,代码来源:MatcherModule.scala
示例19: NameResolverModule
//设置package包名称以及导入依赖的类
package org.globalnames
package index
package nameresolver
import com.google.inject.{Provides, Singleton}
import com.twitter.app.Flag
import com.twitter.finagle.ThriftMux
import com.twitter.inject.TwitterModule
import thrift.matcher.{Service => MatcherService}
import slick.jdbc.PostgresProfile.api._
import scala.util.Properties
object NameResolverModule extends TwitterModule {
val matcherServiceAddress: Flag[String] = flag(
name = "matcherServiceAddress",
help = "Host and port of matcher service",
default = Properties.envOrElse("MATCHER_ADDRESS", "")
)
@Singleton
@Provides
def provideDatabase: Database = {
val host = Properties.envOrElse("DB_HOST", "localhost")
val port = Properties.envOrElse("DB_PORT", "5432")
val database = Properties.envOrElse("DB_DATABASE", "development")
val url = s"jdbc:postgresql://$host:$port/$database"
Database.forURL(
url = url,
user = Properties.envOrElse("DB_USER", "postgres"),
password = Properties.envOrElse("DB_USER_PASS", ""),
driver = "org.postgresql.Driver"
)
}
@Singleton
@Provides
def provideMatcherClient: MatcherService.FutureIface =
ThriftMux.client.newIface[MatcherService.FutureIface](matcherServiceAddress())
}
开发者ID:GlobalNamesArchitecture,项目名称:gnindex,代码行数:41,代码来源:NameResolverModule.scala
示例20: DefaultModule
//设置package包名称以及导入依赖的类
package modules
import com.galacticfog.gestalt.security.SecurityConfig
import com.galacticfog.gestalt.security.data.domain.{AccountStoreMappingService, DefaultAccountStoreMappingServiceImpl}
import com.google.inject.{AbstractModule, Provides}
import org.joda.time.Duration
import scala.util.Properties.envOrNone
import scala.util.Try
class DefaultModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[AccountStoreMappingService]).to(classOf[DefaultAccountStoreMappingServiceImpl])
}
@Provides
def providesSecurityConfig(): SecurityConfig = {
import SecurityConfig._
val tokenLifetime = (for {
envString <- envOrNone("OAUTH_TOKEN_LIFETIME")
lifetime <- Try { Duration.parse(envString) }.toOption
} yield lifetime) getOrElse DEFAULT_TOKEN_LIFETIME
val methodOverrideParameter = envOrNone("METHOD_OVERRIDE_PARAM") getOrElse DEFAULT_METHOD_OVERRIDE_PARAM
val database = DatabaseConfig(
host = envOrThrow("DATABASE_HOSTNAME"),
username = envOrThrow("DATABASE_USERNAME"),
password = envOrThrow("DATABASE_PASSWORD"),
dbname = envOrThrow("DATABASE_NAME"),
port = getEnvOptInt("DATABASE_PORT").getOrElse(5432),
timeout = getEnvOptInt("DATABASE_TIMEOUT_MS").getOrElse(5000)
)
val rateLimiting = AuthAttemptConfig(
periodInMinutes = getEnvOptInt("OAUTH_RATE_LIMITING_PERIOD") getOrElse AuthAttemptConfig.DEFAULT_RATE_LIMITING_PERIOD_IN_MINUTES,
attemptsPerPeriod = getEnvOptInt("OAUTH_RATE_LIMITING_AMOUNT") getOrElse AuthAttemptConfig.DEFAULT_MAX_ATTEMPTS_PER_MINUTE
)
SecurityConfig(
tokenLifetime = tokenLifetime,
methodOverrideParameter = methodOverrideParameter,
database = database,
rateLimiting = rateLimiting
)
}
}
开发者ID:GalacticFog,项目名称:gestalt-security,代码行数:50,代码来源:DefaultModule.scala
注:本文中的com.google.inject.Provides类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论