Loading Different files from resource directory via Pureconfig

916 views Asked by At

I have few files in a resource folder and I have a mapping class for the same. Now All I want is to load each file in different config class using pureconfig. Is there any way to load it via providing only resource folder name.

 - src
    - main
        - resources
            - configs
                - conf1.json
                - conf2.json

I want something like this

ConfigSource.resources("configs")

and it should return

List<Conf>

The current approach is something like this

def main(args: Array[String]): Unit = {
    implicit def hint[A]: ProductHint[A] =
      ProductHint[A](ConfigFieldMapping(CamelCase, CamelCase))

    val resourceFiles = getResourceFolderFiles("configs")
    val configs = new ListBuffer[SampleConfig];
    resourceFiles.foreach(file =>
      configs.append(
        ConfigSource
          .file(file)
          .load[SampleConfig]
          .getOrElse(null)))
    println(configs.size)
  }

  private def getResourceFolderFiles(folder: String): Array[File] = {
    val loader = Thread.currentThread.getContextClassLoader
    val url = loader.getResource(folder)
    val path = url.getPath
    new File(path).listFiles
  }

Is there any simplest way possible?

1

There are 1 answers

3
sarveshseri On BEST ANSWER
implicit def hint[A]: ProductHint[A] =
  ProductHint[A](ConfigFieldMapping(CamelCase, CamelCase))


val sampleConfigList =
  Try(Thread.currentThread().getContextClassLoader.getResource("configs").getPath)
    .flatMap(filePath => Try(new File(filePath).listFiles().toList))
    .map(fileList =>
      fileList.flatMap(file => ConfigSource.file(file).load[SampleConfig].toOption)
    )
    .getOrElse(List.empty[SampleConfig])