The title talks by itself, I have a Config object (from https://github.com/typesafehub/config) and I want to pass it the a constructor which only supports java.util.Properties as argument. Is there an easy way to convert a Config to a Properties object ?
Typesafe Config is the reference implementation for HOCON, Human-Optimized Config Object Notation.” This is a JSON superset flavored with some Java Properties syntax.
Typesafe Config allows you to store configuration into separated files and use include keyword to include configuration of those files. Here is a concrete example for myApp which relies on the configuration of moduleA and moduleB .
public final class ConfigFactory extends java.lang.Object. Contains static methods for creating Config instances. See also ConfigValueFactory which contains static methods for converting Java values into a ConfigObject . You can then convert a ConfigObject into a Config with ConfigObject.
class ConfigFactoryDefines the configuration object factory. The configuration object factory instantiates a Config object for each configuration object name that is accessed and returns it to callers.
Here is a way to convert a typesafe Config object into a Properties java object. I have only tested it in a simple case for creating Kafka properties.
Given this configuration in application.conf
kafka-topics {
my-topic {
zookeeper.connect = "localhost:2181",
group.id = "testgroup",
zookeeper.session.timeout.ms = "500",
zookeeper.sync.time.ms = "250",
auto.commit.interval.ms = "1000"
}
}
You can create the corresponding Properties object like that:
import com.typesafe.config.{Config, ConfigFactory}
import java.util.Properties
import kafka.consumer.ConsumerConfig
object Application extends App {
def propsFromConfig(config: Config): Properties = {
import scala.collection.JavaConversions._
val props = new Properties()
val map: Map[String, Object] = config.entrySet().map({ entry =>
entry.getKey -> entry.getValue.unwrapped()
})(collection.breakOut)
props.putAll(map)
props
}
val config = ConfigFactory.load()
val consumerConfig = {
val topicConfig = config.getConfig("kafka-topics.my-topic")
val props = propsFromConfig(topicConfig)
new ConsumerConfig(props)
}
// ...
}
The function propsFromConfig is what you are mainly interested in, and the key points are the use of entrySet to get a flatten list of properties, and the unwrapped of the entry value, that gives an Object which type depends on the configuration value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With