当前位置: 首页>>代码示例>>Scala>>正文


Scala Singleton类代码示例

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


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

示例1: User

//设置package包名称以及导入依赖的类
package com.bob.reservefund.scala.Controller

import com.bob.reservefund.scala.Service.UserService
import com.bob.reservefund.scala.Util.EnvironmentContext
import com.google.inject.{Inject, Singleton}
import com.twitter.finagle.http.Request
import com.twitter.finatra.annotations.Flag
import com.twitter.finatra.http.request.RequestUtils

import com.bob.reservefund.scala.Filter.WhichUserLoginContext._

case class User(name: String, id: Int, age: Int)

@Singleton
class UserController @Inject()(userService: UserService, @Flag("active.environment") env: String) extends FinatraController {

  get("/users", swagger(o => {
    o.summary("get all users")
      .description("return all users item")
      .tag("user")
      .produces("application/json")
      .responseWith[List[User]](200, "the response json", example = Some(List(User("bb", 1, 2))))
      .responseWith[Unit](404, "the address is not found")
  })) { request: Request =>
    println(request.user.id)
    info("users")
    List(User(env, -1, -1), User(RequestUtils.pathUrl(request), 1, 1), Hello(userService.dbusername, 2, 2), Hello(EnvironmentContext.get("mqconfig.maxTryTimes", "fuck"), 3, 1))
  }

  get("/properties", swagger(o => {
    o.summary("get all properties")
      .description("return all properties item")
      .tag("user")
      .produces("application/json")
      .responseWith[List[User]](200, "the response json", example = Some(List(User("bb", 1, 2))))
      .responseWith[Unit](404, "the address is not found")
  })) { request: Request =>
    EnvironmentContext.toMap
  }
} 
开发者ID:bobxwang,项目名称:ReserveFundService,代码行数:41,代码来源:UserController.scala

示例2: Field

//设置package包名称以及导入依赖的类
package de.htwg.se.scotlandyard.model.impl

import com.google.inject.Singleton
import de.htwg.se.scotlandyard.model.TField

import scala.collection.mutable.ListBuffer



@Singleton
case class Field() extends TField {

	override var fieldM = scala.collection.mutable.Map.empty[Int, Node]

	var stream = Field.getClass.getResourceAsStream("/Knoten.txt")
	for (line <- scala.io.Source.fromInputStream( stream ).getLines) {
		var data = line.split(" ")
		val pcon  : ListBuffer[(Int, String)] = ListBuffer()
		fieldM += (data(0).toInt -> Node(data(0).toInt,false,data(1).toInt,data(2).toInt, pcon))
	}

	stream = Field.getClass.getResourceAsStream("/Kanten.txt")
	for (line <- scala.io.Source.fromInputStream( stream ).getLines) {
		var data = line.split(" ")
		fieldM(data(0).toInt).pcon.+=:(data(1).toInt,data(2))
	}
	stream = Field.getClass.getResourceAsStream("/Kanten.txt")
	for (line <- scala.io.Source.fromInputStream( stream ).getLines) {
		var data = line.split(" ")
		fieldM(data(1).toInt).pcon.+=:(data(0).toInt,data(2))
	}

	override def reset = new Field()

	override def prettyPconList(fieldNo: Int): String = {
		var sb = new StringBuilder
		var i = 0
		val rfield = fieldM(fieldNo).pcon.toList
		sb.append("Possible Moves: \n")
		for (a <- 0 until rfield.length) {
			sb.append("(" + a + ")" + rfield(a) + "\n")
		}
		sb.toString()
	}
	override def toString = {
    var a = 199
    var sb = new StringBuilder()
    for (a <- 1 to 199) {
			if (fieldM(a).occ == true) {
				sb.append(fieldM(a).no.toString + " " + fieldM(a).occ.toString + "\n")
			}
    }
    sb.toString()
	}
} 
开发者ID:maximiliangraebel,项目名称:ScotlandYard,代码行数:56,代码来源:Field.scala

示例3: getUserID

//设置package包名称以及导入依赖的类
package dal.repositories.authentication

import com.google.inject.Singleton
import com.mongodb.casbah.Imports._
import com.mongodb.casbah.MongoCollection
import com.mongodb.casbah.commons.TypeImports._
import dal.Services
import dal.databases.MongoDBConfiguration

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global


trait AuthenticationRepository {
  def getUserID(username :String, password : String) : Option[String]
  def updateLogin(id : String) : String
}


