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

Scala Inject类代码示例

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

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



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

示例1: RootResponse

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

import javax.inject.Inject

import play.api.libs.json.Json
import play.api.mvc.Controller
import uk.gov.bis.levyApiMock.actions.AuthenticatedAction
import uk.gov.bis.levyApiMock.data.GatewayUserOps
import uk.gov.bis.levyApiMock.data.levy.Href

import scala.concurrent.ExecutionContext

case class RootResponse(_links: Map[String, Href], emprefs: Seq[String])

class RootController @Inject()(users: GatewayUserOps, authenticatedAction: AuthenticatedAction)(implicit ec: ExecutionContext) extends Controller {
  implicit def hrefW = Json.writes[Href]

  implicit def rootW = Json.writes[RootResponse]

  def root = authenticatedAction.async { request =>
    users.forGatewayID(request.authRecord.gatewayID).map {
      case Some(user) => Ok(Json.toJson(RootResponse(buildLinks(user.empref), user.empref.toSeq)))
      case _ => NotFound
    }
  }

  def buildLinks(empref: Option[String]): Map[String, Href] = {
    import views.html.helper.urlEncode
    Seq(
      Some("self" -> Href("/")),
      empref.map(e => e -> Href(s"/epaye/${urlEncode(e)}"))
    ).flatten.toMap
  }
} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:35,代码来源:RootController.scala


示例2: MerchantAreasDAOImpl

//设置package包名称以及导入依赖的类
package daos.merchant.impl

import java.util.UUID
import javax.inject.Inject

