Skip to content

Instantly share code, notes, and snippets.

@123avi
Last active May 9, 2018 12:50
Show Gist options
  • Save 123avi/c59e99f203b28bb7fc8a082cf3e18eb6 to your computer and use it in GitHub Desktop.
Save 123avi/c59e99f203b28bb7fc8a082cf3e18eb6 to your computer and use it in GitHub Desktop.
Handling config idiomatically
import com.typesafe.config.ConfigException.Missing
import com.typesafe.config._
import org.slf4j.{Logger, LoggerFactory}
import scala.concurrent.duration.{FiniteDuration, TimeUnit}
import scala.language.{implicitConversions, postfixOps}
import scala.util.Try
import scala.util.matching.Regex
trait ConfExtractor[A]{
def getConf(key:String):A
}
trait ConfigUtils {
self =>
import scala.collection.JavaConverters._
implicit def javaToScalaInt(d: List[java.lang.Integer]): List[Int] = d.map(_.intValue)
lazy val config: Config = ConfigFactory.load()
implicit val getInt: ConfExtractor[Int] = (key: String) => config.getInt(key)
implicit val getString: ConfExtractor[String] = (key: String) => config.getString(key)
implicit val getLong: ConfExtractor[Long] = (key: String) => config.getLong(key)
implicit val getBoolean: ConfExtractor[Boolean] = (key: String) => config.getBoolean(key)
implicit val getConfig: ConfExtractor[Config] = (key: String) => config.getConfig(key)
implicit val getStringList: ConfExtractor[List[String]] = (key: String) => config.getStringList(key).asScala.toList
implicit val getIntList: ConfExtractor[List[Int]] = (key: String) => config.getIntList(key).asScala.toList
def getConfig(path: String, default: => Config): Config = getConfValue(path, Option(default))
def getConfValue[T : ConfExtractor](key: String, default: => Option[T] = None) : T = {
Try( implicitly[ConfExtractor[T]].getConf(key)).recover{
case ex: Missing =>
// throw the original exception of no default
Try(default.get).getOrElse{ throw ex}
}.get
}
private def getDuration(key: String, default: => Option[Long])(tu: TimeUnit): FiniteDuration = {
val d: Long = getConfValue(key,default)
FiniteDuration(d, tu)
}
protected case class HttpConfig(interface: String, port: Int) {
//memoize
private val httpString = s"$interface:$port"
override def toString: String = httpString
}
protected object HttpConfig {
val FromString: Regex = """([a-zA-z0-9\-\_\.]+):(\d+)$""".r
def unapply(httpString: String): Option[(String, Int)] = httpString match {
case FromString(host, port) => Some(host, port.toInt)
case _ => None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment