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

Scala Named类代码示例

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

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



在下文中一共展示了Named类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: DocumentService

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

import javax.inject.{Inject, Named}

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives._
import spray.json.DefaultJsonProtocol




@Named
class DocumentService @Inject()(documentRepository: DocumentRepository) extends DefaultJsonProtocol with SprayJsonSupport {

  val docRoutes =
    path("documents") {
      get {
        complete(documentRepository.getDocuments)
      }
    } ~
      path("document"/Segment  ) {
        r => complete(documentRepository.getDocument(r))
      } ~
      path("nowatermarks") {
        complete(documentRepository.getNoWatermarks)
      } ~
      path("nowatermark"/"""\w+""".r) {
        r => complete(documentRepository.getNoWatermark(r))
      }

} 
开发者ID:devknutst,项目名称:watermarkAkka,代码行数:32,代码来源:DocumentService.scala


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


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


示例4: NewsQueueClient

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

import javax.inject.{ Inject, Named }

import com.amazonaws.services.sqs.AmazonSQSClient
import com.amazonaws.services.sqs.model.ReceiveMessageRequest
import domain.common.{ MessageToken, ReceivedMessage }
import domain.news.NewsMessage
import infrastructure.config.NewsQueueConfig
import infrastructures.common.ReceivedMessageConverters
import play.api.Logger
import services.NewsQueue

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.{ Failure, Success, Try }

class NewsQueueClient @Inject()(
    sqsClient: AmazonSQSClient,
    config: NewsQueueConfig
)(implicit @Named("aws") ec: ExecutionContext) extends NewsQueue {

  override def receive: Future[List[ReceivedMessage[NewsMessage]]] = Future {
    import NewsMessageConverters.NewsMessageFormat

    import scala.collection.JavaConverters._

    Try {
      val req = new ReceiveMessageRequest(config.url)
      sqsClient.receiveMessage(req)
    } match {
      case Success(r) =>
        r.getMessages.asScala.toList map { message =>
          ReceivedMessageConverters.toReceivedMessage(message)(NewsMessageFormat)
        }
      case Failure(e) =>
        Logger.error("ReceiveMessage Failed.", e)
        throw new IllegalArgumentException(e)
    }


  }

  override def delete(token: MessageToken): Future[Unit] = Future {
    sqsClient.deleteMessage(config.url, token.identifier)
  }
} 
开发者ID:cm-wada-yusuke,项目名称:ecn-news,代码行数:47,代码来源:NewsQueueClient.scala


示例5: ScaleAppUpdateStepImpl

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.task.update.impl.steps
//scalastyle:off
import javax.inject.Named

import akka.Done
import akka.actor.ActorRef
import com.google.inject.{ Inject, Provider }
import mesosphere.marathon.MarathonSchedulerActor.ScaleRunSpec
import mesosphere.marathon.core.condition.Condition
import mesosphere.marathon.core.instance.update.{ InstanceChange, InstanceChangeHandler }
import org.slf4j.LoggerFactory

import scala.concurrent.Future
//scalastyle:on

