本文整理汇总了Scala中com.typesafe.config.ConfigException类的典型用法代码示例。如果您正苦于以下问题:Scala ConfigException类的具体用法?Scala ConfigException怎么用?Scala ConfigException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConfigException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: send
//设置package包名称以及导入依赖的类
package com.bwsw.controllers
import javax.inject.Inject
import com.bwsw.controllers.Secured.UserAction
import com.bwsw.dao.SendLogDAO
import com.bwsw.models.{Message, SendLogRecord}
import com.bwsw.utils.SmsGateway.SmsGateway
import com.typesafe.config.ConfigException
import org.joda.time.DateTime
import play.api.libs.json._
import play.api.mvc.Controller
import scala.concurrent.Future
import scala.util.{Failure, Success, Try}
def send = UserAction.async(parse.json) { implicit request =>
request.body.validate[Message] match {
case _: JsError => Future.successful(BadRequest(Json.obj("error" -> "Invalid json")).as(JSON))
case JsSuccess(m, _) => SmsGateway.getSmsGateway fold (
error => Future.successful(BadRequest(Json.obj("error" -> error)).as(JSON)),
service => Try(service.sendMessage(m)) match {
case Success(result) => result.fold(
error => Future.successful(BadRequest(Json.obj("error" -> error)).as(JSON)),
result => {
sendLogDAO.insert(SendLogRecord(request.user.username, m.sender, m.destination, m.text, DateTime.now().getMillis / 1000))
Future.successful(Ok(Json.obj("message" -> result)).as(JSON))
}
)
case Failure(e) => e match {
case _: ConfigException => Future.successful(BadRequest(Json.obj("error" -> "Bad application config: missing SMS gateway setting(s))")).as(JSON))
case _ => Future.successful(BadRequest(Json.obj("error" -> ("Unknown error: " + e.toString))).as(JSON))
}
}
)
}
}
}
开发者ID:bwsw,项目名称:sms-rest-gw,代码行数:40,代码来源:SendMessageController.scala
示例2: ConfigsSpec
//设置package包名称以及导入依赖的类
package knot.core.config
import com.typesafe.config.ConfigException
import knot.core.adapter.DefaultAdapterFactory
import org.scalatest.FunSpec
import org.scalatest.Matchers._
class ConfigsSpec extends FunSpec {
describe("configs") {
it("log is singleton") {
Configs.log should be theSameInstanceAs Configs.log
}
it("cache part config") {
Configs.part("default") should be theSameInstanceAs Configs.part("default")
}
it("not found part name") {
an[ConfigException.Missing] should be thrownBy {
Configs.part("x")
}
}
it("fallback default") {
Configs.adapterFactoryClass should be(classOf[DefaultAdapterFactory])
}
it("override") {
Configs.log.logLevel should be("4")
}
}
}
开发者ID:defvar,项目名称:knot,代码行数:33,代码来源:ConfigsSpec.scala
示例3: WSConfigParser
//设置package包名称以及导入依赖的类
package play.api.libs.ws
import javax.inject.{ Inject, Provider, Singleton }
import com.typesafe.config.{ Config, ConfigException }
import com.typesafe.sslconfig.ssl.SSLConfigParser
import com.typesafe.sslconfig.util.EnrichedConfig
import scala.concurrent.duration.Duration
@Singleton
class WSConfigParser @Inject() (config: Config, classLoader: ClassLoader) extends Provider[WSClientConfig] {
def parse(): WSClientConfig = {
val wsConfig = config.getConfig("play.ws")
val connectionTimeout = Duration(wsConfig.getString("timeout.connection"))
val idleTimeout = Duration(wsConfig.getString("timeout.idle"))
val requestTimeout = Duration(wsConfig.getString("timeout.request"))
val followRedirects = wsConfig.getBoolean("followRedirects")
val useProxyProperties = wsConfig.getBoolean("useProxyProperties")
val userAgent = {
try {
Some(wsConfig.getString("useragent"))
} catch {
case e: ConfigException.Null =>
None
}
}
val compressionEnabled = wsConfig.getBoolean("compressionEnabled")
val sslConfig = new SSLConfigParser(EnrichedConfig(wsConfig.getConfig("ssl")), classLoader).parse()
WSClientConfig(
connectionTimeout = connectionTimeout,
idleTimeout = idleTimeout,
requestTimeout = requestTimeout,
followRedirects = followRedirects,
useProxyProperties = useProxyProperties,
userAgent = userAgent,
compressionEnabled = compressionEnabled,
ssl = sslConfig
)
}
override lazy val get: WSClientConfig = parse()
}
开发者ID:playframework,项目名称:play-ws,代码行数:52,代码来源:WSConfigParser.scala
示例4: ActorServerModules
//设置package包名称以及导入依赖的类
package im.actor.server
import akka.actor._
import com.typesafe.config.{ ConfigException, ConfigObject, Config }
import im.actor.server.api.rpc.RpcApiExtension
import scala.collection.JavaConversions._
import scala.util.{ Failure, Success, Try }
object ActorServerModules extends ExtensionId[ActorServerModules] with ExtensionIdProvider {
override def createExtension(system: ExtendedActorSystem): ActorServerModules = new ActorServerModules(system)
override def lookup(): ExtensionId[_ <: Extension] = ActorServerModules
}
final class ActorServerModules(system: ExtendedActorSystem) extends Extension {
private val RpcServiceClazz = classOf[im.actor.api.rpc.Service]
def startModules(): Unit =
system.settings.config.getObject("modules") foreach {
case (n, c: ConfigObject) ? startModule(n, c.toConfig)
case (_, c) ?
throw new RuntimeException(s"Module have to be a config but got: ${c.getClass.getName}")
}
def startModule(name: String, config: Config): Unit = {
system.log.debug("Starting module {}", name)
(for {
fqcn ? Try(config.getString("rpc"))
clazz ? Try(Class.forName(fqcn).asSubclass(RpcServiceClazz))
} yield RpcApiExtension(system).register(clazz)) match {
case Success(_) ?
case Failure(_: ConfigException.Missing) ?
case Failure(_: ClassCastException) ?
throw new RuntimeException(s"rpc should extend im.actor.api.rpc.Service")
case Failure(e) ? throw e
}
(for {
fqcn ? Try(config.getString("extension"))
obj ? system.dynamicAccess.getObjectFor[AnyRef](fqcn)
} yield obj) match {
case Success(eid: ExtensionId[_]) ? startExtension(eid)
case Success(_) ?
throw new RuntimeException(s"extension should extend akka.actor.Extension")
case Failure(_: ConfigException.Missing) ?
case Failure(e) ? throw e
}
}
private def startExtension[T <: Extension](ext: ExtensionId[T]): T = ext.apply(system)
}
开发者ID:wex5,项目名称:dangchat-server,代码行数:54,代码来源:ActorServerModules.scala
示例5: RichConfig
//设置package包名称以及导入依赖的类
package swave.core.util
import com.typesafe.config.{Config, ConfigException}
import swave.core.ConfigurationException
import scala.concurrent.duration._
final class RichConfig(val underlying: Config) extends AnyVal {
def getScalaDuration(path: String): Duration =
underlying.getString(path) match {
case "infinite" ? Duration.Inf
case x ? Duration(x)
}
def getFiniteDuration(path: String): FiniteDuration =
Duration(underlying getString path) match {
case x: FiniteDuration ? x
case _ ? throw new ConfigurationException(s"Config setting '$path' must be a finite duration")
}
def getPossiblyInfiniteInt(path: String): Int =
underlying.getString(path) match {
case "infinite" ? Int.MaxValue
case x ? underlying getInt path
}
def getIntBytes(path: String): Int = {
val value: Long = underlying getBytes path
if (value <= Int.MaxValue) value.toInt
else throw new ConfigurationException(s"Config setting '$path' must not be larger than ${Int.MaxValue}")
}
def getPossiblyInfiniteIntBytes(path: String): Int =
underlying.getString(path) match {
case "infinite" ? Int.MaxValue
case x ? getIntBytes(path)
}
def getPossiblyInfiniteLongBytes(path: String): Long =
underlying.getString(path) match {
case "infinite" ? Long.MaxValue
case x ? underlying getBytes path
}
def getOptionalConfig(path: String): Option[Config] =
try Some(underlying getConfig path)
catch {
case _: ConfigException.Missing ? None
}
}
开发者ID:sirthias,项目名称:swave,代码行数:51,代码来源:RichConfig.scala
示例6: getBacklogConfiguration
//设置package包名称以及导入依赖的类
package com.nulabinc.backlog.migration.common.conf
import java.io.File
import com.typesafe.config.{ConfigException, ConfigFactory}
trait BacklogConfiguration {
val internal = ConfigFactory.load()
val external = ConfigFactory.parseFile(new File("./application.conf"))
val applicationName = internal.getString("application.title")
val versionName = internal.getString("application.version")
val mixpanelToken = internal.getString("application.mixpanel.token")
val mixpanelProduct = internal.getString("application.mixpanel.product")
val language = internal.getString("application.language")
val exportLimitAtOnce = {
try {
external.getInt("application.export-limit-at-once")
} catch {
case _: ConfigException =>
internal.getInt("application.export-limit-at-once")
}
}
val akkaMailBoxPool = {
try {
external.getInt("application.akka.mailbox-pool")
} catch {
case _: ConfigException =>
internal.getInt("application.akka.mailbox-pool")
}
}
def getBacklogConfiguration() = {
try {
external.getInt("application.akka.mailbox-pool")
external
} catch {
case _: ConfigException =>
internal
}
}
}
开发者ID:nulab,项目名称:backlog-migration-common,代码行数:53,代码来源:BacklogConfiguration.scala
示例7: validatePoolProps
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.helpers
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.typesafe.config.{Config, ConfigException}
import org.apache.commons.pool.impl.GenericObjectPool
trait GenericObjectPoolHelper {
def validatePoolProps(poolName: String, poolProps: Config) = {
val reqdPoolConf = Map[String, AnyVal](
"maxActive" -> GenericObjectPool.DEFAULT_MAX_ACTIVE,
"maxIdle" -> GenericObjectPool.DEFAULT_MAX_IDLE,
"minEvictableIdleTimeMillis" -> GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
"timeBetweenEvictionRunsMillis" -> GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
"whenExhaustedAction" -> GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION,
"enableLifo" -> GenericObjectPool.DEFAULT_LIFO
)
ConnektLogger(LogFile.FACTORY).info(s"Verifying requisite configs for $poolName pool.")
reqdPoolConf.foreach(kv => {
try {
poolProps.getAnyRef(kv._1)
} catch {
case e: ConfigException.Missing =>
ConnektLogger(LogFile.FACTORY).warn(s"Missing ${kv._1} default ${kv._2.toString} shall be applied.")
}
})
ConnektLogger(LogFile.FACTORY).info(s"$poolName pool config verification complete.")
}
}
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:30,代码来源:GenericObjectPoolHelper.scala
示例8: Fico
//设置package包名称以及导入依赖的类
import org.scalatest._
//Standard scala library for making typesafe-config nice
//Same behavior as typesafe-config
object Fico extends FunSuite with App {
import com.typesafe.config._
import net.ceedubs.ficus.Ficus._
val config = ConfigFactory.load()
assert(config.as[String]("service.http.host") == "0.0.0.0")
assert(config.as[Int]("service.http.port") == 8080)
assertThrows[ConfigException$Missing](config.as[String]("service.fico"))
}
//Knobs is a haskell-like library used by verizon
//Ficus creator uses knobs
object Knobbo extends FunSuite with App {
import com.typesafe.config._
import knobs.{ Required, ClassPathResource, Config }
import scalaz.concurrent.Task
val cfg: Task[Config] = knobs.Typesafe.config
val fico: Task[String] = for {
c <- cfg
f = c.require[String]("service.fico")
} yield f
assertThrows[knobs.KeyError](fico.run)
}
//Cool library
object Puro extends FunSuite with App {
import com.typesafe.config.ConfigException
import pureconfig.loadConfig
case class Http(host: String, port: Int)
case class Fico(fico: String)
assert(loadConfig[Http]("service.http").get.host == "0.0.0.0")
assert(loadConfig[Http]("service.http").get.port == 8080)
assertThrows[ConfigException](loadConfig[Fico]("service.fico"))
}
开发者ID:buildo,项目名称:fico,代码行数:45,代码来源:Fico.scala
示例9: ReallyConfig
//设置package包名称以及导入依赖的类
package io.really
import com.typesafe.config.{ Config, ConfigFactory, ConfigException }
import _root_.io.really.gorilla.EventLogStorageConfig
import com.typesafe.config.{ Config, ConfigFactory }
import _root_.io.really.gorilla.{ GorillaConfig, EventLogStorageConfig }
import _root_.io.really.model.{ MongodbConfig, CollectionActorConfig, ShardingConfig }
import java.nio.file._
class ReallyConfig(config: Config) extends QuickSandConfig with ShardingConfig with CollectionActorConfig
with MongodbConfig with EventLogStorageConfig with RequestDelegateConfig with GorillaConfig {
protected val reference = ConfigFactory.defaultReference()
private def newPath(file: String): Path = FileSystems.getDefault.getPath(file)
protected val reallyConfig = config.getConfig("really") withFallback (reference.getConfig("really"))
// validate against the reference configuration
reallyConfig.checkValid(reference, "core")
val coreConfig = reallyConfig.getConfig("core")
def getRawConfig: Config = config
def getReallyHome: Path = {
try {
val directory = config.getString("really.home")
val path = newPath(directory)
if (Files.notExists(path)) {
throw new ReallyConfigException(s"really.home ($path) specified does not exist.")
}
if (!Files.isDirectory(path)) {
throw new ReallyConfigException(s"really.home ($path) is not a directory.")
}
if (!Files.isReadable(path)) {
throw new ReallyConfigException(s"really.home ($path) is not readable (permissions).")
}
path.toRealPath()
} catch {
case e: ConfigException.Missing =>
//create the .really folder under current directory if needed
val directory = System.getProperty("user.dir") + FileSystems.getDefault.getSeparator + ".really"
val path = newPath(directory)
if (Files.notExists(path)) {
//let's create it.
Files.createDirectory(path)
}
path.toRealPath()
}
}
def getModelsPath: Path = getReallyHome.resolve("models")
}
开发者ID:radiodb,项目名称:radiodb,代码行数:55,代码来源:ReallyConfig.scala
示例10: Settings
//设置package包名称以及导入依赖的类
package com.booking.spark
import java.io.File
import com.typesafe.config.{ConfigFactory, Config, ConfigRenderOptions, ConfigException}
import scala.collection.JavaConversions._
import org.apache.log4j.{Level, Logger}
class Settings() {
private val logger = Logger.getLogger(this.getClass())
logger.setLevel(Level.DEBUG)
private val config: Config = ConfigFactory.load()
private def formatConfig(config: Config): String = config.root().render(ConfigRenderOptions.concise().setFormatted(true))
def getSchema(): SnapshotterSchema = {
try {
config.checkValid(ConfigFactory.defaultReference().getConfig("HBaseSnapshotter.MySQLSchema"))
logger.info(s"Detected valid $MySQLSchema")
MySQLSchema
} catch {
case e: ConfigException => {
try
{
config.checkValid(ConfigFactory.defaultReference().getConfig("HBaseSnapshotter.HBaseSchema"))
logger.info(s"Detected valid $HBaseSchema")
HBaseSchema
}
catch {
case e: ConfigException => {
logger.error(
s"""Bad config. Your application.json:
|${formatConfig(config)}
|HBaseSchema format:
|${formatConfig(ConfigFactory.defaultReference().getConfig("HBaseSnapshotter.HBaseSchema"))}
|MySQLSchema format:
|${formatConfig(ConfigFactory.defaultReference().getConfig("HBaseSnapshotter.MySQLSchema"))}
|$e
""".stripMargin)
System.exit(1)
HBaseSchema
}
}
}
}
}
val schemaType: SnapshotterSchema = getSchema()
def mysqlTable(): String = config.getString("mysql.table")
def mysqlSchema(): String = config.getString("mysql.schema")
def hbaseTimestamp(): Long = config.getLong("hbase.timestamp")
def hbaseZookeperQuorum(): String = config.getStringList("hbase.zookeeper_quorum").toList.mkString(",")
def hbaseSchema(): List[String] = config.getStringList("hbase.schema").toList
def hbaseTable(): String = config.getString("hbase.table")
def hiveTable(): String = config.getString("hive.table")
}
开发者ID:mysql-time-machine,项目名称:hbase-snapshotter,代码行数:57,代码来源:Settings.scala
示例11: auth
//设置package包名称以及导入依赖的类
package com.bwsw.controllers
import com.bwsw.models.User
import com.bwsw.utils.LdapAuthService
import com.typesafe.config.ConfigException
import com.unboundid.ldap.sdk.LDAPException
import pdi.jwt.JwtSession
import play.api.libs.json._
import play.api.mvc.{Action, Controller}
import scala.concurrent.Future
import scala.util.{Failure, Success}
def auth = Action.async(parse.json) { request =>
request.body.validate[Credentials] match {
case JsError(_) => Future.successful(BadRequest(Json.obj("error" -> "Invalid json")).as(JSON))
case JsSuccess(c: Credentials, _) => {
LdapAuthService.authenticate(c.username, c.password) match {
case Failure(e) => e match {
case _: LDAPException => Future.successful(BadRequest(Json.obj("error" -> "LDAP service error")).as(JSON))
case _: ConfigException => Future.successful(BadRequest(Json.obj("error" -> "Bad application config: missing [app.ldap.(host|port))] setting(s))")).as(JSON))
case _ => Future.successful(BadRequest(Json.obj("error" -> ("Unknown error: " + e.toString))).as(JSON))
}
case Success(r) => {
val session = JwtSession() + ("user", User(c.username))
Future.successful(Ok(Json.obj("token" -> session.serialize)).as(JSON))
}
}
}
}
}
}
开发者ID:bwsw,项目名称:sms-rest-gw,代码行数:34,代码来源:AuthController.scala
示例12: ConfigurationTest
//设置package包名称以及导入依赖的类
package com.microsoft.azure.iot.iothubreact.checkpointing
import com.microsoft.azure.iot.iothubreact.checkpointing.backends.cassandra.lib.Auth
import com.typesafe.config.{Config, ConfigException}
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FeatureSpec, GivenWhenThen}
class ConfigurationTest extends FeatureSpec with GivenWhenThen with MockitoSugar {
info("As a configured instance")
info("I want logic around returned values to be consistent with application expectations")
val confPath = "iothub-react.checkpointing."
Feature("Configuration Cassandra authorization") {
Scenario("Only one of username or password is supplied") {
var cfg = mock[Config]
when(cfg.getString(confPath + "storage.cassandra.username")).thenReturn("username")
when(cfg.getString(confPath + "storage.cassandra.password")).thenThrow(new ConfigException.Missing("path"))
assert(new CPConfiguration(cfg).cassandraAuth == None)
cfg = mock[Config]
when(cfg.getString(confPath + "storage.cassandra.username")).thenThrow(new ConfigException.Missing("path"))
when(cfg.getString(confPath + "storage.cassandra.password")).thenReturn("password")
assert(new CPConfiguration(cfg).cassandraAuth == None)
}
Scenario("Both username and password are supplied") {
var cfg = mock[Config]
when(cfg.getString(confPath + "storage.cassandra.username")).thenReturn("username")
when(cfg.getString(confPath + "storage.cassandra.password")).thenReturn("password")
assert(new CPConfiguration(cfg).cassandraAuth == Some(Auth("username", "password")))
}
}
Feature("Storage namespace") {
Scenario("Cassandra has a special namespace value") {
var cfg = mock[Config]
when(cfg.getString(confPath + "storage.namespace")).thenReturn("")
when(cfg.getString(confPath + "storage.backendType")).thenReturn("anythingbutcassandra")
assert(new CPConfiguration(cfg).storageNamespace == "iothub-react-checkpoints")
when(cfg.getString(confPath + "storage.backendType")).thenReturn("AZUREBLOB")
assert(new CPConfiguration(cfg).storageNamespace == "iothub-react-checkpoints")
when(cfg.getString(confPath + "storage.backendType")).thenReturn("CASSANDRA")
assert(new CPConfiguration(cfg).storageNamespace == "iothub_react_checkpoints")
}
}
}
开发者ID:Azure,项目名称:toketi-iothubreact,代码行数:54,代码来源:ConfigurationTest.scala
示例13: CPConfigurationTest
//设置package包名称以及导入依赖的类
// Copyright (c) Microsoft. All rights reserved.
package com.microsoft.azure.iot.iothubreact.checkpointing
import com.microsoft.azure.iot.iothubreact.checkpointing.backends.cassandra.lib.Auth
import com.typesafe.config.{Config, ConfigException}
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FeatureSpec, GivenWhenThen}
class CPConfigurationTest extends FeatureSpec with GivenWhenThen with MockitoSugar {
info("As a configured instance")
info("I want logic around returned values to be consistent with application expectations")
val confPath = "iothub-react.checkpointing."
Feature("Configuration Cassandra authorization") {
Scenario("Only one of username or password is supplied") {
var cfg = mock[Config]
when(cfg.getString(confPath + "storage.cassandra.username")).thenReturn("username")
when(cfg.getString(confPath + "storage.cassandra.password")).thenThrow(new ConfigException.Missing("path"))
assert(new CPConfiguration(cfg).cassandraAuth == None)
cfg = mock[Config]
when(cfg.getString(confPath + "storage.cassandra.username")).thenThrow(new ConfigException.Missing("path"))
when(cfg.getString(confPath + "storage.cassandra.password")).thenReturn("password")
assert(new CPConfiguration(cfg).cassandraAuth == None)
}
Scenario("Both username and password are supplied") {
var cfg = mock[Config]
when(cfg.getString(confPath + "storage.cassandra.username")).thenReturn("username")
when(cfg.getString(confPath + "storage.cassandra.password")).thenReturn("password")
assert(new CPConfiguration(cfg).cassandraAuth == Some(Auth("username", "password")))
}
}
Feature("Storage namespace") {
Scenario("Cassandra has a special namespace value") {
var cfg = mock[Config]
when(cfg.getString(confPath + "storage.namespace")).thenReturn("")
when(cfg.getString(confPath + "storage.backendType")).thenReturn("anythingbutcassandra")
assert(new CPConfiguration(cfg).storageNamespace == "iothub-react-checkpoints")
when(cfg.getString(confPath + "storage.backendType")).thenReturn("AZUREBLOB")
assert(new CPConfiguration(cfg).storageNamespace == "iothub-react-checkpoints")
when(cfg.getString(confPath + "storage.backendType")).thenReturn("CASSANDRA")
assert(new CPConfiguration(cfg).storageNamespace == "iothub_react_checkpoints")
}
}
}
开发者ID:Azure,项目名称:toketi-iothubreact,代码行数:56,代码来源:CPConfigurationTest.scala
示例14: getHttpAddress
//设置package包名称以及导入依赖的类
package io.corbel.http
import java.net.NetworkInterface
import com.typesafe.config.{ConfigException, Config}
import grizzled.slf4j.Logging
import io.corbel.actor.AkkaModule
trait HttpModule extends AkkaModule with Logging {
lazy val server: Server = new Server(
getHttpAddress,
config.getInt(Config.HttpPort),
httpHandler
)
private def getHttpAddress: String =
if(config.hasPath(Config.HttpAddress)) config.getString(Config.HttpAddress)
else getAddressFromInterface
private def getAddressFromInterface: String = {
try {
val interface = config.getString(Config.HttpInterface)
val networkInterface = NetworkInterface.getByName(interface)
val inetAddress = networkInterface.getInetAddresses.nextElement()
inetAddress.getHostAddress
}
catch {
case e: ConfigException.Missing =>
error(s"You must specify either ${Config.HttpAddress} or ${Config.HttpInterface} in your configuration", e)
throw e
case e: Throwable => throw e
}
}
object Config {
val HttpAddress = "http.address"
val HttpInterface = "http.interface"
val HttpPort = "http.port"
}
//module dependencies ----------
def config: Config
def httpHandler: Server.Handler
}
开发者ID:alexdeleon,项目名称:corbel-2.0,代码行数:52,代码来源:HttpModule.scala
示例15: FlickrClientSpec
//设置package包名称以及导入依赖的类
package com.jcranky.flickr
import com.jcranky.flickr.FlickrClient.ClientError
import com.jcranky.flickr.HttpClient.{GetError, GetResponse}
import com.jcranky.flickr.model.Foto
import com.typesafe.config.{ConfigException, ConfigFactory}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
class FlickrClientSpec extends Specification with Mockito {
"FlickrClient.fromConfig" should {
"work with valid configuration" in {
val client = FlickrClient.fromConfig(ConfigFactory.load("app-test.conf"))
client !=== null
}
"fail if some configuration is missing" in {
FlickrClient.fromConfig(ConfigFactory.load("acre.conf")) should throwAn[ConfigException]
}
}
"FlickrClient.buscaFotos" should {
"ask the httpclient for the photos and pass the response to the response parser" in {
val fotos = List(Foto("1", "jcranky", "123", "321", 1, "my pic", true, false, false))
val resp = buscaFotos(
Right(GetResponse(200, "fotos-xml-here")),
Right(fotos)
)
resp should beRight(fotos)
}
"return a client error if the parser returns a FlickrError" in {
val error = FlickrKnownError(100, "Invalid API Key (Key has invalid format)")
val resp = buscaFotos(
Right(GetResponse(200, "error-xml-here")),
Left(error)
)
resp should beLeft(ClientError(error.toString))
}
}
def buscaFotos(httpResp: Either[GetError, GetResponse], parsed: Either[FlickrError, Seq[Foto]]): Either[ClientError, Seq[Foto]] = {
val httpClient = mock[HttpClient]
val parser = mock[ResponseParser]
httpClient.get(any[String]) returns httpResp
parser.parse(any[String]) returns parsed
val client = new FlickrClient("api-key", "base-url", httpClient, parser)
val resp = client.buscaFotos(List("scala"))
there was one(httpClient).get(anyString)
resp
}
}
开发者ID:jcranky,项目名称:scalando,代码行数:60,代码来源:FlickrClientSpec.scala
注:本文中的com.typesafe.config.ConfigException类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论