Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuration properties using the same key to create an array / list

I would like to store the source for html select boxes in a configuration file. These contain a lengthy strings that don't change often (but occassionaly do):

  • Lorem ipsum sit amet nr. 1
  • Lorem ipsum sit amet nr. 2
  • Lorem ipsum sit amet nr. 3
  • Lorem ipsum sit amet nr. 4

I already use commons-configuration. Is it possible to store them using the same property keys in some kind of configuration object (XMLConfiguration, HierarchicalConfiguration, etc.)? I mean to be able to retrieve them in one go using interface similar to getStringArray() (or list)? Example:

// reject.reason = Lorem ipsum sit amet nr. 1
// reject.reason = Lorem ipsum sit amet nr. 2
// reject.reason = Lorem ipsum sit amet nr. 3
// reject.reason = Lorem ipsum sit amet nr. 4

config.getStringArray(reject.reason)

I don't want to keep them separated on the same line because, first, the reasons are lengthy, and second, there are lots of reasons (> 10).

I don't want to store them in enums either, b/c it will be impossible to change them without recompiling the code.

Any hints on how to achieve this?

like image 270
Mike Minicki Avatar asked Jan 14 '11 12:01

Mike Minicki


2 Answers

Your example looks fine to me. If you specify a list of values using the same key, they are treated as a list, and the following should work:

reject.reason = Lorem ipsum sit amet nr. 1
reject.reason = Lorem ipsum sit amet nr. 2
reject.reason = Lorem ipsum sit amet nr. 3
reject.reason = Lorem ipsum sit amet nr. 4

In your Java code:

PropertiesConfiguration config = new PropertiesConfiguration("gui.properties");
String[] reasons = config.getStringArray("reject.reason");

http://commons.apache.org/configuration/userguide/howto_properties.html#Lists_and_arrays

like image 193
dogbane Avatar answered Oct 27 '22 01:10

dogbane


You could store them in a .properties file and name as ...

key.0=line0  
key.1=line1  
key.2=line2

Then in your code iterate through properties with a for loop looking for "key." + i until you get a null back.

I have done this in the past to enumerate and configure com ports and it works well.

like image 41
Romain Hippeau Avatar answered Oct 27 '22 01:10

Romain Hippeau