com.typesafe.config.ConfigException Scala Examples

The following examples show how to use com.typesafe.config.ConfigException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: MetricsConfig.scala    From skafka   with MIT License 5 votes vote down vote up
package com.evolutiongaming.skafka

import com.evolutiongaming.config.ConfigHelper._
import com.typesafe.config.{Config, ConfigException}
import org.apache.kafka.clients.{CommonClientConfigs => C}

import scala.concurrent.duration._

final case class MetricsConfig(
  sampleWindow: FiniteDuration = 30.seconds,
  numSamples: Int = 2,
  recordingLevel: String = "INFO",
  reporters: List[String] = Nil) {

  def bindings: Map[String, String] = Map[String, String](
    (C.METRICS_SAMPLE_WINDOW_MS_CONFIG, sampleWindow.toMillis.toString),
    (C.METRICS_NUM_SAMPLES_CONFIG, numSamples.toString),
    (C.METRICS_RECORDING_LEVEL_CONFIG, recordingLevel),
    (C.METRIC_REPORTER_CLASSES_CONFIG, reporters mkString ","))
}

object MetricsConfig {

  val Default: MetricsConfig = MetricsConfig()

  def apply(config: Config): MetricsConfig = {

    def get[T: FromConf](path: String, paths: String*) = {
      config.getOpt[T](path, paths: _*)
    }

    def getDuration(path: String, pathMs: => String) = {
      val value = try get[FiniteDuration](path) catch { case _: ConfigException => None }
      value orElse get[Long](pathMs).map { _.millis }
    }

    MetricsConfig(
      sampleWindow = getDuration(
        "metrics.sample-window",
        "metrics.sample.window.ms") getOrElse Default.sampleWindow,
      numSamples = get[Int](
        "metrics.num-samples",
        "metrics.num.samples") getOrElse Default.numSamples,
      recordingLevel = get[String](
        "metrics.recording-level",
        "metrics.recording.level") getOrElse Default.recordingLevel,
      reporters = get[List[String]](
        "metrics.reporters",
        "metric.reporters") getOrElse Default.reporters)
  }
} 
Example 2
Source File: PluginCollection.scala    From sumobot   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.sumobot.plugins

import akka.actor.{ActorSystem, Props}
import akka.event.Logging
import com.sumologic.sumobot.core.Bootstrap
import com.typesafe.config.ConfigException

import scala.util.{Failure, Success, Try}

trait PluginCollection {

  protected def addPlugin(name: String, props: Props)(implicit system: ActorSystem): Unit = {
    lazy val log = Logging.getLogger(system, this)
    val property = s"plugins.$name.enabled"
    Try(system.settings.config.getBoolean(property)) match {
      case Success(true) =>
        system.actorOf(props, name)
      case Success(false) =>
        log.debug(s"Plugin $name is disabled.")
      case Failure(_: ConfigException.Missing) =>
        log.debug(s"Could not find $property. Enabling plugin by default.")
        system.actorOf(props, name)
      case Failure(other) =>
        throw other
    }
  }

  def setup(implicit system: ActorSystem): Unit
} 
Example 3
Source File: ListOfConfigs.scala    From sumobot   with Apache License 2.0 5 votes vote down vote up
package com.sumologic.sumobot.core.config

import com.typesafe.config.{Config, ConfigException}

import scala.collection.JavaConverters._
import scala.util.{Failure, Success, Try}

object ListOfConfigs {
  def parse[T](config: Config, path: String)(convert: (String, Config) => T): Map[String, T] = {
    Try(config.getObject(path).asScala) match {
      case Success(accounts) =>
        accounts.map {
          obj =>
            val name = obj._1
            name -> convert(name, config.getConfig(path + "." + name))
        }.toMap
      case Failure(e: ConfigException.Missing) =>
        Map.empty
      case Failure(other) =>
        throw other
    }
  }
} 
Example 4
Source File: FlickrClientSpec.scala    From scalando   with MIT License 5 votes vote down vote up
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
  }
} 
Example 5
Source File: ConfigurationDetectorSpec.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.util

import com.typesafe.config.{Config, ConfigException}
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

class ConfigurationDetectorSpec extends Specification with Mockito {

  val myConfigFromEnvVar = "my-configuration-from-env-var"
  val myConfigFromFile = "my-configuration-from-file"