import models.{ MerchantAreas, ServeArea }
import daos.merchant.MerchantAreasDAO
import daos.util.ServeAreaDAO
import models.slick.SlickDAO
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class MerchantAreasDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider, serveAreaDAO: ServeAreaDAO) extends MerchantAreasDAO with SlickDAO {

  import driver.api._

  
  def save(userID: UUID, area: ServeArea) = {
    val dbMerchAreas = DBMerchantAreas(userID.toString, area.id)
    val act = (for {
      exist <- slickMerchantAreas += dbMerchAreas
    } yield ()).transactionally
    db.run(act).map { _ => area }

  }

  def clear(userID: UUID) = {
    val actions = for {
      merchants <- slickMerchantAreas.filter(_.merchantId === userID.toString)
    } yield merchants
    db.run(actions.delete).map(_ => MerchantAreas(Seq()))
  }

  def deleteOne(userID: UUID, serveArea: ServeArea) = {
    val actions = for {
      ma <- slickMerchantAreas.filter(ma => ma.merchantId === userID.toString && ma.areaId === serveArea.id)
    } yield ma
    db.run(actions.delete).map(_ => serveArea)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:41,代码来源:MerchantAreasDAOImpl.scala


示例3: MerchantCertificatesDAOImpl

//设置package包名称以及导入依赖的类
package daos.merchant.impl

import java.util.UUID
import javax.inject.Inject

import daos.merchant.MerchantCertificatesDAO
import models.slick.SlickDAO
import models.{ CertificateState, CertificateType, MerchantCertificate, MerchantCertificates }
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class MerchantCertificatesDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider) extends MerchantCertificatesDAO with SlickDAO {

  import driver.api._

  
  def save(userID: UUID, cert: MerchantCertificate) = {
    val dbCert = DBCertificates(None, cert.name, cert.description, cert.value, cert.certificate_type.id)
    val insertCertificate = slickCertificates.returning(slickCertificates.map(_.id)).
      into((cer, id) => cer.copy(certificateID = Some(id))) += dbCert
    val act = (for {
      certificate <- insertCertificate
      _ <- slickMerchantCertificates += DBMerchantCertificates(userID.toString, certificate.certificateID.get)
    } yield ()).transactionally
    db.run(act).map { _ => cert }
  }

  def clear(userID: UUID) = {
    val mc = slickMerchantCertificates.filter(_.merchantId === userID.toString)
    val c = slickCertificates.filter(_.id in mc.map(_.certificateId))
    db.run((mc.delete andThen c.delete).transactionally).map(_ => MerchantCertificates(Seq()))
  }

  def deleteOne(userID: UUID, cert: MerchantCertificate) = {
    val actions = for {
      ma <- slickMerchantCertificates.filter(ma => ma.merchantId === userID.toString && ma.certificateId === cert.id)
    } yield ma
    db.run(actions.delete).map(_ => cert)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:41,代码来源:MerchantCertificatesDAOImpl.scala


示例4: StoryController

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

import controllers.StoryModel.StoryData
import javax.inject.Inject

import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import model.StoryDao
import model.DataModel.Story

import scala.collection.mutable.ListBuffer

class StoryController @Inject()(implicit storyDao:StoryDao,config:Configuration) extends Controller{

  def index = Action {
    val result = storyDao.create();

    Ok(views.html.story("Welcome to StoryBoard !!",listStory))
  }

  def createStory = Action { implicit Request =>
    var result = storyDao.insert(new Story(storyForm.bindFromRequest().get.title,storyForm.bindFromRequest().get.description))
    Ok(views.html.story("Story Created:" + "(" + storyForm.bindFromRequest().get.title + "," + storyForm.bindFromRequest().get.description + ")",listStory))

  }

  def listStory:List[StoryData] = {
    val stories:List[Story] = storyDao.list
    var storiesData = new ListBuffer[StoryData]
    for(s <- stories){
      storiesData += (new StoryData(s.title,s.description))
    }
    storiesData.toList
  }

  val storyForm = Form(
    mapping(
      "title" -> text,
      "description" -> text
    )(StoryData.apply)(StoryData.unapply)
  )

}

object StoryModel{
  case class StoryData(
                      title:String,
                      description:String
                      )
} 
开发者ID:rajat965ng,项目名称:storyBoard,代码行数:53,代码来源:StoryController.scala


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


示例6: TimeCostInput

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

import javax.inject.Inject

import com.shouldioptimize.model.{Ec2Pricing, PreTaxHourlyTimeCostModel}
import play.api.cache.Cached
import play.api.data.Forms._
import play.api.data._
import play.api.data.validation.{Constraint, Invalid, Valid, ValidationResult}
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._

case class TimeCostInput(programmerHourCost: BigDecimal, instanceType: String)

class Application @Inject()(val messagesApi: MessagesApi, cached: Cached) extends Controller with I18nSupport {
  val validInstanceType = Constraint[String] ({
    case it if Ec2Pricing.all.contains(it) => Valid
    case _ => Invalid("invalid instance type")
  }: PartialFunction[String,ValidationResult])

  val TimeCostInputForm = Form(
    mapping(
      "programmerHourCost" -> bigDecimal,
      "instanceType" -> text.verifying(validInstanceType)
    )(TimeCostInput.apply)(TimeCostInput.unapply))

  private val DefaultProgrammerHourCost = BigDecimal("42.88")
  private val DefaultInstanceType = "t2.large"
  private val DefaultForm = TimeCostInputForm.fill(TimeCostInput(BigDecimal("42.88"), DefaultInstanceType))

  def index = cached.status(_ => "/index", OK, 60) {
    Action {
      Ok(views.html.results(new PreTaxHourlyTimeCostModel(BigDecimal("42.88")).calculate.values, DefaultForm))
    }
  }

  def results = Action { request =>
    val form = TimeCostInputForm.bind(request.queryString.mapValues(_.head))
    form.fold(
      formWithErrors => BadRequest(views.html.results(new PreTaxHourlyTimeCostModel(DefaultProgrammerHourCost).calculate.values, formWithErrors)),
      timeCostInput => Ok(views.html.results(new PreTaxHourlyTimeCostModel(timeCostInput.programmerHourCost).calculate.values, form))
    )
  }

  def why = cached.status(_ => "/why", OK, 60) {
    Action {
      Ok(views.html.why())
    }
  }

} 
开发者ID:ostewart,项目名称:shouldioptimize,代码行数:52,代码来源:Application.scala


示例7: ProjectServiceImpl

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

import javax.inject.Inject

import com.nulabinc.backlog.migration.common.convert.Convert
import com.nulabinc.backlog.migration.common.convert.writes.ProjectWrites
import com.nulabinc.backlog.migration.common.domain.BacklogProject
import com.nulabinc.backlog.migration.common.utils.Logging
import com.nulabinc.backlog4j.api.option.CreateProjectParams
import com.nulabinc.backlog4j.{BacklogAPIException, BacklogClient, Project}


class ProjectServiceImpl @Inject()(implicit val projectWrites: ProjectWrites, backlog: BacklogClient) extends ProjectService with Logging {

  override def create(project: BacklogProject): Either[Throwable, BacklogProject] =
    optProject(project.key) match {
      case Some(project) => Right(project)
      case _             => doCreate(project)
    }

  override def optProject(projectKey: String): Option[BacklogProject] =
    try {
      Some(Convert.toBacklog(backlog.getProject(projectKey)))
    } catch {
      case e: BacklogAPIException =>
        if (!(e.getMessage.contains("No project") || e.getMessage.contains("No such project"))) {
          logger.error(e.getMessage, e)
        }
        None
    }

  private[this] def doCreate(project: BacklogProject): Either[Throwable, BacklogProject] = {
    val params = new CreateProjectParams(
      project.name,
      project.key,
      project.isChartEnabled,
      project.isSubtaskingEnabled,
      Project.TextFormattingRule.enumValueOf(project.textFormattingRule)
    )
    try {
      Right(Convert.toBacklog(backlog.createProject(params)))
    } catch {
      case e: Throwable =>
        Left(e)
    }
  }

  override def projectOfKey(projectKey: String): BacklogProject =
    Convert.toBacklog(backlog.getProject(projectKey))

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


示例8: CustomerCertificatesDAOImpl

//设置package包名称以及导入依赖的类
package daos.customer.impl

import java.util.UUID
import javax.inject.Inject

import daos.customer.CustomerCertificatesDAO
import models.slick.SlickDAO
import models.{ CertificateState, _ }
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class CustomerCertificatesDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider) extends CustomerCertificatesDAO with SlickDAO {

  import driver.api._

  
  def save(userID: UUID, cert: Certificate) = {
    val act = (for {
      _ <- slickCustomerCertificates += DBCustomerCertificates(userID.toString, cert.id, cert.code, cert.state.id, cert.bought_at, cert.expires_at)
    } yield ()).transactionally
    db.run(act).map { _ => cert }
  }

  def clear(userID: UUID) = {
    val cc = slickCustomerCertificates.filter(_.customerId === userID.toString)
    db.run(cc.delete.transactionally).map(_ => CustomerCertificates(Seq()))
  }

  def deleteOne(userID: UUID, certID: Int) = {
    val actions = for {
      ma <- slickCustomerCertificates.filter(ma => ma.customerId === userID.toString && ma.certificateId === certID)
    } yield ma
    db.run(actions.delete).map(_ => certID)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:36,代码来源:CustomerCertificatesDAOImpl.scala


示例9: ServeAreaDAOImpl

//设置package包名称以及导入依赖的类
package daos.util.impl

import javax.inject.Inject

import daos.util.ServeAreaDAO
import models.ServeArea
import models.slick.SlickDAO
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class ServeAreaDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider) extends ServeAreaDAO with SlickDAO {

  import driver.api._

  def findByName(name: String) = {
    val query = for {
      dbArea <- slickServeAreas.filter(_.name === name)
    } yield dbArea
    db.run(query.result.headOption).map { resultOption =>
      resultOption.map {
        case area =>
          ServeArea(
            id = area.areaID,
            name = area.name,
            description = area.description
          )
      }
    }
  }

  def find(areaID: Int) = {
    val query = for {
      dbArea <- slickServeAreas.filter(_.id === areaID)
    } yield dbArea
    db.run(query.result.headOption).map { resultOption =>
      resultOption.map {
        case area =>
          ServeArea(
            id = area.areaID,
            name = area.name,
            description = area.description
          )
      }
    }
  }

  def allServeAreas = db.run(slickServeAreas.map(_.name).result)

} 
开发者ID:Bakuchi,项目名称:certification,代码行数:50,代码来源:ServeAreaDAOImpl.scala


示例10: CityDAOImpl

//设置package包名称以及导入依赖的类
package daos.util.impl

import javax.inject.Inject

import daos.util.CityDAO
import models.City
import models.slick.SlickDAO
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext


class CityDAOImpl @Inject() (protected val dbConfigProvider: DatabaseConfigProvider) extends CityDAO with SlickDAO {

  import driver.api._

  def findByName(name: String) = {
    val query = for {
      dbCity <- slickCity.filter(_.name === name)
    } yield dbCity
    db.run(query.result.headOption).map { resultOption =>
      resultOption.map {
        case city =>
          City(
            city.cityID,
            city.name)
      }
    }
  }

  def find(cityID: Int) = {
    val query = for {
      dbCity <- slickCity.filter(_.id === cityID)
    } yield dbCity
    db.run(query.result.headOption).map { resultOption =>
      resultOption.map {
        case city =>
          City(
            city.cityID,
            city.name)
      }
    }
  }
  def allCityNames = {
    val query = slickCity.map(_.name)
    db.run(query.result)
  }
} 
开发者ID:Bakuchi,项目名称:certification,代码行数:48,代码来源:CityDAOImpl.scala


示例11: ContactUsController

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

import javax.inject.Inject

import model.ContactFormTemplate
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import play.api.Play.current
import play.api.data.validation._
import play.api.i18n.Messages.Implicits._
import services._

import scala.concurrent.Future

class ContactUsController @Inject()(validator: Validation) extends Controller  {

  val contactUsForm: Form[ContactFormTemplate] = Form(
    mapping(
      "name" -> nonEmptyText(maxLength = 20),
      "email" -> nonEmptyText(maxLength = 30).verifying(validator.emailCheckConstraint),
      "description" -> nonEmptyText(maxLength = 50)
    )(ContactFormTemplate.apply)(ContactFormTemplate.unapply)
  )

  def entry = Action {
    Ok(views.html.contact(contactUsForm))
  }

  def postForm = Action.async { implicit request =>
    println(request.body)
    contactUsForm.bindFromRequest.fold(
      formWithErrors => {
        Future.successful(BadRequest(views.html.contact(formWithErrors)))
      },
      UserData => {
        Future.successful(Redirect(routes.ContactUsController.success(UserData.name, UserData.email, UserData.description)))
      }
    )
  }

  def success(name: String, email: String, description: String) = Action {
    Ok(views.html.contactFormConfirmation(name, email, description))
  }
} 
开发者ID:ZDevelop94,项目名称:ZolvedIT,代码行数:46,代码来源:ContactUsController.scala


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


示例13: ChangePasswordController

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.exceptions.ProviderException
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util.{ Credentials, PasswordHasherRegistry, PasswordInfo }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import models.services.UserService
import play.api.i18n.{ I18nSupport, Messages, MessagesApi }
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.Controller
import utils.auth.{ DefaultEnv, WithProvider }

import scala.concurrent.Future

class ChangePasswordController @Inject() (
  val messagesApi: MessagesApi,
  silhouette: Silhouette[DefaultEnv],
  userService: UserService,
  credentialsProvider: CredentialsProvider,
  authInfoRepository: AuthInfoRepository,
  passwordHasherRegistry: PasswordHasherRegistry
)
  extends Controller with I18nSupport {

  def view = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)) { implicit request =>
    Ok(views.html.changePassword(new myform.MyChangePasswordForm(), request.identity))
  }

  def submit = silhouette.SecuredAction(WithProvider[DefaultEnv#A](CredentialsProvider.ID)).async { implicit request =>
    new myform.MyChangePasswordForm().bindFromRequest match {
      case form: myform.MyChangePasswordForm => Future.successful(BadRequest(views.html.changePassword(form, request.identity)))
      case data: myform.MyChangePasswordFormData => {
        val (currentPassword, newPassword) = (data.currentPassword, data.newPassword)
        val credentials = Credentials(request.identity.email.getOrElse(""), currentPassword)
        credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
          val passwordInfo = passwordHasherRegistry.current.hash(newPassword)
          authInfoRepository.update[PasswordInfo](loginInfo, passwordInfo).map { _ =>
            Redirect(routes.ChangePasswordController.view()).flashing("success" -> Messages("password.changed"))
          }
        }.recover {
          case e: ProviderException =>
            Redirect(routes.ChangePasswordController.view()).flashing("error" -> Messages("current.password.invalid"))
        }
      }
    }
  }
} 
开发者ID:serversideapps,项目名称:silhmojs,代码行数:51,代码来源:ChangePasswordController.scala


示例14: Users

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

import javax.inject.Inject

import org.joda.time.DateTime
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc.{Action, BodyParsers, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import repos.UserRepoImpl



class Users @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents{

  import models.UserFields._

  def userRepo = new UserRepoImpl(reactiveMongoApi)

  def create = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim Anlegen
    implicit request =>
      val name = (request.body \ Name).as[String]
      val password = (request.body \ Password).as[String]
      val email = (request.body \ EMail).as[String]
      userRepo.save(BSONDocument(
        Name -> name,
        Password -> password,
        EMail -> email,
        CreatedAt -> DateTime.now.toString
      )).map(result => Created("Created"))
  }

  def read(id: String) = Action.async{ implicit request =>
    userRepo.select(BSONDocument(Id -> BSONObjectID(id))).map(exercise => Ok(Json.toJson(exercise)))
  }


  def update(id: String) = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim updaten
    implicit request =>
      val name = (request.body \ Name).asOpt[String]
      val password = (request.body \ Password).asOpt[String]
      val email = (request.body \ EMail).asOpt[String]
      userRepo.update(BSONDocument( Id -> BSONObjectID(id)),
        BSONDocument("$set" -> BSONDocument(
          Name -> name,
          Password -> password,
          EMail -> EMail
      ))).map(result => Accepted)
  }

  def delete(id: String) = Action.async{
    userRepo.remove(BSONDocument(Id -> BSONObjectID(id))).map(result => Accepted("Deleted: "+ id ))
  }

} 
开发者ID:NorbertEbenhoeh,项目名称:projectX,代码行数:58,代码来源:Users.scala


示例15: TweetCometController

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

import javax.inject.Inject

import akka.stream.Materializer
import play.api.Configuration
import play.api.http.ContentTypes
import play.api.libs.Comet
import play.api.libs.json._
import play.api.mvc._
import repositories.TweetRepository
import services.{PersistenceService, TweetService}


class TweetCometController @Inject()(materializer: Materializer,
                                     config: Configuration,
                                     tweetRepository: TweetRepository,
                                     tweetService: TweetService,
                                     persistenceService: PersistenceService) extends Controller {

  private lazy val searchTerms = config.getStringSeq("tweet.tags").getOrElse(Seq(""))

  def tweetComet = Action {
    implicit val mat = materializer
    def content = tweetService
      .createSearchSource(searchTerms)
      .map { s => Option(s.getText).getOrElse("") }
      .via(persistenceService.stringPersister(tweetRepository.insert))
      .map { s => JsString(s) }
      .via(Comet.json("parent.cometMessage"))
    Ok.chunked(content).as(ContentTypes.HTML)
  }
} 
开发者ID:snackCake,项目名称:TweetStreamChallenge,代码行数:34,代码来源:TweetCometController.scala


示例16: newCtx

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

import javax.inject.Inject

import io.opentracing.{References, Tracer}

trait CtxFactory {
    def newCtx(name: String)(implicit from: Option[Ctx] = None, fromKind: String = References.CHILD_OF): Ctx
    def startCtx(ctx: Ctx): Ctx
    def finishCtx(ctx: Ctx): Ctx
}


class CtxFactorySpanOnly @Inject()(tracer: Tracer) extends CtxFactory {
    def newCtx(name: String)(implicit from: Option[Ctx] = None, fromKind: String = References.CHILD_OF): Ctx = {
        val bs = tracer.buildSpan(name)
        from.foreach { fromCtx =>
            bs.addReference(fromKind, fromCtx.span.context())
        }
        val span = bs.start()
        CtxSpanOnly(span)
    }
    def startCtx(ctx: Ctx): Ctx = {
        ctx
    }
    def finishCtx(ctx: Ctx): Ctx = {
        ctx.span.finish()
        ctx
    }
} 
开发者ID:davidB,项目名称:sandbox_context_scala,代码行数:31,代码来源:CtxFactory.scala


示例17: Products

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

import play.api.mvc._
import javax.inject.Inject
import play.api.i18n.{Messages, MessagesApi, I18nSupport}
import play.api.data.Form
import play.api.data.Forms.{mapping, longNumber, nonEmptyText}
import models.Product

class Products @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
  def list = Action { implicit request =>
    val products = Product.findAll
    Ok(views.html.products.list(products))
  }

  def show(ean: Long) = Action {
    implicit request => Product.findByEan(ean).map {
      // rendering product details
      product => Ok(views.html.products.details(product))
    }.getOrElse(NotFound)  // return page 404
  }

  private val productForm: Form[Product] = Form(
    mapping(
      "ean" -> longNumber.verifying("validation.ean.duplicate", Product.findByEan(_).isEmpty),  // form? field? ????
      "name" -> nonEmptyText,
      "description" -> nonEmptyText
    )(Product.apply)(Product.unapply) // form? model ?? mapping
  )

  def save = Action {
    implicit request => val newProductForm = productForm.bindFromRequest()

    newProductForm.fold(
      hasErrors = {
        form => Redirect(routes.Products.newProduct()).
          flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
      },
      success = {
        newProduct => Product.add(newProduct)
        val message = Messages("products.new.success", newProduct.name)
        Redirect(routes.Products.show(newProduct.ean)).flashing("success" -> message)
      }
    )
  }

  def newProduct = Action {
    implicit request => val form = if (request2flash.get("error").isDefined)
      productForm.bind(request2flash.data)
    else
      productForm

    Ok(views.html.products.editProduct(form))
  }
} 
开发者ID:makeajourney,项目名称:play-products-example,代码行数:56,代码来源:Products.scala


示例18: StashController

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

import javax.inject.{Inject, Singleton}

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc
import play.api.mvc.{Action, AnyContent, Controller, Result}
import services.{Constants, JsonConverter, Stash, StashStore}

import scala.concurrent.Future


@Singleton
class StashController @Inject()(stashStore: StashStore, jsonConverter: JsonConverter) extends Controller {

  def addStash = Action.async(request => {
    validateStashAndRespond(request, (stash) => stashStore.addStash(stash).map(addedStash => Ok(Json.toJson[Stash](addedStash))))
  })

  def index = Action.async(request => {
    stashStore.getStashes().map(stashes => Ok(Json.toJson(stashes)))
  })

  def getStash(id: String) = Action.async(request =>
    stashStore.getStash(id).map {
      case Some(retrievedStash) => Ok(Json.toJson[Stash](retrievedStash))
      case None => NotFound
    }
  )

  def updateStash = Action.async(request => {
    validateStashAndRespond(request, (stash) => stashStore.updateStash(stash).map(updatedStash => Ok(Json.toJson[Stash](updatedStash))))
  })

  private def validateStashAndRespond(request: mvc.Request[AnyContent], responseAction: (Stash) => Future[Result]): Future[Result] = {
    request.body.asJson match {
      case None => Future.successful(BadRequest(Constants.noValidJsonMessage))
      case Some(json) =>
        val stash = jsonConverter.getStashFromRequestBody(json)
        stash match {
          case Some(value) => responseAction(value)
          case None => Future.successful(BadRequest(json))
        }
    }
  }
} 
开发者ID:dgrald,项目名称:locals-only-service-play,代码行数:48,代码来源:StashController.scala


示例19: StashStore

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

import javax.inject.Inject

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.Future


class StashStore @Inject()(val reactiveMongoApi: ReactiveMongoApi) {

  implicit val locationFormat: OFormat[Stash] = new OFormat[Stash] {
    override def writes(o: Stash): JsObject = Json.obj("_id" -> o._id, "stash" -> Stash.stashWrites.writes(o))

    override def reads(json: JsValue): JsResult[Stash] = Stash.stashReads.reads((json \ "stash").get)
  }

  implicit val jsonFormat: OWrites[JsObject] = new OWrites[JsObject] {
    override def writes(o: JsObject): JsObject = o
  }

  val locationCollection = reactiveMongoApi.database.map(d => d.collection[JSONCollection]("stashes"))

  def addStash(stash: Stash): Future[Stash] = {
    locationCollection.flatMap(l => l.insert[Stash](stash).map(_ => stash))
  }

  def getStashes(): Future[Seq[Stash]] = {
    locationCollection.flatMap(l => l.find(Json.obj()).cursor[Stash]().collect[List]())
  }

  def getStash(id: String): Future[Option[Stash]] = {
    locationCollection.flatMap(l => l.find(Json.obj("_id" -> id)).cursor[Stash].collect[List]().map {
      case List(matchingStash) => Some(matchingStash)
      case _ => None
    })
  }

  def deleteStash(id: String): Future[Boolean] = {
    locationCollection.flatMap(l => l.findAndRemove(Json.obj("_id" -> id)).map(result => true))
  }

  def updateStash(updatedStash: Stash): Future[Stash] = {
    locationCollection.flatMap(l => l.findAndUpdate(Json.obj("_id" -> updatedStash._id), updatedStash).map(_ => updatedStash))
  }
} 
开发者ID:dgrald,项目名称:locals-only-service-play,代码行数:50,代码来源:StashStore.scala


示例20: AccountDAO

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

import javax.inject.Inject
import java.sql.Date

import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile
import slick.driver.MySQLDriver.api._
import models.Account

import scala.concurrent.Future

class AccountDAO @Inject() (protected val databaseConfigProvider: DatabaseConfigProvider){
  private class AccountTable(tag: Tag) extends Table[Account] (tag, "Account"){
    def account_id = column[Long]("account_id", O.PrimaryKey, O.AutoInc)
    def user_id = column[Option[Long]]("user_id")
    def name = column[String]("name")
    def amount = column[Long]("amount")
    def category_id = column[Long]("category_id")
    def register_at = column[Date]("register_at")
    def payment_source_id = column[Option[Long]]("payment_source_id")
    def payment_destination_id = column[Option[Long]]("payment_destination_id")

    override def * = (
      account_id,
      user_id,
      name,
      amount,
      category_id,
      register_at,
      payment_source_id,
      payment_destination_id) <> (Account.tupled, Account.unapply)
  }

  val dbConfig = databaseConfigProvider.get[JdbcProfile]
  private val accounts = TableQuery[AccountTable]

  def list: Future[Seq[Account]] = {
    dbConfig.db.run(accounts.result)
  }
} 
开发者ID:kogai,项目名称:kakei-log,代码行数:42,代码来源:AccountDAO.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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