@Singleton
class Authentication extends AuthenticationRepository  with Services {

  val collection : MongoCollection = MongoDBConfiguration.mongoCollections("meguide","users")

  def getUserID(username : String, password : String) : Option[String] = {
    val query = MongoDBObject("username" -> username, "password" -> password, "status" -> "active")
    val result : Option[DBObject] = collection.findOne(query)

    result match {
      case Some(x) => Some( updateLogin(x.get("_id") toString ))
      case None => None
    }
  }

  override def updateLogin(id : String) : String = {
    val goAsync : Future[Int] = scala.concurrent.Future {
      val query = MongoDBObject("_id" -> new ObjectId(id) )
      val update = MongoDBObject("$set" -> MongoDBObject("last_login" -> createTime) )
      val result = collection.update(query, update)
      result.getN
    }
    id
  }
} 
开发者ID:mubeenahmed,项目名称:MeGuideApi,代码行数:45,代码来源:AuthenticationRepository.scala

示例4: ActorClusterModule

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

import akka.actor.{ActorRef, ActorSystem}
import com.google.inject.Singleton
import akka.actor._
import com.google.inject._
import db.DaoAware
import play.api.{Configuration, Environment}


class ActorClusterModule extends play.api.inject.Module {
  def bindings(
    environment:   Environment,
    configuration: Configuration
  ) = Seq(
    play.api.inject.bind[ActorRef].qualifiedWith("people_actor").toProvider[PeopleActorProvider]
  )
}

@Singleton
class PeopleActorProvider @Inject() (system: ActorSystem, dao: DaoAware) extends Provider[ActorRef] {
  val props = Props(new PeopleActor(dao))

  lazy val get = system.actorOf(props, "people_actor")
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:26,代码来源:ActorClusterModule.scala

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

示例6: Application

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

import akka.actor._
import akka.pattern.AskTimeoutException
import com.google.inject.name.Named
import com.google.inject.{Inject, Singleton}
import play.api._
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc._
import scala.concurrent.Future
import scalaz.\/.left
import scalaz.{-\/, \/-}
import actors.Library
import actors.Library.{RequestBooks, BookData}
import entities.Book
import forms.SearchForm

@Singleton
class Application @Inject()(system: ActorSystem,
                            @Named("ndl-client-actor") ndlClient: ActorRef)
  extends Controller {
  import akka.pattern.ask
  import scala.concurrent.duration._

  def index = Action(Ok(views.html.index("Simple OPAC")))

  val bookForm = Form(
    mapping(
      "title"  -> optional(text),
      "author" -> optional(text),
      "any"    -> optional(text),
      "count"  -> optional(number(min = 1, max = 200))
    )(SearchForm.apply)(SearchForm.unapply)
  )

  implicit val bookToJson = Json.writes[Book]
  implicit val timeout: akka.util.Timeout = 1 minute
  lazy val libraryActor = system.actorOf(Library.props)

  def books = Action.async { implicit req =>
    bookForm.bindFromRequest.fold(
      formWithError => {
        Future.successful(BadRequest("invalid request"))
      },
      {
        case validForm => (try {
          libraryActor.ask(RequestBooks(validForm, ndlClient)).mapTo[BookData].map(_.books)
        } catch {
          case e: AskTimeoutException => Future.successful(left(s"Server Error: \n$e"))
          case _ => Future.successful(left("Something wrong..."))
        }).map {
          case \/-(books) => Ok(Json.toJson(books))
          case -\/(msg) => InternalServerError(msg)
        }
      }
    )
  }
} 
开发者ID:cedretaber,项目名称:simple-opac,代码行数:62,代码来源:Application.scala

示例7: Pong

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

import javax.inject.Inject

import com.github.ikhoon.swagger.SimpleSwaggerController
import com.google.inject.Singleton
import com.twitter.finagle.http.Request
import com.twitter.util.Future
import com.typesafe.config.Config

case class Pong(pong: String)

@Singleton
class PingController @Inject() (config: Config) extends SimpleSwaggerController {

  {
    get("/ping") { request: Request =>
      info("ping")
      Future.value(Pong("pong"))
    }
  }
} 
开发者ID:ikhoon,项目名称:finatra-mysql-seed,代码行数:23,代码来源:PingController.scala

示例8: ElectionDao

//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api.persistence.daos

import au.id.tmm.senatedb.api.services.exceptions.NoSuchElectionException
import au.id.tmm.senatedb.core.model.SenateElection
import com.google.common.collect.ImmutableBiMap
import com.google.inject.Singleton

import scala.concurrent.{ExecutionContext, Future}

@Singleton
object ElectionDao {

  // TODO needs scala implementation
  private val electionIdLookup: ImmutableBiMap[SenateElection, String] = ImmutableBiMap.of(
    SenateElection.`2016`, "2016",
    SenateElection.`2014 WA`, "2014WA",
    SenateElection.`2013`, "2013"
  )

  private val electionIdLookupByAecId: ImmutableBiMap[Int, String] = ImmutableBiMap.of(
    SenateElection.`2016`.aecID, electionIdLookup.get(SenateElection.`2016`),
    SenateElection.`2014 WA`.aecID, electionIdLookup.get(SenateElection.`2014 WA`),
    SenateElection.`2013`.aecID, electionIdLookup.get(SenateElection.`2013`)
  )

  def electionWithId(electionId: String): Option[SenateElection] = {
    Option(electionIdLookup.inverse.get(electionId.toUpperCase))
  }

  def idOf(election: SenateElection): Option[String] = {
    Option(electionIdLookup.get(election))
  }

  def idOf(aecElectionId: Int): Option[String] = {
    Option(electionIdLookupByAecId.get(aecElectionId))
  }

  def withParsedElection[A](electionId: String)(block: SenateElection => Future[A])
                           (implicit ec: ExecutionContext): Future[A] = {
    electionWithId(electionId) match {
      case Some(matchingElection) => block(matchingElection)
      case None => Future.failed(NoSuchElectionException(electionId))
    }
  }
} 
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:46,代码来源:ElectionDao.scala

示例9: EntityClassPopulator

//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api.persistence.population

import au.id.tmm.senatedb.api.persistence.daos.{DivisionDao, VoteCollectionPointDao}
import au.id.tmm.senatedb.core.model.DivisionsAndPollingPlaces
import au.id.tmm.senatedb.core.model.parsing.VoteCollectionPoint
import au.id.tmm.senatedb.core.tallies.Tally1
import com.google.inject.{Inject, Singleton}

import scala.concurrent.Future

@Singleton
class EntityClassPopulator @Inject() (divisionDao: DivisionDao, voteCollectionPointDao: VoteCollectionPointDao) {

  def populateDivisions(divisionsAndPollingPlaces: DivisionsAndPollingPlaces): Future[Unit] =
    divisionDao.write(divisionsAndPollingPlaces.divisions)

  def populatePollingPlaces(divisionsAndPollingPlaces: DivisionsAndPollingPlaces): Future[Unit] =
    voteCollectionPointDao.write(divisionsAndPollingPlaces.pollingPlaces)

