Leggere file TOML in Scala con toml4j

Mattepuffo's logo
Leggere file TOML in Scala con toml4j

Leggere file TOML in Scala con toml4j

In questo articolo vediamo come leggere un file TOML in Scala usando toml4j.

E' possibile anche usare un mapper con classi apposite, ma noi faremo un esempio basico più semplice.

Inoltre, come al solito, specifico che si tratta di Scala 3.

Per l'installazione se usate sbt aggiungete questa dipendenza:

libraryDependencies ++= Seq(
  "com.moandjiezana.toml" % "toml4j" % "0.7.2"
)

Questo il file TOML:

title = "Test TOML"
version = "1.0.0"

[database]
host = "localhost"
port = 5432
username = "root"
password = "password"
databases = ["db_test"]
pool_size = 10
ssl_enabled = true

[server]
host = "0.0.0.0"
port = 8080
debug = false
allowed_hosts = ["*"]

[logging]
level = "INFO"
format = "%(asctime)s - %(levelname)s - %(message)s"
handlers = ["console", "file"]

[cache]
enabled = true
ttl = 3600
max_size = 1000

[features]
enable_api = true
rate_limit = 100

Qui sotto un pò di codice:

package com.test

import com.moandjiezana.toml.Toml

import java.io.File

@main
def main(): Unit =
  val toml = new Toml().read(new File("C:\TEST\test.toml"))

  val title = toml.getString("title")
  val version = toml.getString("version")

  println("Title: " + title)
  println("Version: " + version)

  val dbHost = toml.getString("database.host")
  val dbPort = toml.getLong("database.port")
  val databases = toml.getList("database.databases")
  val sslEnabled = toml.getBoolean("database.ssl_enabled")

  println("nDatabase:")
  println("Host: " + dbHost)
  println("Port: " + dbPort)
  println("Databases: " + databases)
  println("SSL: " + sslEnabled)

  val serverHost = toml.getString("server.host")
  val serverPort = toml.getLong("server.port")
  val debug = toml.getBoolean("server.debug")
  val allowedHosts = toml.getList("server.allowed_hosts")

  println("nAllowed hosts:")
  allowedHosts.forEach(el => println(el))

  println("nServer:")
  println("Host: " + serverHost)
  println("Port: " + serverPort)
  println("Debug: " + debug)

  val cache: Toml = toml.getTable("cache")
  val cacheEnabled: Boolean = cache.getBoolean("enabled")
  val ttl: Long = cache.getLong("ttl")
  val maxSize: Long = cache.getLong("max_size")

  println("nCache:")
  println("Enabled: " + cacheEnabled)
  println("TTL: " + ttl)
  println("Max Size: " + maxSize)

Enjoy!


Condividi

Commentami!