• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Provider类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中javax.inject.Provider的典型用法代码示例。如果您正苦于以下问题:Scala Provider类的具体用法?Scala Provider怎么用?Scala Provider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Provider类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
  }
} 
开发者ID:oen9,项目名称:bard-api,代码行数:34,代码来源:CustomObjectMapperModule.scala


示例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)
  }

} 
开发者ID:cleliofs,项目名称:play-scala-rest-api-example,代码行数:43,代码来源:PostResourceHandler.scala


示例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)
  }

} 
开发者ID:pelagios,项目名称:recogito2,代码行数:29,代码来源:ErrorHandler.scala


示例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)))
} 
开发者ID:tm-sukehiro,项目名称:play-hands-on,代码行数:41,代码来源:ErrorHandler.scala


示例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)
  }

} 
开发者ID:kapit4n,项目名称:play-news-api,代码行数:42,代码来源:PostResourceHandler.scala


示例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()
} 
开发者ID:playframework,项目名称:play-ws,代码行数:52,代码来源:WSConfigParser.scala


示例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
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:50,代码来源:TestGroupManagerFixture.scala


示例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)
  }
} 
开发者ID:jimnybob,项目名称:smartii-ir,代码行数:62,代码来源:LircParserSpec.scala


示例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)))
  }
} 
开发者ID:springnz,项目名称:play-app-base,代码行数:60,代码来源:ErrorHandler.scala


示例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)
  }
} 
开发者ID:jboner,项目名称:lagom-service-locator-consul,代码行数:30,代码来源:ConsulServiceLocatorModule.scala


示例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)
  }

} 
开发者ID:540,项目名称:etherlinks-backend,代码行数:44,代码来源:SignatureResourceHandler.scala


示例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
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:22,代码来源:MetricRegistryProvider.scala


示例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

} 
开发者ID:igorynia,项目名称:TelegramBotApi,代码行数:50,代码来源:Bootstrap.scala


示例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)
} 
开发者ID:igorynia,项目名称:TelegramBotApi,代码行数:44,代码来源:TelegramApiClientConfiguration.scala


示例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)

} 
开发者ID:wsargent,项目名称:play-ws-with-letsencrypt,代码行数:62,代码来源:Module.scala


示例16: KamonPlayExtensionsModule

//设置package包名称以及导入依赖的类
package au.com.agiledigital.kamon.play_extensions

import javax.inject.{Inject, Provider}

import akka.actor.ReflectiveDynamicAccess
import play.api.{Logger, Configuration, Environment}
import play.api.inject.{Binding, Module}

import scala.util.{Failure, Success}

class KamonPlayExtensionsModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq(
    bind[FutureNameGenerator].toProvider[FutureNameGeneratorProvider],
    bind[Metrics].to[MetricsSingleton].eagerly()
  )
}

class FutureNameGeneratorProvider @Inject()(configuration: Configuration) extends Provider[FutureNameGenerator] {

  private val configurationKey = "kamon.play-extensions.future-name-generator"

  private val dynamics = new ReflectiveDynamicAccess(getClass.getClassLoader)

  override def get(): FutureNameGenerator = {

    configuration.getString(configurationKey) flatMap { fcqn =>
      dynamics.createInstanceFor[FutureNameGenerator](fcqn, Nil) match {
        case Success(generator) => Some(generator)
        case Failure(error) =>
          Logger.warn(s"Failed to create future namer generator [$fcqn] from [$configurationKey].", error)
          None
      }
    } getOrElse new DefaultFutureNameGenerator()
  }
} 
开发者ID:agiledigital,项目名称:kamon-play-extensions,代码行数:36,代码来源:KamonPlayExtensionsModule.scala


示例17: SocketIOConfig

//设置package包名称以及导入依赖的类
package play.socketio

import play.api.Configuration

import scala.concurrent.duration._
import javax.inject.{ Inject, Provider, Singleton }


case class SocketIOConfig(
  ackDeadline:     FiniteDuration = 60.seconds,
  ackCleanupEvery: Int            = 10
)

object SocketIOConfig {
  def fromConfiguration(configuration: Configuration) = {
    val config = configuration.get[Configuration]("play.socket-io")
    SocketIOConfig(
      ackDeadline = config.get[FiniteDuration]("ack-deadline"),
      ackCleanupEvery = config.get[Int]("ack-cleanup-every")
    )
  }
}

