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


Scala Environment类代码示例

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


在下文中一共展示了Environment类的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: Module

//设置package包名称以及导入依赖的类
import javax.inject._

import com.google.inject.AbstractModule
import net.codingwell.scalaguice.ScalaModule
import play.api.{Configuration, Environment}

import jobs._
import models.daos._
import models.services._


class Module(environment: Environment, configuration: Configuration)
    extends AbstractModule
    with ScalaModule {

  override def configure() = {
    bind[UserDAO].to[UserDAOImpl]
    bind[ClassroomDAO].to[ClassroomDAOImpl]

    bind[UserService].to[UserServiceImpl]
    bind[ClassroomService].to[ClassroomServiceImpl]

    bind[Startup].asEagerSingleton()
  }
} 
开发者ID:yoo-haemin,项目名称:hufs-classroom,代码行数:26,代码来源:Module.scala

示例3: PullRequestClientModule

//设置package包名称以及导入依赖的类
package de.stema.pullrequests.client

import de.stema.pullrequests.dto.ProjectDTO
import play.api.inject.{Binding, Module}
import play.api.{Configuration, Environment}

import scala.concurrent.Future


class PullRequestClientModule extends Module {
  def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      if(configuration.getBoolean("offline").getOrElse(false)) {
        bind[PullRequestClient].to[PullRequestSampleClient]
    } else {
        bind[PullRequestClient].to[PullRequestGitHubClient]
    })
  }
}

abstract class PullRequestClient {
  def getPullRequests(configuration: String): Seq[Future[ProjectDTO]]
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:24,代码来源:PullRequestClientModule.scala

示例4: SlickModule

//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.connect.play.slick

import javax.inject.Singleton

import io.toolsplus.atlassian.connect.play.api.repositories.AtlassianHostRepository
import play.api.db.slick.DatabaseConfigProvider
import play.api.inject._
import play.api.{Configuration, Environment}

@Singleton
final class SlickModule extends Module {
  def bindings(environment: Environment,
               configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[AtlassianHostRepository].to[SlickAtlassianHostRepository]
    )
  }
}

trait SlickComponents {

  def dbConfigProvider: DatabaseConfigProvider

  lazy val hostRepository: AtlassianHostRepository =
    new SlickAtlassianHostRepository(dbConfigProvider)
} 
开发者ID:toolsplus,项目名称:atlassian-connect-play-slick,代码行数:27,代码来源:SlickModule.scala

示例5: Item

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

import akka.NotUsed
import com.lightbend.lagom.scaladsl.api.broker.Topic
import com.lightbend.lagom.scaladsl.api.{Descriptor, Service, ServiceCall}
import com.lightbend.lagom.scaladsl.api.transport._
import demo.api.basket.ExtraTransportExceptions.CustomExceptionSerializer
import play.api.Environment
import play.api.libs.json.{Format, Json}

case class Item(name: String, price: Int)
object Item {
  implicit val itemFormat: Format[Item] = Json.format
}

case class Basket(items: Seq[Item], total: Int)
object Basket {
  implicit val basketFormat: Format[Basket] = Json.format
}

case class OrderPlaced(basketId: String, basket: Basket)
object OrderPlaced {
  implicit val orderPlacedFormat: Format[OrderPlaced] = Json.format
}

trait BasketService extends Service {
  def getBasket(basketId: String): ServiceCall[NotUsed, Basket]
  def getTotal(basketId: String): ServiceCall[NotUsed, Int]
  def addItem(basketId: String): ServiceCall[Item, NotUsed]
  def clearAll(basketId: String): ServiceCall[NotUsed, NotUsed]
  def placeOrder(basketId: String): ServiceCall[NotUsed, NotUsed]
  def placedOrders: Topic[OrderPlaced]

  override def descriptor: Descriptor = {
    import Method._
    import Service._

    named("basket").withCalls(
      restCall(GET, "/basket/:basketId", getBasket _),
      restCall(GET, "/basket/:basketId/total", getTotal _),
      restCall(POST, "/basket/:basketId/items", addItem _),
      restCall(DELETE, "/basket/:basketId/items", clearAll _),
      restCall(POST, "/basket/:basketId/order", placeOrder _)
    ).withTopics(
      topic("placed-orders", placedOrders)
    ).withExceptionSerializer(new CustomExceptionSerializer(Environment.simple()))
  }
} 
开发者ID:tommpy,项目名称:demo-lagom-checkout,代码行数:49,代码来源:BasketService.scala

示例6: BadRequest

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

import com.lightbend.lagom.scaladsl.api.deser._
import com.lightbend.lagom.scaladsl.api.transport._
import play.api.Environment

import scala.util.control._

trait ExtraTransportExceptions {
  case class BadRequest(message: ExceptionMessage) extends TransportException(TransportErrorCode.BadRequest, message) with NoStackTrace
  object BadRequest {
    def apply(message: String): BadRequest = apply(new ExceptionMessage(classOf[BadRequest].getSimpleName, message))
  }
}

object ExtraTransportExceptions extends ExtraTransportExceptions {

  final class CustomExceptionSerializer(environment: Environment) extends DefaultExceptionSerializer(environment) {
    protected override def fromCodeAndMessage(transportErrorCode: TransportErrorCode, exceptionMessage: ExceptionMessage): Throwable = {
      transportErrorCode match {
        case TransportErrorCode.BadRequest ? BadRequest(exceptionMessage)
        case _                             ? super.fromCodeAndMessage(transportErrorCode, exceptionMessage)
      }
    }
  }
} 
开发者ID:tommpy,项目名称:demo-lagom-checkout,代码行数:27,代码来源:BadRequest.scala

示例7: PlayApp

//设置package包名称以及导入依赖的类
import play.api.{Application, ApplicationLoader, Environment, Mode, Play}
import play.core.server.{ServerConfig, ServerProvider}

object PlayApp extends App {

  val config = ServerConfig(mode = Mode.Dev)

  val application: Application = {
    val environment = Environment(config.rootDir, this.getClass.getClassLoader, Mode.Dev)
    val context = ApplicationLoader.createContext(environment)
    val loader = ApplicationLoader(context)
    loader.load(context)
  }

  Play.start(application)

  val serverProvider: ServerProvider = ServerProvider.fromConfiguration(this.getClass.getClassLoader, config.configuration)
  serverProvider.createServer(config, application)
} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:20,代码来源:PlayApp.scala

示例8: DevicesControllerHtmlSpec

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

import boot.Boot
import mocks.DataSourceMock
import org.scalatestplus.play._
import play.api.test.Helpers._
import play.api.test._
import play.api.{ApplicationLoader, Environment}

class DevicesControllerHtmlSpec extends PlaySpec {

  "DevicesController GET" should {

    "render the index page from a new instance of controller" in {
      val controller = new DevicesController(stubControllerComponents(), DataSourceMock.mockDevices)
      val home = controller.getDevicesAsHTML.apply(FakeRequest(GET, "/"))

      status(home) mustBe OK
      contentType(home) mustBe Some("text/html")
      contentAsString(home) must include ("Ada weather")
    }

    "render the index page from the router" in {
      val context = ApplicationLoader.createContext(Environment.simple())
      val app = new Boot().load(context)
      val request = FakeRequest(GET, "/")
      val home = route(app, request).get

      status(home) mustBe OK
      contentType(home) mustBe Some("text/html")
      contentAsString(home) must include ("Ada weather")
    }
  }
} 
开发者ID:openada,项目名称:adaweather,代码行数:35,代码来源:DevicesControllerHtmlSpec.scala

示例9: ElasticsearchClient

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

import javax.inject.{Inject, Singleton}