  abstract class ConfigurationDetectorSpecContext extends Scope {
    def config = mock[Config]

    val variableName = "MY-CONFIG"
    val configName = "my.config"
  }

  trait NoEnvVariable extends ConfigurationDetector {
    override protected def environmentVariable(name: String) = None
  }

  trait WithEnvVariable extends ConfigurationDetector {
    override protected def environmentVariable(name: String) = Some(myConfigFromEnvVar)
  }

  trait NoConfigFromFile extends ConfigurationDetector {
    override protected def configuration(path: String) = throw new ConfigException.Missing(path)
  }

  trait WithConfigFromFile extends ConfigurationDetector {
    override protected def configuration(path: String) = myConfigFromFile
  }

  "ConfigurationDetector" should {

    "if environment variable exists" in {

      "if configuration from file does not exists" in {
        "detect the configuration from the environment variable" in
          new ConfigurationDetectorSpecContext with WithEnvVariable with NoConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromEnvVar
          }
      }

      "if configuration from file exists" in {
        "detect the configuration from the environment variable" in
          new ConfigurationDetectorSpecContext with WithEnvVariable with WithConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromEnvVar
          }
      }
    }

    "if environment variable does not exist" in {

      "if configuration from file exists" in {
        "detect the configuration from the configuration file" in
          new ConfigurationDetectorSpecContext with NoEnvVariable with WithConfigFromFile {
            envVarOrConfig(variableName, configName) === myConfigFromFile
          }
      }

      "if configuration from file does not exist" in {
        "throw an exception" in
          new ConfigurationDetectorSpecContext with NoEnvVariable with NoConfigFromFile {
            envVarOrConfig(variableName, configName) must throwA[RuntimeException]
          }
      }
    }
  }
} 
Example 6
Source File: ConfigSettingsValidator.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.settings.utils

import cats.data.{NonEmptyList, Validated, ValidatedNel}
import cats.implicits._
import com.typesafe.config.{Config, ConfigException}
import com.wavesplatform.transaction.assets.exchange.AssetPair
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ValueReader

import scala.jdk.CollectionConverters._
import scala.util.Try

object ConfigSettingsValidator {

  type ErrorsListOr[A] = ValidatedNel[String, A]

  def apply(config: Config): ConfigSettingsValidator = new ConfigSettingsValidator(config)

  implicit class ErrorListOrOps[A](validatedValue: ErrorsListOr[A]) {
    def getValueOrThrowErrors: A = validatedValue valueOr (errorsAcc => throw new Exception(errorsAcc.mkString_(", ")))
  }

  object AdhocValidation {
    def validateAssetPairKey(key: String): Validated[String, AssetPair] =
      Validated.fromTry(AssetPair.fromString(key)) leftMap (_ => s"Can't parse asset pair '$key'")
  }
}

class ConfigSettingsValidator(config: Config) {

  import ConfigSettingsValidator.ErrorsListOr

  private def createError[T](settingName: String, errorMsg: String, showError: Boolean = true, showValue: Boolean = true): NonEmptyList[String] = {

    lazy val value = config.getValue(settingName).unwrapped

    lazy val msg = (showValue, showError) match {
      case (true, true)  => s"$value ($errorMsg)"
      case (true, false) => s"$value"
      case (false, true) => s"$errorMsg"
      case _             => ""
    }

    NonEmptyList.one(s"Invalid setting $settingName value: $msg")
  }

  def validate[T: ValueReader](settingName: String, showError: Boolean = false): ErrorsListOr[T] = {
    Validated fromTry Try(config.as[T](settingName)) leftMap (ex => createError(settingName, ex.getMessage, showError))
  }

  def validateByPredicate[T: ValueReader](settingName: String)(predicate: T => Boolean, errorMsg: String): ErrorsListOr[T] = {
    validate[T](settingName, showError = true).ensure(createError(settingName, errorMsg))(predicate)
  }

  def validatePercent(settingName: String): ErrorsListOr[Double] = {
    validateByPredicate[Double](settingName)(p => 0 < p && p <= 100, "required 0 < percent <= 100")
  }