@Singleton
class SocketIOConfigProvider @Inject() (configuration: Configuration) extends Provider[SocketIOConfig] {
  override lazy val get: SocketIOConfig = SocketIOConfig.fromConfiguration(configuration)
} 
开发者ID:playframework,项目名称:play-socket.io,代码行数:28,代码来源:SocketIOConfig.scala


示例18: ErrorHandler

//设置package包名称以及导入依赖的类
package com.clemble.loveit.common.controller

import com.clemble.loveit.common.error.ThankException
import javax.inject.{Singleton, Inject, Provider}
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import play.api.{Configuration, Environment, OptionalSourceMapper}

import scala.concurrent._

@Singleton
class ErrorHandler @Inject() (
                               env: Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: Provider[Router]
                             ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    exception match {
      case te: ThankException =>
        Future.successful(BadRequest(te))
      case exc =>
        super.onServerError(request, exc)
    }
  }

} 
开发者ID:thankyo,项目名称:thank,代码行数:31,代码来源:ErrorHandler.scala


示例19: CircuitBreakerModule

//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.javadsl.client

import javax.inject.{ Inject, Provider, Singleton }

import akka.actor.ActorSystem
import com.lightbend.lagom.internal.client.{ CircuitBreakerConfig, CircuitBreakerMetricsProviderProvider, CircuitBreakers }
import com.lightbend.lagom.internal.spi.CircuitBreakerMetricsProvider
import com.lightbend.lagom.javadsl.client.CircuitBreakersPanel
import play.api.inject.{ Binding, Module }
import play.api.{ Configuration, Environment }

class CircuitBreakerModule extends Module {

  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[CircuitBreakersPanel].to[CircuitBreakersPanelImpl],
      // for backward compatibility we still need to provide it for wiring
      bind[CircuitBreakers].toProvider[CircuitBreakersProvider],
      bind[CircuitBreakerMetricsProvider].toProvider[CircuitBreakerMetricsProviderProvider]
    )
  }
}

@Singleton
class CircuitBreakersProvider @Inject() (
  system:               ActorSystem,
  circuitBreakerConfig: CircuitBreakerConfig,
  metricsProvider:      CircuitBreakerMetricsProvider
) extends Provider[CircuitBreakers] {
  lazy val get = {

    // only in case some 3rd party lib are still wiring the old one.
    system.log.warning(
      "CircuitBreakers is deprecated, use CircuitBreakersPanel instead. This warning is probably caused by your " +
        "service locator. If you are using a 3rd party service locator, upgrade your dependencies, otherwise this " +
        "service locator could become incompatible with Lagom in future versions."
    )

    new CircuitBreakers(system, circuitBreakerConfig, metricsProvider)
  }
} 
开发者ID:lagom,项目名称:lagom,代码行数:42,代码来源:CircuitBreakerModule.scala


示例20: PostModule

//设置package包名称以及导入依赖的类
package post

import javax.inject.{Inject, Provider, Singleton}

import akka.actor.ActorSystem
import com.google.inject.AbstractModule
import com.lightbend.blog.comment._
import com.lightbend.blog.post._
import play.api.inject.ApplicationLifecycle

class PostModule extends AbstractModule {
  override def configure(): Unit = {
    bind(classOf[CommentRepository]).toProvider(classOf[CommentRepositoryProvider])
    bind(classOf[PostRepository]).toProvider(classOf[PostRepositoryProvider])
  }
}


@Singleton
class CommentRepositoryProvider @Inject()(applicationLifecycle: ApplicationLifecycle,
                                          actorSystem: ActorSystem)
  extends Provider[CommentRepository] {

  lazy val get: CommentRepository = {
    val repo = new CommentRepositoryImpl(executionContext)
    // Hooks the repository lifecycle to Play's lifecycle, so any resources are shutdown
    applicationLifecycle.addStopHook { () =>
      repo.stop()
    }
    repo
  }

  private def executionContext: CommentExecutionContext = {
    //val ec = actorSystem.dispatchers.lookup("post.dispatcher")
    val ec = actorSystem.dispatchers.defaultGlobalDispatcher
    new CommentExecutionContext(ec)
  }

} 
开发者ID:open-track,项目名称:journey-planner-scala,代码行数:40,代码来源:PostModule.scala



注:本文中的javax.inject.Provider类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Encoders类代码示例发布时间:2022-05-23
下一篇:
Scala Mock类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap