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


Scala Singleton类代码示例

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


在下文中一共展示了Singleton类的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
  }
} 
开发者ID:oen9,项目名称:bard-api,代码行数:34,代码来源:CustomObjectMapperModule.scala

示例2: EventsController

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

import javax.inject.{Inject, Singleton}

import models.ZWayEvent
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.mvc.Action

import scala.concurrent.Future

@Singleton
class EventsController @Inject()(
  val messagesApi: MessagesApi
) extends ApiController {

  var events:List[ZWayEvent] = List.empty

  def home() = Action {
    Ok("RPi Play Framework ZWay demo")
  }

  def all() = Action {
    Ok(Json.toJson(events))
  }

  def create() = Action.async(apiJson[ZWayEvent]) { req =>
    val event = req.body
    logger.debug("postEvent: " + event)

    events = events :+ event
    Future.successful(Ok(Json.obj()))
  }

} 
开发者ID:LabCo,项目名称:rpi-zway-play,代码行数:36,代码来源:EventsController.scala

示例3: ApiController

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

import java.util.UUID
import javax.inject.{Inject, Singleton}

import models.RestResource
import play.api.libs.json.{JsError, JsValue, Json}
import play.api.mvc._

import scala.concurrent.Future

@Singleton
class ApiController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def index: Action[AnyContent] = {
    val resources = Seq(RestResource(UUID.randomUUID(), "name 1", "link 2"),
                        RestResource(UUID.randomUUID(), "name 2", "link 2"))
    Action.async {
      val json = Json.toJson(resources)
      Future.successful(Ok(json))
    }
  }

  def show(id: UUID): Action[AnyContent] = {
    Action.async {
      implicit request =>
        val json = Json.toJson(RestResource(id, "name x", "link x"))
        Future.successful(Ok(json))
    }
  }

  def process: Action[JsValue] = Action(parse.json) { implicit request =>
    request.body.validate[RestResource]
      .fold(
        errors =>
          BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors))),
        restResource => {
          println(restResource)
          Ok(Json.toJson(restResource))
        }
      )
  }

  def delete(id: String) = ???

  def update(id: String) = ???

} 
开发者ID:kamilduda,项目名称:play-hateoas,代码行数:49,代码来源:ApiController.scala

示例4: ScalaEventSourceController

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

import java.io.File

import play.Play
import java.nio.file.Paths
import javax.inject.{Inject, Singleton}

import play.api.http.ContentTypes
import play.api.libs.EventSource
import play.api.mvc._

@Singleton
class ScalaEventSourceController @Inject()(cc: ControllerComponents) extends AbstractController(cc) with ScalaTicker {

  def index() = Action {
    Ok(views.html.scalaeventsource())
  }

  def streamClock() = Action {
    Ok.chunked(stringSource via EventSource.flow).as(ContentTypes.EVENT_STREAM)
  }

  def upload = Action(parse.multipartFormData) { request =>
    request.body.file("picture").map { picture =>
      var basePath = "/app/public/upload/"

      var archivoTmp = new File(basePath)
      if(!archivoTmp.exists()) {
        basePath = Play.application().getFile("/public/upload/").getAbsolutePath() + File.separator;
      }

      val filename = picture.filename
      val contentType = picture.contentType
      picture.ref.moveTo(Paths.get(basePath + filename), replace = true)
      reiniciarSimulacion();
      Ok(views.html.scalaeventsource())
    }.getOrElse {
      Redirect(routes.ScalaEventSourceController.index).flashing(
        "error" -> "Missing file")
    }
  }

} 
开发者ID:juancamilogaviriaacosta,项目名称:proyecto-transmimetro-JuanGaviria-MauricioMontano,代码行数:45,代码来源:ScalaEventSourceController.scala

示例5: CustomCORSFilter

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

import javax.inject.{Inject, Singleton}

import akka.stream.Materializer
import play.api.http.HeaderNames
import play.api.mvc.{Filter, RequestHeader, Result}
import play.filters.cors.CORSFilter

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class CustomCORSFilter @Inject()(corsFilter: CORSFilter)
                                (implicit override val mat: Materializer,
                                 exec: ExecutionContext) extends Filter {

  override def apply(nextFilter: RequestHeader => Future[Result])
                    (requestHeader: RequestHeader): Future[Result] = {
    requestHeader.headers.get(HeaderNames.ORIGIN) match {
      case (Some("null")) =>
        val newHeaders = requestHeader.headers
          .remove(HeaderNames.ORIGIN)
          .add(HeaderNames.ORIGIN -> "http://file.url.local.null")
        val mappedOrigin = requestHeader.copy(headers = newHeaders)
        corsFilter(nextFilter)(mappedOrigin)
          .map { result =>
            result.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "null")
          }
      case _ => corsFilter(nextFilter)(requestHeader)
    }
  }
} 
开发者ID:umbc-cmcs447-grp,项目名称:rest-api,代码行数:34,代码来源:CustomCORSFilter.scala

示例6: UsersController

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

import javax.inject.{Inject, Singleton}

import database.UsersCollection
import models.User
import play.api.libs.json.JsValue
import play.api.mvc.{Action, BaseController, ControllerComponents}

import scala.concurrent.{ExecutionContext, Future}



@Singleton
class UsersController @Inject()(
  val controllerComponents: ControllerComponents,
  users: UsersCollection
)(implicit ec: ExecutionContext) extends BaseController {

  def create: Action[JsValue] = Action.async(parse.json) { request =>
    request.body.asOpt[User] match {
      case Some(user) => users.insert(user).map(if(_) Created else InternalServerError)
      case None => Future.successful(BadRequest)
    }
  }

  def read(id: String) = Action {
    users.find(id)
    Ok
  }

} 
开发者ID:WilliamJohnathonLea,项目名称:OAuth-Users,代码行数:33,代码来源:UsersController.scala

示例7: SignupController

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

import javax.inject.{Inject, Singleton}

import com.mohiva.play.silhouette.api.Silhouette
import forms.SignupForm
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.{Action, Controller, Flash}
import utils.auth.DefaultEnv


@Singleton
class SignupController @Inject()
(
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv]
) extends Controller with I18nSupport {

  def createUser = Action { implicit request =>
    println("trying to create!")
    SignupForm.form.bindFromRequest.fold(
      hasErrors = { form =>
        Redirect(routes.SignupController.registerPage())
          .flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
      },
      success = { signupData =>
        println(s"creating a new user $signupData")
        Redirect(routes.BookmarkController.list())
      }
    )
  }

  
  def registerPage = silhouette.UnsecuredAction { implicit request =>
    Ok(views.html.users.register(SignupForm.form))
  }
} 
开发者ID:lostMohican,项目名称:bookmaarket,代码行数:38,代码来源:SignupController.scala

示例8: PushService

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

import scala.Left
import scala.Right
import scala.concurrent.Future
import com.google.inject.ImplementedBy
import javax.inject.Inject
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import javax.inject.Singleton
import play.api.Configuration

@ImplementedBy(classOf[GcmPushService])
abstract class PushService {
  def sendMessage(message: PushMessage): Future[Either[String, Unit]]
}

@Singleton
class GcmPushService @Inject() (ws: WSClient, conf: Configuration) extends PushService {

  val endpoint = conf.getString("gcm.endpoint").get 
  val apiKey = conf.getString("gcm.apiKey").get 

  override def sendMessage(message: PushMessage): Future[Either[String, Unit]] = {

    val pushRequest = ws
      .url(endpoint)
      .withHeaders(
        "Content-Type" -> "application/json",
        "Authorization" -> s"key=$apiKey")

    pushRequest.post(Json.toJson(message)).map { pushResponse =>
      if (pushResponse.status >= 300) {
        Left(pushResponse.statusText)
      } else {
        Right(())
      }
    }

  }
} 
开发者ID:esurijon,项目名称:ravazzo-chat,代码行数:43,代码来源:PushService.scala

示例9: CategoryService

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

import javax.inject.{Inject, Singleton}

import domains.Category
import play.api.db._
import repositories.CategoryRepository

import scala.util.Try



@Singleton
class CategoryService @Inject()(db: Database, repository: CategoryRepository) {

  def insert(o: Category): Try[Option[Long]] = Try {
    db.withTransaction { implicit c =>
      repository.insert(o)
    }
  }

  def update(id: Int, o: Category): Try[Int] = Try {
    db.withTransaction { implicit c =>
      repository.update(id, o)
    }
  }