  def validateList[T: ValueReader](settingName: String): ErrorsListOr[List[T]] = {
    config
      .getList(settingName)
      .asScala
      .toList
      .zipWithIndex
      .traverse {
        case (cfg, index) =>
          val elemPath = s"$settingName.$index"
          Validated fromTry Try(cfg.atPath(elemPath).as[T](elemPath)) leftMap (ex => List(ex.getMessage))
      }
      .leftMap(errorsInList => createError(settingName, errorsInList.mkString(", "), showValue = false))
  }

  def validateMap[K, V: ValueReader](settingName: String)(keyValidator: String => Validated[String, K]): ErrorsListOr[Map[K, V]] = {
    config
      .getConfig(settingName)
      .root()
      .entrySet()
      .asScala
      .toList
      .traverse { entry =>
        val elemPath = s"$settingName.${entry.getKey}"
        val k        = keyValidator(entry.getKey).leftMap(List(_))
        val v        = Validated fromTry Try(entry.getValue.atPath(elemPath).as[V](elemPath)) leftMap (ex => List(ex.getMessage))
        k.product(v)
      }
      .map(_.toMap)
      .leftMap(errorsInList => createError(settingName, errorsInList.mkString(", "), showValue = false))
  }

  def validateWithDefault[T: ValueReader](settingName: String, defaultValue: T, showError: Boolean = false): ErrorsListOr[T] = {
    Validated
      .fromTry(Try(config.as[T](settingName)).recover { case _: ConfigException.Missing => defaultValue })
      .leftMap(ex => createError(settingName, ex.getMessage, showError))
  }

  def validateByPredicateWithDefault[T: ValueReader](
      settingName: String)(predicate: T => Boolean, errorMsg: String, defaultValue: T): ErrorsListOr[T] = {
    validateWithDefault[T](settingName, defaultValue, showError = true).ensure(createError(settingName, errorMsg))(predicate)
  }
} 
Example 7
Source File: RichConfig.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
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
    }
} 
Example 8
Source File: QueueConfigSpec.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.pattern.stream

import com.typesafe.config.{ConfigException, ConfigFactory}
import net.openhft.chronicle.queue.RollCycles
import net.openhft.chronicle.wire.WireType
import org.scalatest.{FlatSpec, Matchers}


class QueueConfigSpec extends FlatSpec with Matchers {

  it should "properly read the configuration from config" in {

    val configText =
      """
        | persist-dir = /tmp/myQueue
        | roll-cycle = xlarge_daily
        | wire-type = compressed_binary
        | block-size = 80m
        | index-spacing = 8k
        | output-ports = 3
        | commit-order-policy = strict
      """.stripMargin
    val config = ConfigFactory.parseString(configText)
    val queueConfig = QueueConfig.from(config)
    queueConfig.persistDir.getAbsolutePath shouldBe "/tmp/myQueue"
    queueConfig.rollCycle shouldBe RollCycles.XLARGE_DAILY
    queueConfig.wireType shouldBe WireType.COMPRESSED_BINARY
    queueConfig.blockSize shouldBe (80 * 1024 * 1024)
    queueConfig.indexSpacing shouldBe (8 * 1024)
    queueConfig.indexCount shouldBe RollCycles.XLARGE_DAILY.defaultIndexCount
    queueConfig.isBuffered shouldBe false
    queueConfig.epoch shouldBe 0L
    queueConfig.outputPorts shouldBe 3
    queueConfig.commitOrderPolicy shouldBe Strict
  }

  it should "properly assume default configurations" in {

    val configText =
      """
        | persist-dir = /tmp/myQueue
      """.stripMargin
    val config = ConfigFactory.parseString(configText)
    val queueConfig = QueueConfig.from(config)
    queueConfig.persistDir.getAbsolutePath shouldBe "/tmp/myQueue"
    queueConfig.rollCycle shouldBe RollCycles.DAILY
    queueConfig.wireType shouldBe WireType.BINARY
    queueConfig.blockSize shouldBe (64 * 1024 * 1024)
    queueConfig.indexSpacing shouldBe RollCycles.DAILY.defaultIndexSpacing
    queueConfig.indexCount shouldBe RollCycles.DAILY.defaultIndexCount
    queueConfig.isBuffered shouldBe false
    queueConfig.epoch shouldBe 0L
    queueConfig.outputPorts shouldBe 1
    queueConfig.commitOrderPolicy shouldBe Lenient
  }

