Converting Configafe Config types to java.util.Properties

The header says by itself, I have a Config object (from https://github.com/typesafehub/config ), and I want to pass it a constructor that only supports java.util.Properties as an argument. Is there an easy way to convert Config to a Properties object?

+7
java scala typesafe
source share
3 answers

The following is a way to convert a Configa Configafe object to a Java object. I just tested it in a simple case to create 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 as follows:

 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 propsFromConfig function is what you are most interested in, and the key points are to use entrySet to get a smoothing list of properties and an expanded record value that gives an object whose type depends on the configuration value.

+5
source share

You can try my scala packaging https://github.com/andr83/scalaconfig . Using it to convert a configuration object in java Properties are simple:

 val properties = config.as[Properties] 
+3
source share

Since typesafe config / hocon supports a much richer structure than java.util.propeties , it will be difficult to get a safe conversion.

Or else, since properties can only express a subset of hocon , the conversion is not clear, because it will have a possible loss of information.

So, if the configuration is pretty flat and does not contain utf-8 , then you can convert hocon to json and then extract the values.

A better solution would be to implement ConfigClass and populate the values ​​with the values ​​from hocon and pass this to the class you want to configure.

+1
source share

All Articles