本文整理汇总了Scala中javax.inject.Provider类的典型用法代码示例。如果您正苦于以下问题:Scala Provider类的具体用法?Scala Provider怎么用?Scala Provider使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Provider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CustomObjectMapperModule
//设置package包名称以及导入依赖的类
package modules
import javax.inject.{Inject, Provider, Singleton}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.inject.{ApplicationLifecycle, Module}
import play.api.{Configuration, Environment}
import play.libs.Json
import scala.concurrent.Future
class CustomObjectMapperModule extends Module {
def bindings(environment: Environment, configuration: Configuration) = Seq(
bind[ObjectMapper].toProvider[ObjectMapperProvider].eagerly()
)
}
@Singleton
class ObjectMapperProvider @Inject() (lifecycle: ApplicationLifecycle) extends Provider[ObjectMapper] {
lazy val get : ObjectMapper = {
val objectMapper = Json.newDefaultMapper()
objectMapper.registerModule(DefaultScalaModule)
Json.setObjectMapper(objectMapper)
lifecycle.addStopHook { () =>
Future.successful(Json.setObjectMapper(null))
}
objectMapper
}
}
示例2: PostResourceHandler
//设置package包名称以及导入依赖的类
package v1.post
import javax.inject.{Inject, Provider}
import play.api.MarkerContext
import scala.concurrent.{ExecutionContext, Future}
import play.api.libs.json._
class PostResourceHandler @Inject()(
routerProvider: Provider[PostRouter],
postRepository: PostRepository)(implicit ec: ExecutionContext) {
def create(postInput: PostFormInput)(implicit mc: MarkerContext): Future[PostResource] = {
val data = PostData(PostId("999"), postInput.title, postInput.body)
// We don't actually create the post, so return what we have
postRepository.create(data).map { id =>
createPostResource(data)
}
}
def lookup(id: String)(implicit mc: MarkerContext): Future[Option[PostResource]] = {
val postFuture = postRepository.get(PostId(id))
postFuture.map { maybePostData =>
maybePostData.map { postData =>
createPostResource(postData)
}
}
}
def find(implicit mc: MarkerContext): Future[Iterable[PostResource]] = {
postRepository.list().map { postDataList =>
postDataList.map(postData => createPostResource(postData))
}
}
private def createPostResource(p: PostData): PostResource = {
PostResource(p.id.toString, routerProvider.get.link(p.id), p.title, p.body)
}
}
示例3: ErrorHandler
//设置package包名称以及导入依赖的类
import javax.inject.{ Inject, Provider }
import play.api.{ Configuration, Environment, Logger, OptionalSourceMapper, UsefulException }
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import play.api.routing.Router
import scala.concurrent.Future
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
override def onProdServerError(request: RequestHeader, exception: UsefulException) =
Future.successful(InternalServerError("A server error occurred: " + exception.getMessage))
override def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
if (statusCode == 413) // Request entity too large
Future.successful(EntityTooLarge("Could not upload the file - too large"))
else if (statusCode == 404) // Not Found
Future.successful(NotFound(views.html.error404()))
else
super.onClientError(request, statusCode, message)
}
}
示例4: ErrorHandler
//设置package包名称以及导入依赖的类
package utils
import javax.inject.{Inject, Provider}
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import play.api.http.DefaultHttpErrorHandler
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}
import play.api.routing.Router
import play.api.{Configuration, OptionalSourceMapper}
import scala.concurrent.Future
import controllers.{WebJarAssets, routes}
class ErrorHandler @Inject() (
val messagesApi: MessagesApi,
env: play.api.Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: javax.inject.Provider[Router],
p: Provider[WebJarAssets])
extends DefaultHttpErrorHandler(env, config, sourceMapper, router)
with SecuredErrorHandler with I18nSupport {
// https://www.playframework.com/documentation/2.5.x/Migration25#Handling-legacy-components
implicit lazy val webJarAssets = p.get()
override def onNotAuthenticated(implicit request: RequestHeader): Future[Result] =
Future.successful(Redirect(routes.Auth.signIn()))
override def onNotAuthorized(implicit request: RequestHeader): Future[Result] =
Future.successful(Redirect(routes.Auth.signIn()).flashing("error" -> Messages("error.accessDenied")))
override def onNotFound(request: RequestHeader, message: String): Future[Result] =
Future.successful(Ok(views.html.errors.notFound(request)))
override def onServerError(request:RequestHeader, exception:Throwable):Future[Result] =
Future.successful(Ok(views.html.errors.serverError(request, exception)))
}
示例5: PostResourceHandler
//设置package包名称以及导入依赖的类
package v1.post
import javax.inject.{Inject, Provider}
import scala.concurrent.{ExecutionContext, Future}
import play.api.libs.json._
class PostResourceHandler @Inject()(
routerProvider: Provider[PostRouter],
postRepository: PostRepository)(implicit ec: ExecutionContext) {
def create(postInput: PostFormInput): Future[PostResource] = {
val data = PostData(PostId("999"), postInput.title, postInput.body)
// We don't actually create the post, so return what we have
postRepository.create(data).map { id =>
createPostResource(data)
}
}
def lookup(id: String): Future[Option[PostResource]] = {
val postFuture = postRepository.get(PostId(id))
postFuture.map { maybePostData =>
maybePostData.map { postData =>
createPostResource(postData)
}
}
}
def find: Future[Iterable[PostResource]] = {
postRepository.list().map { postDataList =>
postDataList.map(postData => createPostResource(postData))
}
}
private def createPostResource(p: PostData): PostResource = {
PostResource(p.id.toString, routerProvider.get.link(p.id), p.title, p.body)
}
}
示例6: WSConfigParser
//设置package包名称以及导入依赖的类
package play.api.libs.ws
import javax.inject.{ Inject, Provider, Singleton }
import com.typesafe.config.{ Config, ConfigException }
import com.typesafe.sslconfig.ssl.SSLConfigParser
import com.typesafe.sslconfig.util.EnrichedConfig
import scala.concurrent.duration.Duration
@Singleton
class WSConfigParser @Inject() (config: Config, classLoader: ClassLoader) extends Provider[WSClientConfig] {
def parse(): WSClientConfig = {
val wsConfig = config.getConfig("play.ws")
val connectionTimeout = Duration(wsConfig.getString("timeout.connection"))
val idleTimeout = Duration(wsConfig.getString("timeout.idle"))
val requestTimeout = Duration(wsConfig.getString("timeout.request"))
val followRedirects = wsConfig.getBoolean("followRedirects")
val useProxyProperties = wsConfig.getBoolean("useProxyProperties")
val userAgent = {
try {
Some(wsConfig.getString("useragent"))
} catch {
case e: ConfigException.Null =>
None
}
}
val compressionEnabled = wsConfig.getBoolean("compressionEnabled")
val sslConfig = new SSLConfigParser(EnrichedConfig(wsConfig.getConfig("ssl")), classLoader).parse()
WSClientConfig(
connectionTimeout = connectionTimeout,
idleTimeout = idleTimeout,
requestTimeout = requestTimeout,
followRedirects = followRedirects,
useProxyProperties = useProxyProperties,
userAgent = userAgent,
compressionEnabled = compressionEnabled,
ssl = sslConfig
)
}
override lazy val get: WSClientConfig = parse()
}
示例7: TestGroupManagerFixture
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package api
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Provider
import akka.event.EventStream
import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.core.group.GroupManagerModule
import mesosphere.marathon.core.leadership.AlwaysElectedLeadershipModule
import mesosphere.marathon.io.storage.StorageProvider
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.storage.repository.{ AppRepository, GroupRepository, PodRepository }
import mesosphere.marathon.test.{ MarathonActorSupport, Mockito }
import mesosphere.marathon.util.WorkQueue
class TestGroupManagerFixture extends Mockito with MarathonActorSupport {
val service = mock[MarathonSchedulerService]
val groupRepository = mock[GroupRepository]
val podRepository = mock[PodRepository]
val appRepository = mock[AppRepository]
val eventBus = mock[EventStream]
val provider = mock[StorageProvider]
val config = AllConf.withTestConfig("--zk_timeout", "1000")
val metricRegistry = new MetricRegistry()
val metrics = new Metrics(metricRegistry)
val actorId = new AtomicInteger(0)
val schedulerProvider = new Provider[DeploymentService] {
override def get() = service
}
private[this] val groupManagerModule = new GroupManagerModule(
config = config,
AlwaysElectedLeadershipModule.forActorSystem(system),
serializeUpdates = WorkQueue("serializeGroupUpdates", 1, 10),
scheduler = schedulerProvider,
groupRepo = groupRepository,
appRepo = appRepository,
podRepo = podRepository,
storage = provider,
eventBus = eventBus,
metrics = metrics)
val groupManager = groupManagerModule.groupManager
}
示例8: LircParserSpec
//设置package包名称以及导入依赖的类
package services
import javax.inject.Provider
import io.TestableProcessLogger
import org.scalatest.{FlatSpec, MustMatchers}
import org.scalamock.scalatest.MockFactory
import scala.sys.process._
class LircParserSpec extends FlatSpec with MustMatchers with MockFactory {
"The irsend command" should "find devices" in {
val process = mock[ProcessCreation]
val builder = mock[ProcessBuilder]
val provider = mock[Provider[TestableProcessLogger]]
val logger = mock[TestableProcessLogger]
(process.apply(_:String,_:Seq[String])).expects("irsend", Seq("list", "", "")).returns(builder)
(logger.processLogger _).expects().returns(null)
(logger.lines _).expects().returns(List("irsend: sony", "irsend: jvc"))
(provider.get _).expects().returns(logger)
(builder.lineStream_! (_: ProcessLogger)).expects(*)
val lircParser = new DefaultLircParser(process, provider)
lircParser.listDevices must be(Seq("sony", "jvc"))
}
it should "find buttons for a device" in {
val process = mock[ProcessCreation]
val builder = mock[ProcessBuilder]
val provider = mock[Provider[TestableProcessLogger]]
val logger = mock[TestableProcessLogger]
(process.apply(_:String,_:Seq[String])).expects("irsend", Seq("list", "sony", "")).returns(builder)
(logger.processLogger _).expects().returns(null)
(logger.lines _).expects().returns(List("irsend: 0000000000000481 KEY_VOLUMEUP", "irsend: 0000000000000c81 KEY_VOLUMEDOWN"))
(provider.get _).expects().returns(logger)
(builder.lineStream_! (_:ProcessLogger)).expects(*)
val lircParser = new DefaultLircParser(process, provider)
lircParser.listButtons("sony") must be(Seq("KEY_VOLUMEUP", "KEY_VOLUMEDOWN"))
}
it should "press buttons for a device" in {
val process = mock[ProcessCreation]
val builder = mock[ProcessBuilder]
val provider = mock[Provider[TestableProcessLogger]]
val logger = mock[TestableProcessLogger]
(process.apply(_:String,_:Seq[String])).expects("irsend", Seq("SEND_ONCE", "sony", "KEY_VOLUMEUP")).returns(builder)
(builder.! _).expects().returns(0)
val lircParser = new DefaultLircParser(process, null)
lircParser.pressButton("sony", "KEY_VOLUMEUP") must be(true)
}
}
示例9: ErrorHandler
//设置package包名称以及导入依赖的类
package ylabs.play.common
import java.io.{PrintWriter, StringWriter}
import javax.inject.{Inject, Provider}
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.{JsObject, JsString, Json, Writes}
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import play.api.routing.Router
import play.api.{Configuration, Environment, OptionalSourceMapper, UsefulException}
import ylabs.play.common.models.Helpers.ApiFailure.Failed
import ylabs.play.common.models.ValidationError.{Field, Invalid, Reason}
import scala.concurrent.Future
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
def prettyTrace(t: Throwable) = {
val sw = new StringWriter
t.printStackTrace(new PrintWriter(sw))
sw.toString
}
implicit def exceptionWrites: Writes[Throwable] = new Writes[Throwable] {
def writes(t: Throwable) = JsObject(Seq(
"message" -> JsString(t.getMessage),
"trace" -> JsString(prettyTrace(t))))
}
override def onDevServerError(request: RequestHeader, exception: UsefulException) = {
Future.successful(InternalServerError(Json.toJson(exception)))
}
override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
Future.successful(InternalServerError(Json.toJson("Internal Error")))
}
override def onBadRequest(request: RequestHeader, message: String) = {
def errorToMessage(error: String) = error match {
case "error.path.missing" ? "Value missing"
case _ ? error
}
//This is a bit of a mess because play doesn't allow invalid json to get to our client code
//Message will be something like "Json validation error List((obj.name,List(ValidationError(List(error.path.missing),WrappedArray()))))"
//So this extracts the field and reason
val errorRegex = """\(obj.([^,]+),List\(ValidationError\(List\(([^\)]+)""".r
val errors = errorRegex.findAllMatchIn(message) map { m ? Invalid(Field(m.group(1)), Reason(errorToMessage(m.group(2)))) }
val list = if(errors.nonEmpty) errors.toList else List(Invalid(Field("Unknown"), Reason(message)))
val failed = Failed(list)
Future.successful(BadRequest(Json.toJson(failed)))
}
}
示例10: ConsulServiceLocatorModule
//设置package包名称以及导入依赖的类
package com.lightbend.lagom.discovery.consul
import com.lightbend.lagom.javadsl.api.ServiceLocator
import play.api.{Configuration, Environment, Mode}
import play.api.inject.{Binding, Module}
import javax.inject.Singleton
import javax.inject.Inject
import javax.inject.Provider
import com.ecwid.consul.v1.ConsulClient
class ConsulServiceLocatorModule extends Module {
override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] =
if (environment.mode == Mode.Prod) Seq(
bind[ServiceLocator].to[ConsulServiceLocator].in[Singleton],
bind[ConsulConfig].to[ConsulConfig.ConsulConfigImpl],
bind[ConsulClient].toProvider[ConsulServiceLocatorModule.ConsulClientProvider]
)
else Seq.empty
}
object ConsulServiceLocatorModule {
private class ConsulClientProvider @Inject()(config: ConsulConfig) extends Provider[ConsulClient] {
override lazy val get: ConsulClient = new ConsulClient(config.agentHostname, config.agentPort)
}
}
示例11: SignatureResourceHandler
//设置package包名称以及导入依赖的类
package v1.signature
import java.util.Calendar
import javax.inject.{Inject, Provider}
import scala.concurrent.{ExecutionContext, Future}
import play.api.libs.json._
import scala.util.Random
class SignatureResourceHandler @Inject()(
routerProvider: Provider[SignatureRouter],
signatureRepository: SignatureRepository)(implicit ec: ExecutionContext) {
def create(signatureInput: SignatureFormInput): Future[SignatureResource] = {
val data = SignatureData(SignatureId(Random.nextInt(100000).toString), signatureInput.uri, Calendar.getInstance().getTimeInMillis)
// We don't actually create the post, so return what we have
signatureRepository.create(data).map { id =>
createPostResource(data)
}
}
def lookup(id: String): Future[Option[SignatureResource]] = {
val postFuture = signatureRepository.get(SignatureId(id))
postFuture.map { maybePostData =>
maybePostData.map { postData =>
createPostResource(postData)
}
}
}
def find: Future[Iterable[SignatureResource]] = {
signatureRepository.list().map { postDataList =>
postDataList.map(postData => createPostResource(postData))
}
}
private def createPostResource(p: SignatureData): SignatureResource = {
SignatureResource(p.id.toString, p.uri, p.date)
}
}
示例12: MetricRegistryProvider
//设置package包名称以及导入依赖的类
package microtools.metrics
import javax.inject.{Provider, Singleton}
import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.jvm.{
GarbageCollectorMetricSet,
MemoryUsageGaugeSet,
ThreadStatesGaugeSet
}
@Singleton
class MetricRegistryProvider extends Provider[MetricRegistry] {
private val registry = new MetricRegistry
registry.register("jvm.gc", new GarbageCollectorMetricSet)
registry.register("jvm.memory", new MemoryUsageGaugeSet)
registry.register("jvm.threads", new ThreadStatesGaugeSet)
override def get(): MetricRegistry = registry
}
示例13: RunnerConfigurationProvider
//设置package包名称以及导入依赖的类
package com.igorvovk.telegram.botapi.examples
import javax.inject.{Inject, Named, Provider, Singleton}
import akka.actor.{ActorSystem, Props}
import com.igorvovk.telegram.botapi._
import play.api.Configuration
import play.api.inject.Injector
@Singleton
class RunnerConfigurationProvider @Inject() (config: Configuration) extends Provider[RunnerConfiguration] {
lazy val get = {
val option = for {
ns <- config.getConfig("telegram.runner")
providerClass <- ns.getString("providerClass")
} yield {
RunnerConfiguration(
providerClass = providerClass
)
}
option.get
}
}
case class RunnerConfiguration(providerClass: String)
class RunnerBotProvider @Inject() (runnerConfiguration: RunnerConfiguration, injector: Injector) extends Provider[Props] {
def get() = {
injector.instanceOf(getClass(runnerConfiguration.providerClass, classOf[Provider[Props]])).get()
}
private def getClass[T](className: String, instanceOf: Class[T]) = {
Class.forName(className).asSubclass(instanceOf)
}
}
class Bootstrap @Inject() (system: ActorSystem, client: TelegramApiClient, @Named("bot_from_config") bot: Props) {
val logger = system.actorOf(SimpleMessageLoggerActor(), "message_logger")
val gate: Props = ChatGateActor(client, ChatGateActorConfig(bot, messageLogger = Some(logger)))
val emitter = system.actorOf(UpdatesEmitterActor(client), "emitter")
val router = system.actorOf(PerChatMessageRouterActor(gate), "router")
emitter ! UpdatesEmitterActor.AddSubscriber(router)
emitter ! UpdatesEmitterActor.StartReceivingUpdates
}
示例14: TelegramApiClientConfiguration
//设置package包名称以及导入依赖的类
package com.igorvovk.telegram.botapi
import javax.inject.{Inject, Provider, Singleton}
import play.api.Configuration
object TelegramApiClientConfiguration {
object Token {
def fromConfig(config: Configuration): Option[Token] = {
for {
id <- config.getLong("id")
secret <- config.getString("secret")
} yield Token(id, secret)
}
}
case class Token(id: Long, secret: String) {
lazy val str = s"$id:$secret"
}
def fromConfig(config: Configuration): TelegramApiClientConfiguration = {
val token = config.getConfig("bot.token").flatMap(Token.fromConfig).get
TelegramApiClientConfiguration(
credentials = token,
apiBaseUrl = config.getString("apiUrl").get + "/bot" + token.str,
downloadBaseUrl = config.getString("apiUrl").get + "/file/bot" + token.str,
receiveUpdatesTimeout = Some(90)
)
}
}
case class TelegramApiClientConfiguration(credentials: TelegramApiClientConfiguration.Token,
apiBaseUrl: String,
downloadBaseUrl: String,
receiveUpdatesTimeout: Option[Int])
@Singleton
class TelegramApiClientConfigurationProvider @Inject()(config: Configuration) extends Provider[TelegramApiClientConfiguration] {
lazy val get = TelegramApiClientConfiguration.fromConfig(config.getConfig("telegram").get)
}
示例15: Module
//设置package包名称以及导入依赖的类
import com.google.inject.AbstractModule
import javax.inject.{Inject, Provider}
import akka.actor.ActorSystem
import akka.stream.Materializer
import contexts._
import controllers.{CertificateDownloader, LetsEncryptWSClient}
import play.api.inject.ApplicationLifecycle
import play.api.libs.ws.WSClient
import play.api.{Configuration, Environment}
class Module(environment: Environment,
configuration: Configuration) extends AbstractModule {
override def configure() = {
bind(classOf[WSExecutionContext]).toProvider(classOf[WSExecutionContextProvider])
bind(classOf[DefaultExecutionContext]).toProvider(classOf[DefaultExecutionContextProvider])
bind(classOf[CertificateDownloader]).toProvider(classOf[CertificateDownloaderProvider])
bind(classOf[LetsEncryptWSClient]).toProvider(classOf[LetsEncryptWSClientProvider])
}
}
class DefaultExecutionContextProvider @Inject() (actorSystem: ActorSystem)
extends Provider[DefaultExecutionContext] {
lazy val get: DefaultExecutionContext = {
new DefaultExecutionContext(play.api.libs.concurrent.Execution.defaultContext)
}
}
class WSExecutionContextProvider @Inject() (actorSystem: ActorSystem)
extends Provider[WSExecutionContext] {
lazy val get: WSExecutionContext = {
new WSExecutionContext(actorSystem.dispatchers.lookup("dispatchers.ws"))
}
}
class CertificateDownloaderProvider @Inject()(ws: WSClient,
config:Configuration,
wsExecutionContext: WSExecutionContext)
extends Provider[CertificateDownloader] {
lazy val get: CertificateDownloader = {
new CertificateDownloader(ws, config)(wsExecutionContext)
}
}
class LetsEncryptWSClientProvider @Inject()(lifecycle: ApplicationLifecycle,
env: Environment)
(implicit mat: Materializer, wsEc: WSExecutionContext)
extends Provider[LetsEncryptWSClient] {
override lazy val get: LetsEncryptWSClient = new LetsEncryptWSClient(lifecycle, env)
}