  it should "set commit order policy to lenient" in {
    val configText =
      """
        | persist-dir = /tmp/myQueue
        | roll-cycle = xlarge_daily
        | wire-type = compressed_binary
        | block-size = 80m
        | index-spacing = 8k
        | output-ports = 3
        | commit-order-policy = lenient
      """.stripMargin
    val config = ConfigFactory.parseString(configText)
    val queueConfig = QueueConfig.from(config)
    queueConfig.commitOrderPolicy shouldBe Lenient
  }

  it should "throw BadValue exception when commit-order-policy is set to an invalid value" in {
    val configText =
      """
        | persist-dir = /tmp/myQueue
        | roll-cycle = xlarge_daily
        | wire-type = compressed_binary
        | block-size = 80m
        | index-spacing = 8k
        | output-ports = 3
        | commit-order-policy = invalid
      """.stripMargin
    val config = ConfigFactory.parseString(configText)
    a [ConfigException.BadValue] should be thrownBy QueueConfig.from(config)
  }
} 
Example 9
Source File: CryptoAlgebraSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.core.crypto

import java.lang.reflect.InvocationTargetException

import com.typesafe.config.{Config, ConfigException, ConfigFactory}

import scala.collection.JavaConverters._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class TestCrypto(config: Config) extends CryptoAlgebra {
  val testMe: String = config.getString("test-me")
  def encrypt(value: String): String = value
  def decrypt(value: String): String = value
}
class CryptoAlgebraSpec extends AnyWordSpec with Matchers {

  private val conf =
    """
      | type = "vinyldns.core.crypto.NoOpCrypto"
      | test-me = "hello"
    """.stripMargin

  private val cryptoConf = ConfigFactory.parseString(conf)

  "CryptoAlgebra" should {
    "load the expected crypto instance" in {
      CryptoAlgebra.load(cryptoConf).unsafeRunSync() shouldBe a[NoOpCrypto]
    }
    "throw an exception if config is missing type" in {
      val badConfig = ConfigFactory.empty()
      a[ConfigException] should be thrownBy CryptoAlgebra.load(badConfig).unsafeRunSync()
    }
    "return ok if all params are provided" in {
      val opts = Map("type" -> "vinyldns.core.crypto.TestCrypto", "test-me" -> "wassup")
      val goodConfig = ConfigFactory.parseMap(opts.asJava)
      val ok = CryptoAlgebra.load(goodConfig).unsafeRunSync().asInstanceOf[TestCrypto]
      ok.testMe shouldBe "wassup"
    }
    "throw an exception if config is missing items required by the class" in {
      val opts = Map("type" -> "vinyldns.core.crypto.TestCrypto")
      val badConfig = ConfigFactory.parseMap(opts.asJava)

      val thrown = the[InvocationTargetException] thrownBy CryptoAlgebra
        .load(badConfig)
        .unsafeRunSync()
      thrown.getCause shouldBe a[ConfigException]
    }
  }
} 
Example 10
Source File: ConfigUtil.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.utils

import java.util.concurrent.TimeUnit

import akka.util.Timeout
import com.typesafe.config.{ConfigException, Config, ConfigFactory}

object ConfigUtil {

  lazy val referenceConfig = ConfigFactory.defaultReference

  
  def getDefaultTimeout(config:Config, path:String, default:Timeout, unit:TimeUnit=TimeUnit.SECONDS) : Timeout = {
    if (config.hasPath(path)) {
      val duration = config.getDuration(path, unit)
      Timeout(duration, unit)
    } else {
      default
    }
  }
} 
Example 11
Source File: ConfigFactoryWrapperSpec.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.backend

import java.io.FileNotFoundException

import com.typesafe.config.{ ConfigException, ConfigFactory }
import pureconfig.BaseSuite
import pureconfig.PathUtils._
import pureconfig.error.{ CannotParse, CannotReadFile }

class ConfigFactoryWrapperSpec extends BaseSuite {

  behavior of "ConfigFactoryWrapper.parseFile"

  it should "return a Left when a file does not exist" in {
    ConfigFactory.parseFile(nonExistingPath.toFile) shouldEqual ConfigFactory.empty
    ConfigFactoryWrapper.parseFile(nonExistingPath) should failLike {
      case CannotReadFile(`nonExistingPath`, Some(reason)) => be(a[FileNotFoundException])(reason)
    }
  }