  def delete(id: Int): Try[Int] = Try {
    db.withTransaction { implicit c =>
      repository.delete(id)
    }
  }

  def findAll(): Try[List[Category]] = Try {
    db.withTransaction { implicit c =>
      repository.findAll()
    }
  }

  def findOne(id: Int): Try[Option[Category]] = Try {
    db.withTransaction { implicit c =>
      repository.findOne(id)
    }
  }

  def findByName(name: String): Try[List[Category]] = Try {
    db.withTransaction { implicit c =>
      repository.findByName(name)
    }
  }

  def findByParentId(parentId: Int): Try[List[Category]] = Try {
    db.withTransaction { implicit c =>
      repository.findByParentId(parentId)
    }
  }
} 
开发者ID:jasoet,项目名称:play-product-example,代码行数:58,代码来源:CategoryService.scala

示例10: index

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

import javax.inject.{Inject, Singleton}

import play.api.data.Form
import play.api.libs.json._
import play.api.libs.ws.WSClient
import play.api.mvc._
import play.api.data.Forms._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.concurrent.Future

@Singleton
class [email protected]()(wsClient:WSClient) extends Controller {

  implicit val resultFormat:Format[Result] = Json.format[Result]

  val userForm = Form(
    mapping(
      "name" -> nonEmptyText
    )(UserData.apply)(UserData.unapply)
  )

  def index = Action {
    Ok(views.html.index())
  }

  def processRequest(userData:UserData):Future[play.api.mvc.Result] =
    wsClient.url(s"http://localhost:8080/ninjaName/forUser/${userData.name}").get().map {
    case resp if resp.status == 200 =>  resp.json.validate match {
      case JsSuccess(res:Result,_) => Ok(views.html.ninjaName(res.result))
      case JsError(_) => InternalServerError("Unknown message format.")
    }
    case _ => InternalServerError("Error connecting to Ninja Name Generator API")
  }

  def createNinjaName = Action.async { implicit request =>
    userForm
      .bindFromRequest()
      .fold[Future[play.api.mvc.Result]](hasErrors = {
      formWithErrors => Future.successful(BadRequest(s"bad request, try again $formWithErrors"))
      },
        success = processRequest)
  }

}

case class UserData(name: String)
case class Result(result:String) 
开发者ID:nicocavallo,项目名称:ninja-name-generator-web,代码行数:51,代码来源:Application.scala

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

示例12: Aggregator

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

import play.api.mvc._
import ui.{HtmlStream, Pagelet}
import akka.actor.ActorSystem
import javax.inject.{Inject, Singleton}
import jp.t2v.lab.play2.auth.AuthElement
import frontend.{RegularUser, AuthorizationConfig}

@Singleton class Aggregator @Inject()(val conf: play.api.Configuration,
                                      //controller: TaxiController,
                                      rebCnt: ReboundLeaders, ptsCnt: PointsPerGameLeaders, daily: DailyResults,
                                      val system: ActorSystem) extends Controller
  with AuthElement with AuthorizationConfig
  with MaterializerSupport {

  val log: org.slf4j.Logger = akka.event.slf4j.Logger("aggregator")

  def index(stage: String) = StackAction(AuthorityKey -> RegularUser) { implicit request =>
    val user = loggedIn(request)
    log.info(s"aggregator ${user.login} -> ${request.uri}")

    val dailyStream = Pagelet.renderStream(daily.gateway("2016-02-10", user).map(views.html.daily.results(_)), "daily")
    val rebStream = Pagelet.renderStream(rebCnt.gateway(stage, user).map(views.html.leaders.reb(_)), "reb-lead")
    val prsStream = Pagelet.renderStream(ptsCnt.gateway(stage, user).map(views.html.leaders.pts(_)), "pts-lead")

    val body = HtmlStream.interleave(rebStream, prsStream, dailyStream)

    //TODO: use akka Source instead Enumerator

    import ui.HtmlStreamImplicits._
    Ok.chunked(views.stream.aggregatorBody(body))

  
  }
} 
开发者ID:haghard,项目名称:scenter-frontend,代码行数:37,代码来源:Aggregator.scala

示例13: DailyResult

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


import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import frontend.{Account, AuthorizationConfig}
import jp.t2v.lab.play2.auth.AuthElement
import play.api.libs.json.JsArray
import play.api.libs.ws.WSClient
import play.api.mvc.Controller

import scala.concurrent.Future



case class DailyResult(arena: String, guestTeam: String, homeTeam: String, guestScore: String, homeScore:String,
                       guestScoreLine:String, homeScoreLine:String, date: String)

@Singleton class DailyResults @Inject() (val conf: play.api.Configuration,
                              val ws: WSClient, val system: ActorSystem) extends Controller with AuthElement
  with AuthorizationConfig with GatewaySupport {

  override val key = "url.daily-results"

  override val log = akka.event.slf4j.Logger("daily-results")

  def gateway(stage: String, user: Account): Future[Seq[DailyResult]] = {
    val url = getUrl(key, stage)
    log.info(s"${user.login} -> $url")
    ws.url(url).withHeaders(authHeader -> user.token).get().flatMap { response =>
      response.status match {
        case OK => Future {
          (response.json \ "view").as[JsArray].value.map { item =>
            val teams = item.\("lineup").as[String].trim.split("@")
            val score = item.\("score").as[String].trim.split(" - ")
            val guestT = score(0).split(":")
            val guestFinalScore = guestT(1)
            val guestScoreLine = guestT(0)
            val homeT = score(1).split(":")
            val homeFinalScore = homeT(1)
            val homeScoreLine = homeT(0)
            DailyResult(item.\("arena").as[String], s"$picPref${teams(0).trim}.gif", s"$picPref${teams(1).trim}.gif",
              guestFinalScore, homeFinalScore, guestScoreLine, homeScoreLine,
              item.\("time").as[String])
          }
        }
        case FORBIDDEN => refreshGatewayToken[DailyResult](user, stage, gateway)
        case badCode => Future.successful(Seq.empty)
      }
    }
  }
} 
开发者ID:haghard,项目名称:scenter-frontend,代码行数:54,代码来源:DailyResults.scala

示例14: LoginController

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

import javax.inject.{Singleton, Inject}
import scala.concurrent.Future
import play.api.mvc._
import play.api.i18n._
import play.api.libs.concurrent.Execution.Implicits._

import models.UserForm
import dao.UserDAO
import values.session

@Singleton
class LoginController @Inject() (val messagesApi: MessagesApi, val user: UserDAO) extends Controller with I18nSupport {
  def index = Action {
    Ok(views.html.login(UserForm.form))
  }

  def login = Action.async { implicit request =>
    UserForm.form.bindFromRequest.fold(
      e => Future.successful(BadRequest(views.html.login(e))),
      input => {
        user.auth(input.email, input.password).map {
          case Some(u) if u.user_id.isDefined => Redirect(routes.HomeController.index())
            .withSession(session.SESSION_KEY -> u.user_id.get.toString)
          case None => Unauthorized(views.html.error("?????????????????????"))
        }
      }
    )
  }

  def logout = Action { implicit request =>
    Ok(views.html.index("?????????")).withNewSession
  }
} 
开发者ID:kogai,项目名称:kakei-log,代码行数:36,代码来源:LoginController.scala

示例15: VisitService

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

import com.sksamuel.elastic4s.{ HitAs, RichSearchHit }
import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.source.Indexable
import javax.inject.{ Inject, Singleton }
import play.api.Logger
import play.api.libs.json.Json
import scala.concurrent.{ Future, ExecutionContext }
import storage.ES

@Singleton
class VisitService @Inject() (implicit val es: ES, val ctx: ExecutionContext) {
  
  implicit object VisitIndexable extends Indexable[Visit] {
    override def json(v: Visit): String = Json.stringify(Json.toJson(v))
  }

  implicit object VisitHitAs extends HitAs[Visit] {
    override def as(hit: RichSearchHit): Visit =
      Json.fromJson[Visit](Json.parse(hit.sourceAsString)).get
  }
  
  def insertVisit(visit: Visit): Future[Unit] =
    es.client execute {
      index into ES.RECOGITO / ES.VISIT source visit
    } map { _ => 
    } recover { case t: Throwable =>
      Logger.error("Error logging visit event")
      val foo = t.printStackTrace
    }
    
  def countTotal(): Future[Long] =
    es.client execute {
      search in ES.RECOGITO / ES.VISIT limit 0
    } map { _.totalHits }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:39,代码来源:VisitService.scala


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