本文整理汇总了Scala中javax.inject.Inject类的典型用法代码示例。如果您正苦于以下问题:Scala Inject类的具体用法?Scala Inject怎么用?Scala Inject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Inject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
示例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)
}
}
示例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)
}
}
示例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
)
}
示例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()))
}
}
示例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())
}
}
}
示例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))
}
示例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)
}
}
示例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)
}
示例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)
}
}
示例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))
}
}
示例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))
}
}
示例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"))
}
}
}
}
}
示例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 ))
}
}
示例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)
}
}