import play.api.libs.ws.{WSAuthScheme, WSClient, WSRequest, WSResponse}
import play.api.{Configuration, Environment, Logger}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class ElasticsearchClient @Inject()(ws: WSClient, environment: Environment, configuration: Configuration)(implicit ec: ExecutionContext) {

  val logger = Logger("ElasticsearchClient")

  val elasticsearchUri: String = configuration.getString("elasticsearch.uri").getOrElse("http://localhost:9200")
  val elasticsearchUser: Option[String] = configuration.getString("elasticsearch.user")
  val elasticsearchPassword: Option[String] = configuration.getString("elasticsearch.password")
  logger.info(s"Elasticsearch URI = $elasticsearchUri")

  private def client(path: String): WSRequest = {
    val sanitizedPath: String = if (path.startsWith("/")) {
      path
    } else {
      s"/$path"
    }

    elasticsearchUser match {
      case None => ws.url(s"$elasticsearchUri$sanitizedPath")
      case Some(user) => ws.url(s"$elasticsearchUri$sanitizedPath").withAuth(user, elasticsearchPassword.getOrElse(""), WSAuthScheme.BASIC)
    }

  }

  def bulk(body: String): Future[WSResponse] = {
    client(s"/_bulk").post(body)
  }

} 
开发者ID:devconferences,项目名称:devconferences,代码行数:39,代码来源:ElasticsearchClient.scala

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

示例11: Router

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

import pokestats.UPickleSerializers.pickler
import javax.inject.Inject

import akka.util.ByteString
import play.api.{Configuration, Environment}
import play.api.http.HttpEntity
import play.api.mvc._
import pokestats.{Api, UPickleSerializers}

import scala.concurrent.ExecutionContext

object Router
    extends UPickleSerializers
    with autowire.Server[String, pickler.Reader, pickler.Writer]

class Application @Inject()(
    action: DefaultActionBuilder,
    parsers: PlayBodyParsers,
    api: Api)(
    implicit context: ExecutionContext,
    config: Configuration,
    env: Environment)
    extends InjectedController {

  def index(path: String) = action {
    Ok(views.html.pokestats.index("PokéStats"))
  }

  def autowireApi(path: String) = action.async(parsers.tolerantText) {
    implicit request =>
      println(s"Request path: $path")

      // get the request body as String
      val b = request.body

      // call Autowire route
      Router
        .route[Api](api)(
          autowire.Core
            .Request(path.split("/"), pickler.read[Map[String, String]](b))
        )
        .map(result => {
          Result(
            header = ResponseHeader(200, Map.empty),
            body =
              HttpEntity.Strict(ByteString(result), Some("application/json"))
          )
        })
  }
} 
开发者ID:guilgaly,项目名称:pokemon-stats,代码行数:53,代码来源:Application.scala

示例12: TestUserClient

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

import scala.concurrent.{ExecutionContext, Future}
import play.api.{ApplicationLoader, Environment}
import play.api.ApplicationLoader.Context

import clients._
import init.ApplicationComponents
import models.User

class TestUserClient(
  users: (Int, User)*
) extends UserClient {

  private val usersMap = Map(users:_*)

  def getUser(id: Int)(implicit ec: ExecutionContext): Future[Option[User]] = {
    Future.successful(usersMap.get(id))
  }

}

class TestApplicationComponents(
  context: Context = ApplicationLoader.createContext(Environment.simple()),
  val userClient: UserClient
) extends ApplicationComponents(context)
  with ClientComponents 
开发者ID:EVENFinancial,项目名称:play-compile-time-di-example,代码行数:28,代码来源:Helpers.scala

示例13: GenerateFixtures

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

import com.google.inject.{Inject, Singleton}
import org.birdfeed.chirp.database.SchemaTables
import org.birdfeed.chirp.database.models._
import play.api.{Environment, Logger}
import play.api.inject.DefaultApplicationLifecycle

import scala.sys.process.Process
import scala.util.Random
import com.github.t3hnar.bcrypt._



@Singleton
class GenerateFixtures @Inject()(lifecycle: DefaultApplicationLifecycle, env: Environment) {
  SchemaTables.initialize

  // Create Users
  val admin = User("Test Admin", "[email protected]", "foobar123".bcrypt, 1).create
  val researcher = User("Test Researcher", "[email protected]", "barbaz123".bcrypt, 2).create
  val participant = User("Test Participant", "[email protected]", "quux456".bcrypt, 3).create

  // Create some samples
  val samples = 1 to 50 map { n =>
    Sample(s"Sound Bite $n", researcher.id, "https://not.a.real.s3.url").create
  }

  // Create some experiments
  1 to 10 foreach { n =>
    val e = Experiment(s"Experiment $n", researcher.id).create
    e.samples := Random.shuffle(samples).take(Random.nextInt(50))
  }

  // Generate an API key
  Logger.debug(s"Fixture generation complete! Use this API key: ${ApiKey(true).create.key}")

  SchemaTables.cleanup

  // TODO: This is not graceful at all
  lifecycle.stop
  Process("kill `cat target/universal/stage/RUNNING_PID`")
} 
开发者ID:AwesomeIT,项目名称:chirp,代码行数:44,代码来源:GenerateFixtures.scala

示例14: executionContext

//设置package包名称以及导入依赖的类
package com.example.auction.item.impl

import com.example.auction.bidding.api.BiddingService
import com.example.auction.item.api.ItemService
import com.lightbend.lagom.scaladsl.broker.kafka.LagomKafkaComponents
import com.lightbend.lagom.scaladsl.devmode.LagomDevModeComponents
import com.lightbend.lagom.scaladsl.persistence.cassandra.CassandraPersistenceComponents
import com.lightbend.lagom.scaladsl.server._
import com.softwaremill.macwire._
import com.typesafe.conductr.bundlelib.lagom.scaladsl.ConductRApplicationComponents
import play.api.Environment
import play.api.libs.ws.ahc.AhcWSComponents

import scala.concurrent.ExecutionContext

trait ItemComponents extends LagomServerComponents
  with CassandraPersistenceComponents {

  implicit def executionContext: ExecutionContext
  def environment: Environment

  override lazy val lagomServer = serverFor[ItemService](wire[ItemServiceImpl])
  lazy val itemRepository = wire[ItemRepository]
  lazy val jsonSerializerRegistry = ItemSerializerRegistry

  persistentEntityRegistry.register(wire[ItemEntity])
  readSide.register(wire[ItemEventProcessor])
}

abstract class ItemApplication(context: LagomApplicationContext) extends LagomApplication(context)
  with ItemComponents
  with AhcWSComponents
  with LagomKafkaComponents {

  lazy val biddingService = serviceClient.implement[BiddingService]

  wire[BiddingServiceSubscriber]
}

class ItemApplicationLoader extends LagomApplicationLoader {
  override def loadDevMode(context: LagomApplicationContext): LagomApplication =
    new ItemApplication(context) with LagomDevModeComponents

  override def load(context: LagomApplicationContext): LagomApplication =
    new ItemApplication(context) with ConductRApplicationComponents

  override def describeService = Some(readDescriptor[ItemService])
} 
开发者ID:lagom,项目名称:online-auction-scala,代码行数:49,代码来源:ItemApplication.scala

示例15: MailsendActorModule

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


import play.api.{Configuration, Environment}
import play.api.inject.{Binding, Module}
import play.api.libs.concurrent.AkkaGuiceSupport

import actors.MailsendActor
import com.google.inject.AbstractModule
import schedulers.MailsendScheduler


class MailsendActorModule extends AbstractModule with AkkaGuiceSupport {
  override def configure() = {
    bindActor[MailsendActor]("mailsend-actor")
  }
}

class MailsendScheduleModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(
      bind[MailsendScheduler].toSelf.eagerly
    )
  }
} 
开发者ID:bananapianist,项目名称:playfw_sample,代码行数:26,代码来源:MailsendModule.scala


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