  it should "return a Left when a file exists but cannot be parsed" in {
    val tmpPath = createTempFile("{foo:")
    intercept[ConfigException](ConfigFactory.parseFile(tmpPath.toFile))
    ConfigFactoryWrapper.parseFile(tmpPath) should failWithType[CannotParse]
  }

  behavior of "ConfigFactoryWrapper.loadFile"

  it should "return a Left when a file does not exist" in {
    ConfigFactory.load(ConfigFactory.parseFile(nonExistingPath.toFile)) shouldEqual ConfigFactory.load(ConfigFactory.empty)
    ConfigFactoryWrapper.loadFile(nonExistingPath) should failLike {
      case CannotReadFile(`nonExistingPath`, Some(reason)) => be(a[FileNotFoundException])(reason)
    }
  }

  it should "return a Left when a file exists but cannot be parsed" in {
    val tmpPath = createTempFile("{foo:")
    intercept[ConfigException](ConfigFactory.load(ConfigFactory.parseFile(tmpPath.toFile)))
    ConfigFactoryWrapper.loadFile(tmpPath) should failWithType[CannotParse]
  }

  it should "return a Left when it finds unresolved placeholders" in {
    val tmpPath = createTempFile(f"""{ foo1: "bla", foo2: $${charlie}}""")
    intercept[ConfigException](ConfigFactory.load(ConfigFactory.parseFile(tmpPath.toFile)))
    ConfigFactoryWrapper.loadFile(tmpPath) should failWithType[CannotParse]
  }
} 
Example 12
Source File: ConfigurationTest.scala    From toketi-iothubreact   with MIT License 5 votes vote down vote up
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")
    }
  }
} 
Example 13
Source File: CPConfigurationTest.scala    From toketi-iothubreact   with MIT License 5 votes vote down vote up
// 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")
    }
  }
} 
Example 14
Source File: ConfigurationManager.scala    From ionroller   with MIT License 5 votes vote down vote up
package ionroller

import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting
import com.typesafe.config.{Config, ConfigException, ConfigFactory}
import com.typesafe.scalalogging.StrictLogging
import ionroller.aws.Dynamo
import play.api.libs.json._

import scalaz.concurrent.Task
import scalaz.stream._
import scalaz.{-\/, \/-}

class ConfigurationManager(initialConfig: SystemConfiguration) extends StrictLogging {
  val configurationSignal = async.signalOf(initialConfig)
}

object ConfigurationManager extends StrictLogging {
  def apply(initialConfig: SystemConfiguration): ConfigurationManager =
    new ConfigurationManager(initialConfig)

  val confFile: Config = ConfigFactory.load()
  val defaultSolutionStack: String = confFile.getString("ionroller.solution-stack-name")
  val whitelistKey = "ionroller.modify-environments-whitelist"
  val blacklistKey = "ionroller.modify-environments-blacklist"

  val modifyEnvironmentslist: (String, Boolean) => Set[TimelineName] = {
    (key, required) =>
      try {
        confFile.getString(key)
          .split(",")
          .map(_.trim)
          .collect({ case s: String if !s.isEmpty && s != "ALL" => s })
          .map(TimelineName.apply).toSet
      } catch {
        case ex: ConfigException.Missing => {
          if (required) {
            logger.error(s"${key} $required configuration is missing.\nRun ION-Roller with property: -D${key}=[ALL|<TIMELINE_NAME_1,TIMELINE_NAME_2,...>]")
            throw ex
          } else Set.empty
        }
      }
  }

  val modifyEnvironmentsWhitelist = modifyEnvironmentslist(whitelistKey, true)
  val modifyEnvironmentsBlacklist = modifyEnvironmentslist(blacklistKey, false)

  logger.debug("Processing timelines: " + {
    if (modifyEnvironmentsWhitelist.isEmpty) "ALL" else modifyEnvironmentsWhitelist
  }) + {
    if (!modifyEnvironmentsBlacklist.isEmpty) "excluding: " + modifyEnvironmentsBlacklist else ""
  }
  val modifyEnvironments = confFile.getBoolean("ionroller.modify-environments")

  val defaultOptionSettings: Seq[ConfigurationOptionSetting] = {
    val options = confFile.getString("ionroller.option-settings")

    Task(Json.parse(options).as[Seq[ConfigurationOptionSetting]]).attemptRun match {
      case \/-(settings) => settings
      case -\/(t) => {
        logger.error(t.getMessage, t)
        Seq.empty
      }
    }
  }

