Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a convention for loading yaml config files from the classpath #6

Merged
merged 6 commits into from May 10, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/main/scala/com/target/data_validator/ConfigParser.scala
Expand Up @@ -7,7 +7,7 @@ import io.circe._
import io.circe.generic.auto._
import io.circe.yaml.parser

import scala.io.Source
import scala.io.{BufferedSource, Source}
import scala.util.{Failure, Success, Try}

object ConfigParser extends LazyLogging {
Expand All @@ -28,9 +28,35 @@ object ConfigParser extends LazyLogging {
json.as[ValidatorConfig]
}

private def bufferContentsAsString(buffer: BufferedSource): String = {
val contents = buffer.mkString
buffer.close()
contents
}

private def loadFromFile(filename: String): String = {
logger.info(s"Attempting to load `$filename` from file system")
val buffer = Source.fromFile(filename)
bufferContentsAsString(buffer)
}

private def loadFromClasspath(filename: String): String = {
logger.info(s"Attempting to load `$filename` from classpath")
val is = getClass.getResourceAsStream(filename)
val buffer = Source.fromInputStream(is)
bufferContentsAsString(buffer)
}

def parseFile(filename: String, cliMap: Map[String, String]): Either[Error, ValidatorConfig] = {
logger.info(s"Parsing `$filename`")
Try(Source.fromFile(filename).mkString) match {

Try {
if (filename.startsWith("classpath:")) {
loadFromClasspath(filename.stripPrefix("classpath:"))
} else {
loadFromFile(filename)
}
} match {
case Success(contents) => parse(contents)
case Failure(thr) => Left[Error, ValidatorConfig](DecodingFailure.fromThrowable(thr, List.empty))
}
Expand Down