  def populateOtherVoteCollectionPoints(formalBallotsByVoteCollectionPoint: Tally1[VoteCollectionPoint]): Future[Unit] = {
    val voteCollectionPoints = formalBallotsByVoteCollectionPoint.asMap.keys

    voteCollectionPointDao.write(voteCollectionPoints)
  }
} 
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:26,代码来源:EntityClassPopulator.scala

示例10: EntityPopulationChecker

//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api.persistence.population

import au.id.tmm.senatedb.core.model.SenateElection
import au.id.tmm.senatedb.api.persistence.daos.GeneralDao
import au.id.tmm.utilities.concurrent.FutureCollectionUtils.FutureSetOps
import com.google.inject.{Inject, Singleton}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class EntityPopulationChecker @Inject() (generalDao: GeneralDao)
                                        (implicit ec: ExecutionContext) {

  def unpopulatedOf(election: SenateElection, entityClasses: Set[PopulatableEntityClass]): Future[Set[PopulatableEntityClass]] = {
    entityClasses.filterEventually(isPopulatedAtElection(election, _).map(!_))
  }

  private def isPopulatedAtElection(election: SenateElection, entityClass: PopulatableEntityClass): Future[Boolean] = {
    entityClass match {
      case PopulatableEntityClass.Divisions => generalDao.divisionDao.hasAnyDivisionsFor(election)
      case PopulatableEntityClass.PollingPlaces => generalDao.voteCollectionPointDao.hasAnyPollingPlacesFor(election)
      case PopulatableEntityClass.OtherVoteCollectionPoints =>
        generalDao.voteCollectionPointDao.hasAnyNonPollingPlaceVoteCollectionPointsFor(election)
    }
  }

} 
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:28,代码来源:EntityPopulationChecker.scala

示例11: DbPopulationController

//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api.controllers

import au.id.tmm.senatedb.api.services.DbPopulationService
import au.id.tmm.senatedb.api.services.exceptions.NoSuchElectionException
import com.google.inject.{Inject, Singleton}
import play.api.mvc.{Action, AnyContent, Controller}

import scala.concurrent.ExecutionContext

@Singleton
class DbPopulationController @Inject()(dbPopulationService: DbPopulationService)
                                      (implicit ec: ExecutionContext) extends Controller {

  def populateFor(electionId: String): Action[AnyContent] = Action.async {
    dbPopulationService.beginPopulationFor(electionId)
      .map(_ => Ok(s"Begun populating for $electionId"))
      .recover {
        case _: NoSuchElectionException => NotFound(electionId) // TODO handle this with an application level error handler
        case e: DbPopulationService.Exceptions.AnotherElectionCurrentlyPopulatingException => Ok(s"Already populating ${e.election}")
      }
  }

  def checkPopulationStatusFor(electionId: String): Action[AnyContent] = Action.async {
    dbPopulationService.isElectionPopulated(electionId)
      .map(electionIsPopulated => Ok(electionIsPopulated.toString))
      .recover {
        case _: NoSuchElectionException => NotFound(electionId) // TODO handle this with an application level error handler
      }
  }
} 
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:31,代码来源:DbPopulationController.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: ChirpHandlerCache

//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.auth.handlers

import be.objectify.deadbolt.scala.cache.HandlerCache
import be.objectify.deadbolt.scala.{DeadboltHandler, HandlerKey}
import com.google.inject.{Inject, Singleton}

@Singleton
class ChirpHandlerCache @Inject()(val defaultHandler: ChirpDeadboltHandler) extends HandlerCache {
  case class ChirpKey(name: String) extends HandlerKey

  object HandlerKeys { val defaultHandler = ChirpKey("defaultHandler") }

  // HandlerKeys is an user-defined object, containing instances
  // of a case class that extends HandlerKey
  val handlers: Map[Any, DeadboltHandler] = Map(HandlerKeys.defaultHandler -> defaultHandler)

  // Get the default handler.
  override def apply(): DeadboltHandler = defaultHandler

  // Get a named handler
  override def apply(handlerKey: HandlerKey): DeadboltHandler = handlers(handlerKey)
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:23,代码来源:ChirpHandlerCache.scala

示例14: Handler

//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.errors

import com.google.inject.Singleton
import org.postgresql.util.PSQLException
import play.api.http.HttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._

import scala.concurrent._

@Singleton
class Handler extends HttpErrorHandler with JsonError {

  def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    Future.successful(
      Status(statusCode)("A client error occurred: " + message)
    )
  }

  def onServerError(request: RequestHeader, exception: Throwable) = {
    Future.successful(exception match {
      case ex: PSQLException => {
        BadRequest(jsonException("A database error has occurred.", ex))
      }
        // TODO: Fix this
//      case ex: AuthenticationFailedException => {
//        Unauthorized(jsonException("Invalid credentials.", ex))
//      }
      case ex: Exception => {
        InternalServerError(jsonException("An ISE has occurred.", ex))
    }})
  }
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:34,代码来源:Handler.scala

示例15: onStart

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

import com.google.inject.{Inject, Singleton}
import play.api.Logger
import scredis._

import scala.concurrent.Future

trait DatabaseServiceLike {
  def onStart(): Unit
  def onStop(): Unit
  def addSong(name: String, songId: String): Future[Boolean]
  def getSongId(name: String): Future[Option[String]]
}

@Singleton
class RedisDatabaseService @Inject() (
) extends DatabaseServiceLike {

  var redis: Redis = _

  def addSong(name: String, songId: String): Future[Boolean] = {
    Option(redis) map { r =>
      r.set(name, songId)
    } getOrElse {
      Logger.error("Redis not yet initialized, or has already shut down!")
      Future.successful(false)
    }
  }

  def getSongId(name: String): Future[Option[String]] = {
    Option(redis) map { r =>
      r.get(name)
    } getOrElse {
      Logger.error("Redis not yet initialized, or has already shut down!")
      Future.successful(None)
    }
  }

  def onStart(): Unit = {
    redis = Redis()
  }

  def onStop(): Unit = {
    redis.quit()
  }
} 
开发者ID:DenF923,项目名称:radio-playlist-service,代码行数:48,代码来源:IDatabaseService.scala


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