  val defaultResources: JsObject = {
    val resources = confFile.getString("ionroller.resources")

    Task(Json.parse(resources).as[JsObject]).attemptRun match {
      case \/-(resources) => resources
      case -\/(t) => {
        logger.error(t.getMessage, t)
        JsObject(Seq.empty)
      }
    }
  }

  def getSavedConfiguration: Task[SystemConfiguration] = {
    for {
      table <- Dynamo.configTable(None)
      systemConfig <- Dynamo.getSystemConfig(table)
    } yield systemConfig
  }

} 
Example 15
Source File: HoconMapSpec.scala    From mqtt-mongo   with MIT License 5 votes vote down vote up
package com.izmailoff.mm.util

import com.typesafe.config.{ConfigException, ConfigFactory}
import org.specs2.mutable.Specification

class HoconMapSpec extends Specification {

  "HOCON config" should {
    val rawConf =
      """
        |application {
        |  someSettings {
        |    mappings = [
        |      { "one" : 2000 },
        |      { "two" : 3000 },
        |      { "three" : 5000 }
        |    ]
        |  }
        |}
      """.stripMargin
    val conf = ConfigFactory.parseString(rawConf)

    "parse map like entries given a root conf and full path and create a proper Scala map from them" in {
      val expected = Map("one" -> 2000L,
        "two" -> 3000L,
        "three" -> 5000L)
      HoconMap.getMap[String, Long](identity(_), _.toLong, conf, "application.someSettings.mappings") === expected
    }

    "throw config exception for incomplete/wrong path because full path is required" in {
      HoconMap.getMap[String, Long](identity(_), _.toLong, conf, "mappings") must throwA[ConfigException]
    }
  }

} 
Example 16
Source File: SpiTests.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.spi

import com.typesafe.config.ConfigException
import common.StreamLogging
import common.WskActorSystem
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class SpiTests extends FlatSpec with Matchers with WskActorSystem with StreamLogging {

  behavior of "SpiProvider"

  it should "load an Spi from SpiLoader via typesafe config" in {
    val simpleSpi = SpiLoader.get[SimpleSpi]
    simpleSpi shouldBe a[SimpleSpi]
  }

  it should "throw an exception if the impl defined in application.conf is missing" in {
    a[ClassNotFoundException] should be thrownBy SpiLoader.get[MissingSpi]
  }

  it should "throw an exception if the module is missing" in {
    a[ClassNotFoundException] should be thrownBy SpiLoader.get[MissingModule]
  }

  it should "throw an exception if the config key is missing" in {
    a[ConfigException] should be thrownBy SpiLoader.get[MissingKey]
  }
}

trait SimpleSpi extends Spi
object SimpleSpiImpl extends SimpleSpi

trait MissingSpi extends Spi
trait MissingModule extends Spi
trait MissingKey extends Spi 
Example 17
Source File: WSConfigParser.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws

import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton

import com.typesafe.config.Config
import com.typesafe.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()
} 
Example 18
Source File: ConfigSupportSpec.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.common.config

import java.util.Properties

import com.typesafe.config.{ConfigException, ConfigFactory}
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpecLike
import ConfigSupport._

import scala.collection.JavaConverters._


class ConfigSupportSpec extends Matchers with AnyFunSpecLike with ConfigSupport {

  describe("When configuring") {
    it("has the correct application name") {
      applicationName shouldBe "hydraTest"
    }

    it("converts a config to map") {
      val map = Map(
        "test-key" -> "test-value",
        "test-number" -> 1,
        "test.boolean" -> false
      )

      ConfigFactory.parseMap(map.asJava).toMap shouldBe map

    }

    it("converts a config object to map") {
      val map = Map(
        "test-key" -> "test-value",
        "test-number" -> 1,
        "test.boolean" -> false
      )

      ConfigSupport.toMap(ConfigFactory.parseMap(map.asJava).root()) shouldBe map

    }

    it("converts a map to a java properties") {
      val map = Map[String, AnyRef](
        "test-key" -> "test-value",
        "test-number" -> "1",
        "test.boolean" -> "false"
      )
      (map: Properties).getProperty("test.boolean") shouldBe "false"
    }

  }

}