As you can see (and as expected) basic HOCON maps pretty well to
our current IParameters. We will also have support for more
complex data structures like Maps and Arrays. We can add flexmark
to take our comments and convert them to HTML for documentation. I
will put most of this functionality in a new lib (lib-config) so
we don't add dependencies to core.
# Sample HOCON configuration file with comments database { # Database host host: "localhost" # Database port port: 5432 # Database credentials user: "username" # Database password password: "password" }
import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigOrigin; import java.util.HashMap; import java.util.List; import java.util.Map; public class HOCONReader { public static void main(String[] args) { // Load configuration from the HOCON file Config config = ConfigFactory.parseResources("example.conf"); // Access values from the configuration String host = config.getString("database.host"); int port = config.getInt("database.port"); String user = config.getString("database.user"); String password = config.getString("database.password"); // Print the values System.out.println("Host: " + host); System.out.println("Port: " + port); System.out.println("User: " + user); System.out.println("Password: " + password); ConfigObject root = config.root(); List<String> comments = root.origin().comments(); String description = root.origin().description(); System.out.println("Description: " + description); System.out.println("Comments: " + comments); System.out.println(parseComments(root)); } private static Map<String, String> parseComments(ConfigObject configObject) { Map<String, String> commentsMap = new HashMap<>(); configObject.forEach((key, configValue) -> { ConfigOrigin origin = configValue.origin(); String comment = origin.comments().stream().reduce((s1, s2) -> s1 + "\n" + s2).orElse(""); commentsMap.put(key, comment); // Recursively process nested objects if (configValue instanceof ConfigObject) { commentsMap.putAll(parseComments((ConfigObject) configValue)); } }); return commentsMap; } }
OUTPUT: Host: localhost Port: 5432 User: username Password: password Description: example.conf @ file:/home/jimh/DATA/IdeaProjects/okapi/okapi/parsers/hocon/target/classes/example.conf: 1 Comments: [] {database= Sample HOCON configuration file with comments, password= Database password, port= Database port, host= Database host, user= Database credentials}