ksl
ksl

Reputation: 4709

Java properties file validation

My Java application loads a properties file at startup, which contains key-value pairs. I can set and retrieve the expected properties successfully.

However, as it stands the properties file can contain any property name I care to put in there. I'd like to be able to restrict the properties to a specific set, some of which are mandatory and others optional.

I can manually check each loaded property against a valid set but I was wondering if there was a more elegant way to do this. E.g. perhaps some way to declare the expected mandatory/optional properties, so that when the properties file is loaded, an exception is thrown if an invalid or missing property is detected. Similar to the kind of thing boost::program_options offers in C++.

Upvotes: 4

Views: 10453

Answers (2)

phatfingers
phatfingers

Reputation: 10250

Since Properties is already a simple iterable structure, I would just perform your validation against that object. Below is a simple validation of required vs optional.

public static void testProps(Properties props, Set<String> required, Set<String> optional) {
    int requiredCount=0;
    Enumeration keys = props.keys();
    while (keys.hasMoreElements()) {
        String key=(String) keys.nextElement();
        if (required.contains(key)) {
            requiredCount++;
        } else if (!optional.contains(key)) {
            throw new IllegalStateException("Unauthorized key : " + key);
        }
    }
    if (requiredCount<required.size()) {
        for (String requiredKey : required) {
            if (!props.containsKey(requiredKey)) {
                throw new IllegalStateException("Missing required key : " + requiredKey);
            }
        }
    }
}

Upvotes: 4

sleske
sleske

Reputation: 83587

I can manually check each loaded property against a valid set but I was wondering if there was a more elegant way to do this. E.g. perhaps some way to declare the expected mandatory/optional properties, so that when the properties file is loaded, an exception is thrown if an invalid or missing property is detected.

The built-in API of the JDK (java.util.Properties) do not offer this kind of validation.

However, it should not be difficult to implment your own ConfigLoader class which does this. Your class could wrap java.util.Properties, and validate the data after loading. You could for example maintain a list of mandatory and optional keys (hardcoded, or loaded externally), and then check the list of loaded keys against these lists.

It's possible you could find some implementation which does this, but as the validation itself will be specific to your needs anyway, and the rest is fairly simple, I don't think it's worth hunting for an existing solution.

Upvotes: 2

Related Questions