Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read a list of objects from the configuration file in play framework

How can i read a list of users from the configuration file in play framework? i have tried doing something like this:

users=[{uid:123,pwd:xyz},{uid:321,pwd:abc}]

from the play application

 List<Object> uids = Play.application().configuration().getList("users");

will give me this a list of objects, if I iterate through the list i get each object as

{uid=123,pwd=xyz} and {uid=321,pwd=abc}

at this point i don't know how i can elegantly get the value of the uid, i can do some hacky job as omit the first and last bracket and parse for the before after equal sign, but it would be too ugly! any idea? (the application is written in java)

thanks

like image 436
nightograph Avatar asked Mar 29 '13 18:03

nightograph


People also ask

How do I open a conf file in Windows 10?

From the taskbar, search System Configuration. Select the top result, System Configuration desktop app.

How does a config file look like?

Configuration files have largely adopted a serialization format, such as XML, YAML and JSON, to represent complex data structures in a way that is easily stored and parsed. The resulting filenames can reflect the format. For example, a configuration file in YAML format may appear such as myapplication_configuration.

What is ConfigFactory in Scala?

Configurations from a fileBy default, the ConfigFactory looks for a configuration file called application. conf. If willing to use a different configuration file (e.g.: another. conf), we just need to indicate a different file name and path to load (e.g.: ConfigFactory. load("another")).


2 Answers

A Scala implementation that avoids the deprecated getConfigList method would rely on retrieving a Seq[Configuration] as follows:

  case class UserConfig(uid: Int, pwd: String)
  val userConfigs: Seq[UserConfig] = configuration.get[Seq[Configuration]]("users").map { userConfig =>
    UserConfig(userConfig.get[Int]("uid"), userConfig.get[String]("pwd"))
  }
like image 106
mrucci Avatar answered Sep 17 '22 20:09

mrucci


Since I had recently the same problem and this is still unanswered, here is my suggestion:

List<User> users = getConfig().getConfigList("users").stream().map(
            config -> new User(config.getString("uid"), config.getBoolean("pwd"))
    ).collect(Collectors.toList());

As far as I know there are no tuples or anything in Java, you need to use either an object or a list with two elements. I decided to go for an object here, you can also return a list.

like image 20
Aleks Avatar answered Sep 21 '22 20:09

Aleks