class ScaleAppUpdateStepImpl @Inject() (
    @Named("schedulerActor") schedulerActorProvider: Provider[ActorRef]) extends InstanceChangeHandler {

  private[this] val log = LoggerFactory.getLogger(getClass)
  private[this] lazy val schedulerActor = schedulerActorProvider.get()

  private[this] def scalingWorthy: Condition => Boolean = {
    case Condition.Reserved | Condition.UnreachableInactive | _: Condition.Terminal => true
    case _ => false
  }

  override def name: String = "scaleApp"

  override def process(update: InstanceChange): Future[Done] = {
    // TODO(PODS): it should be up to a tbd TaskUnreachableBehavior how to handle Unreachable
    calcScaleEvent(update).foreach(event => schedulerActor ! event)
    Future.successful(Done)
  }

  def calcScaleEvent(update: InstanceChange): Option[ScaleRunSpec] = {
    if (scalingWorthy(update.condition) && update.lastState.forall(lastState => !scalingWorthy(lastState.condition))) {
      val runSpecId = update.runSpecId
      val instanceId = update.id
      val state = update.condition
      log.info(s"initiating a scale check for runSpec [$runSpecId] due to [$instanceId] $state")
      // TODO(PODS): we should rename the Message and make the SchedulerActor generic
      Some(ScaleRunSpec(runSpecId))
    } else {
      None
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:48,代码来源:ScaleAppUpdateStepImpl.scala


示例6: ThrottlingTaskStatusUpdateProcessor

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package core.task.update.impl

import javax.inject.{ Inject, Named }

import mesosphere.marathon.core.task.update.TaskStatusUpdateProcessor
import mesosphere.marathon.util.WorkQueue
import org.apache.mesos.Protos.TaskStatus

import scala.concurrent.{ ExecutionContext, Future }

object ThrottlingTaskStatusUpdateProcessor {
  
  final val dependencyTag = "ThrottlingTaskStatusUpdateProcessor"
}

private[core] class ThrottlingTaskStatusUpdateProcessor @Inject() (
  @Named(ThrottlingTaskStatusUpdateProcessor.dependencyTag) serializePublish: WorkQueue,
  @Named(ThrottlingTaskStatusUpdateProcessor.dependencyTag) wrapped: TaskStatusUpdateProcessor)
    extends TaskStatusUpdateProcessor {
  override def publish(status: TaskStatus): Future[Unit] = {
    serializePublish(wrapped.publish(status))(ExecutionContext.global)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:25,代码来源:ThrottlingTaskStatusUpdateProcessor.scala


示例7: FakeService

//设置package包名称以及导入依赖的类
package com.github.ikhoon.app.v1.fake

import javax.inject.{ Inject, Named }

import com.fasterxml.jackson.databind.JsonNode
import com.twitter.finatra.httpclient.{ HttpClient, RequestBuilder }
import com.twitter.util.{ Await, Duration, Future }
import com.typesafe.config.Config

class FakeService @Inject() (@Named("fake") httpClient: HttpClient, config: Config) {
  def withSleepAsync(sec: Int): Future[JsonNode] = {
    val url = s"/api/?sleep=$sec"
    httpClient.executeJson[JsonNode](RequestBuilder.get(url))
  }

  def withSleepSync(sec: Int): JsonNode = {
    val url = s"/api/?sleep=$sec"
    val jsonNode = httpClient.executeJson[JsonNode](RequestBuilder.get(url))
    Await.result(jsonNode, Duration.fromSeconds(100))
  }
} 
开发者ID:ikhoon,项目名称:finatra-mysql-seed,代码行数:22,代码来源:FakeService.scala


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


示例9: IssueTypeServiceImpl

//设置package包名称以及导入依赖的类
package com.nulabinc.backlog.migration.common.service

import javax.inject.{Inject, Named}

import com.nulabinc.backlog.migration.common.convert.Convert
import com.nulabinc.backlog.migration.common.domain.BacklogIssueType
import com.nulabinc.backlog.migration.common.utils.Logging
import com.nulabinc.backlog.migration.common.convert.writes.IssueTypeWrites
import com.nulabinc.backlog4j.api.option.AddIssueTypeParams
import com.nulabinc.backlog4j.{BacklogClient, Project}

import scala.collection.JavaConverters._


class IssueTypeServiceImpl @Inject()(implicit val issueTypeWrites: IssueTypeWrites, @Named("projectKey") projectKey: String, backlog: BacklogClient)
    extends IssueTypeService
    with Logging {

  override def allIssueTypes(): Seq[BacklogIssueType] =
    backlog.getIssueTypes(projectKey).asScala.map(Convert.toBacklog(_))

  override def add(issueType: BacklogIssueType): BacklogIssueType = {
    val params = new AddIssueTypeParams(projectKey, issueType.name, Project.IssueTypeColor.strValueOf(issueType.color))
    Convert.toBacklog(backlog.addIssueType(params))
  }

  override def remove(issueTypeId: Long, defaultIssueTypeId: Long) = {
    backlog.removeIssueType(projectKey, issueTypeId, defaultIssueTypeId)
  }

} 
开发者ID:nulab,项目名称:backlog-migration-common,代码行数:32,代码来源:IssueTypeServiceImpl.scala


示例10: IssueCategoryServiceImpl

//设置package包名称以及导入依赖的类
package com.nulabinc.backlog.migration.common.service

import javax.inject.{Inject, Named}

import com.nulabinc.backlog.migration.common.convert.Convert
import com.nulabinc.backlog.migration.common.convert.writes.CategoryWrites
import com.nulabinc.backlog.migration.common.domain.BacklogIssueCategory
import com.nulabinc.backlog.migration.common.utils.Logging
import com.nulabinc.backlog4j.BacklogClient
import com.nulabinc.backlog4j.api.option.AddCategoryParams

import scala.collection.JavaConverters._


class IssueCategoryServiceImpl @Inject()(implicit val categoryWrites: CategoryWrites,
                                         @Named("projectKey") projectKey: String,
                                         backlog: BacklogClient)
    extends IssueCategoryService
    with Logging {

  override def allIssueCategories(): Seq[BacklogIssueCategory] =
    backlog.getCategories(projectKey).asScala.map(Convert.toBacklog(_))

  override def add(backlogIssueCategory: BacklogIssueCategory): BacklogIssueCategory = {
    val params = new AddCategoryParams(projectKey, backlogIssueCategory.name)
    Convert.toBacklog(backlog.addCategory(params))
  }

  override def remove(issueCategoryId: Long) = {
    backlog.removeCategory(projectKey, issueCategoryId)
  }

} 
开发者ID:nulab,项目名称:backlog-migration-common,代码行数:34,代码来源:IssueCategoryServiceImpl.scala


示例11: VersionServiceImpl

//设置package包名称以及导入依赖的类
package com.nulabinc.backlog.migration.common.service

import javax.inject.{Inject, Named}

import com.nulabinc.backlog.migration.common.convert.Convert
import com.nulabinc.backlog.migration.common.convert.writes.VersionWrites
import com.nulabinc.backlog.migration.common.domain.BacklogVersion
import com.nulabinc.backlog.migration.common.utils.Logging
import com.nulabinc.backlog4j.BacklogClient
import com.nulabinc.backlog4j.api.option.{AddVersionParams, UpdateVersionParams}

import scala.collection.JavaConverters._


class VersionServiceImpl @Inject()(implicit val versionWrites: VersionWrites, @Named("projectKey") projectKey: String, backlog: BacklogClient)
    extends VersionService
    with Logging {

  override def allVersions(): Seq[BacklogVersion] =
    backlog.getVersions(projectKey).asScala.map(Convert.toBacklog(_))

  override def add(backlogVersion: BacklogVersion): Option[BacklogVersion] = {
    val params = new AddVersionParams(projectKey, backlogVersion.name)
    params.description(backlogVersion.description)
    for { startDate <- backlogVersion.optStartDate } yield {
      params.startDate(startDate)
    }
    for { releaseDueDate <- backlogVersion.optReleaseDueDate } yield {
      params.releaseDueDate(releaseDueDate)
    }
    try {
      Some(Convert.toBacklog(backlog.addVersion(params)))
    } catch {
      case e: Throwable =>
        logger.error(e.getMessage, e)
        None
    }
  }

  override def update(versionId: Long, name: String): Option[BacklogVersion] = {
    val params = new UpdateVersionParams(projectKey, versionId, name)
    try {
      Some(Convert.toBacklog(backlog.updateVersion(params)))
    } catch {
      case e: Throwable =>
        logger.error(e.getMessage, e)
        None
    }
  }

  override def remove(versionId: Long) = {
    backlog.removeVersion(projectKey, versionId)
  }

} 
开发者ID:nulab,项目名称:backlog-migration-common,代码行数:56,代码来源:VersionServiceImpl.scala


示例12: ProjectUserServiceImpl

//设置package包名称以及导入依赖的类
package com.nulabinc.backlog.migration.common.service

import javax.inject.{Inject, Named}

import com.nulabinc.backlog.migration.common.convert.Convert
import com.nulabinc.backlog.migration.common.domain.BacklogUser
import com.nulabinc.backlog.migration.common.utils.Logging
import com.nulabinc.backlog.migration.common.convert.writes.UserWrites
import com.nulabinc.backlog4j.{BacklogAPIException, BacklogClient}

import scala.collection.JavaConverters._


class ProjectUserServiceImpl @Inject()(implicit val userWrites: UserWrites, @Named("projectKey") projectKey: String, backlog: BacklogClient)
    extends ProjectUserService
    with Logging {

  override def allProjectUsers(projectId: Long): Seq[BacklogUser] = {
    try {
      backlog.getProjectUsers(projectId).asScala.map(Convert.toBacklog(_))
    } catch {
      case e: BacklogAPIException =>
        logger.error(e.getMessage, e)
        Seq.empty[BacklogUser]
    }
  }

  override def add(userId: Long) =
    backlog.addProjectUser(projectKey, userId)

} 
开发者ID:nulab,项目名称:backlog-migration-common,代码行数:32,代码来源:ProjectUserServiceImpl.scala


示例13: read

//设置package包名称以及导入依赖的类
package lert.core.config

import java.io.InputStream
import java.nio.file.{Files, Paths}
import javax.inject.{Inject, Named}

import com.fasterxml.jackson.databind.ObjectMapper

trait ConfigParser {
  def read(is: InputStream): Config
}

class JsonConfigParser @Inject()(objectMapper: ObjectMapper) extends ConfigParser {
  def read(is: InputStream): Config = {
    objectMapper.readValue(is, classOf[Config])
  }
}

trait ConfigProvider {
  def config: Config
}

class SimpleConfigProvider(val config: Config) extends ConfigProvider

object SimpleConfigProvider {
  def apply(config: Config) = new SimpleConfigProvider(config)
}

class FileConfigProvider @Inject()(configReader: ConfigParser,
                                   @Named("configFile") val configFile: String) extends ConfigProvider {
  override def config: Config = {
    val inputStream = Files.newInputStream(Paths.get(configFile))
    try {
      configReader.read(inputStream)
    } finally {
      inputStream.close()
    }
  }
} 
开发者ID:l3rt,项目名称:l3rt,代码行数:40,代码来源:ConfigProvider.scala


示例14: VoiceController

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

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

import actors.{FeedbackAggregatorActor, MonkeyActor, UserWebSocketActor}
import akka.actor.{ActorRef, ActorSystem}
import akka.stream.Materializer
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc._

@Singleton
class VoiceController @Inject()(@Named("feedbackActor") feedbackActor: ActorRef)
                               (implicit system: ActorSystem, materializer: Materializer) extends Controller {


  // Render basic page
  def index = Action { implicit request =>
    Ok(views.html.voice.the_voice())
  }

  def openWebSocket = WebSocket.accept[JsValue, JsValue] { request =>
    ActorFlow.actorRef(outActorRef => UserWebSocketActor.props(outActorRef, feedbackActor))
  }
} 
开发者ID:ChrisCooper,项目名称:customer-feedback-screen,代码行数:26,代码来源:VoiceController.scala


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


示例16: CachingDAO

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

import javax.inject.{Inject, Named}

import model.{Airport, Country, Runaway}
import play.api.cache._
import scala.concurrent.Future

class CachingDAO @Inject()(
                            @Named("appDAO") dao: DAO,
                            cache: CacheApi
                          ) extends DAO {


  override def allAirports(): Future[List[Airport]] = {
    val data = cache.getOrElse("allAirports")(dao.allAirports())
    data
  }

  override def allCountries(): Future[List[Country]] ={
    val data = cache.getOrElse("allCountries")(dao.allCountries())
    data
  }

  override def allRunaways(): Future[List[Runaway]] = {
    val data = cache.getOrElse("allRunaways")(dao.allRunaways())
    data
  }

  override def findAirportsByName(countryCode: String): Future[List[(Airport, List[Runaway])]] = {
    val data = cache.getOrElse(countryCode)(dao.findAirportsByName(countryCode))
    data
  }

  override def allCountriesSortedByNumberOfAirports(): Future[List[(Country, Int)]] = {
    val data = cache.getOrElse("allCountriesSortedByNumberOfAirports")(dao.allCountriesSortedByNumberOfAirports())
    data
  }

  override def typeOfSurfacesPerCountry(): Future[List[(Country, List[String])]] = {
    val data = cache.getOrElse("typeOfSurfacesPerCountry")(dao.typeOfSurfacesPerCountry())
    data
  }

  override def topIdentifications(): Future[List[(String, Int)]] = {
    val data = cache.getOrElse("topIdentifications")(dao.topIdentifications())
    data
  }
} 
开发者ID:MysterionRise,项目名称:airport-dangerzone,代码行数:50,代码来源:CachingDAO.scala


示例17: MongoUserSupportedProjectsRepo

//设置package包名称以及导入依赖的类
package com.clemble.loveit.thank.service.repository.mongo

import javax.inject.{Inject, Named}

import com.clemble.loveit.common.model.UserID
import com.clemble.loveit.common.mongo.MongoSafeUtils
import com.clemble.loveit.thank.service.repository.UserSupportedProjectsRepo
import com.clemble.loveit.user.model.UserIdentity
import play.api.libs.json.{JsObject, Json}
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.play.json._
import scala.concurrent.{ExecutionContext, Future}

class MongoUserSupportedProjectsRepo @Inject()(
                                                @Named("user") collection: JSONCollection,
                                                implicit val ec: ExecutionContext
                                              ) extends UserSupportedProjectsRepo {

  override def getRef(project: UserID): Future[Option[UserIdentity]] = {
    val selector = Json.obj("_id" -> project)
    val projection = Json.obj("id" -> 1, "firstName" -> 1, "lastName" -> 1, "thumbnail" -> 1, "dateOfBirth" -> 1)
    MongoSafeUtils.safe(collection.find(selector, projection).one[UserIdentity])
  }

  override def markSupported(supporter: UserID, project: UserIdentity): Future[Boolean] = {
    val selector = Json.obj("_id" -> supporter)
    val update = Json.obj("$addToSet" -> Json.obj("supported" -> project))
    MongoSafeUtils.safeSingleUpdate(collection.update(selector, update))
  }

  override def getSupported(supporter: UserID): Future[List[UserIdentity]] = {
    val selector = Json.obj("_id" -> supporter)
    val projection = Json.obj("supported" -> 1)
    MongoSafeUtils.safe(
      collection.
        find(selector, projection).
        one[JsObject].
        map(_.flatMap(json => (json \ "supported").asOpt[List[UserIdentity]]).getOrElse(List.empty[UserIdentity])))
  }

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


示例18: MongoUserResourceRepository

//设置package包名称以及导入依赖的类
package com.clemble.loveit.thank.service.repository.mongo

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

import akka.stream.Materializer
import com.clemble.loveit.common.model.UserID
import com.clemble.loveit.thank.model.{UserResource}
import com.clemble.loveit.thank.service.repository.{UserResourceRepository}
import play.api.libs.json.Json
import reactivemongo.play.json.collection.JSONCollection
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}


@Singleton
case class MongoUserResourceRepository @Inject()(@Named("user") collection: JSONCollection,
                                                implicit val m: Materializer,
                                                implicit val ec: ExecutionContext
                                               ) extends UserResourceRepository {

  override def find(user: UserID): Future[Option[UserResource]] = {
    val query = Json.obj("_id" -> user)
    val projection = Json.obj("id" -> 1, "owns" -> 1, "verification" -> 1)
    collection.find(query, projection).one[UserResource]
  }

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


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


示例20: MongoInvitationRepository

//设置package包名称以及导入依赖的类
package com.clemble.loveit.user.service.repository.mongo

import javax.inject.{Inject, Named}

import akka.stream.Materializer
import com.clemble.loveit.common.mongo.MongoSafeUtils
import com.clemble.loveit.user.model.Invitation
import com.clemble.loveit.user.service.repository.InvitationRepository
import play.api.libs.json.{JsObject, Json}
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.play.json._

import scala.concurrent.{ExecutionContext, Future}

class MongoInvitationRepository @Inject()(
                                           @Named("invitation") collection: JSONCollection,
                                           implicit val m: Materializer,
                                           implicit val ec: ExecutionContext
                                         ) extends InvitationRepository {

  override def save(inv: Invitation): Future[Invitation] = {
    val invJson = Json.toJson[Invitation](inv).as[JsObject]
    val fInsert = collection.insert(invJson)
    MongoSafeUtils.safe(inv, fInsert)
  }

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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala types类代码示例发布时间:2022-05-23
下一篇:
Scala Scheduler类代码示例发布时间: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