All Downloads are FREE. Search and download functionalities are using the official Maven repository.

uk.co.unclealex.diagnostics.ConfigurationExtensions.scala Maven / Gradle / Ivy

There is a newer version: 1.2.2
Show newest version
package uk.co.unclealex.diagnostics

import play.api.{ConfigLoader, Configuration}

import scala.util.Try

/**
  * Get configuration options and fall back to environment variables if they are not found.
  */
object ConfigurationExtensions {

  implicit class ConfigurationWithEnvironment(configuration: Configuration) {
    def getOrEnvOptional[T](configurationPropertyName: String, jvmPropertyName: String)
                           (implicit configLoader: ConfigLoader[T], propertyConverter: PropertyConverter[T]): Option[T] = {
      val nullSafeFactory: (String => String) => Option[T] = {
        propertyReader => for {
          propertyAsString <- Option(propertyReader(jvmPropertyName))
          propertyAsType <- Try(propertyConverter(propertyAsString)).toOption
        } yield {
          propertyAsType
        }
      }
      configuration.getOptional[T](configurationPropertyName).
        orElse(nullSafeFactory(System.getProperty)).
        orElse(nullSafeFactory(System.getenv))
    }

    def getOrEnv[T](description: String, configurationPropertyName: String, jvmPropertyName: String)
                (implicit configLoader: ConfigLoader[T], propertyConverter: PropertyConverter[T]): T = {
      getOrEnvOptional[T](configurationPropertyName, jvmPropertyName) match {
        case Some(value) => value
        case None => throw new IllegalStateException(
          s"You must provide a $description either as a '$configurationPropertyName' configuration option or as a '$jvmPropertyName' environment variable ")
      }
    }
  }

  sealed trait PropertyConverter[T] {
    def apply(value: String): T
  }

  implicit val stringPropertyConverter: PropertyConverter[String] = new PropertyConverter[String] {
    override def apply(value: String): String = value
  }

  implicit val intPropertyConverter: PropertyConverter[Int] = new PropertyConverter[Int] {
    override def apply(value: String): Int = Integer.parseInt(value)
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy