Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional statement in .properties file

Is there a way we can have conditional statement inside a .properties file?

like:

if(condition1)
    xyz = abc
else if(condition2)
    xyz = efg
like image 589
Piyush Avatar asked Jun 05 '12 15:06

Piyush


People also ask

How do I break a line in .properties file?

You need to use \n\ as a solution. First two symbols \n - new line for string, third \ - multi-line in properties file. For example (in application. properties):

How do I use .properties file?

The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load . properties file in the form of key-value pairs.


2 Answers

No, it's not possible. The file format is freely available: http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.Reader%29.

Do this in Java code:

if (condition1) {
    return properties.getProperty("xyz.1");
}
else if (condition2) {
    return properties.getProperty("xyz.2");
}
like image 77
JB Nizet Avatar answered Oct 03 '22 19:10

JB Nizet


No There is no such conditional statement in properties file, May be you would write a wrapper over Properties to encapsulate your logic

Example:

class MyProperties extends Properties {


    /**
     * 
     * 
     * 
     * @param key
     * @param conditionalMap
     * @return
     */
    public String getProperty(String key, List<Decision> decisionList) {
        if (decisionList == null) {
            return getProperty(key);
        }
        Long value = Long.parseLong(getProperty(key));
        for (Decision decision : decisionList) {
            if (Condition.EQUALS == decision.getCondition() && decision.getValue().equals(value)) {
                return getProperty(decision.getTargetKey());
            }
        }
        return super.getProperty(key);
    }
}

and

enum Condition {
    EQUALS, GREATER, LESSER

}

and

class Decision {
    Condition condition;
    String targetKey;
    Long value;
    //accessor

    public Condition getCondition() {
        return condition;
    }

    public void setCondition(Condition condition) {
        this.condition = condition;
    }

    public String getTargetKey() {
        return targetKey;
    }

    public void setTargetKey(String targetKey) {
        this.targetKey = targetKey;
    }

}

so now for example if you want to read the properties file, get category of age, if it is greater than 0 and less than 10 read kid

so may be you could pass the list of such conditions,

note: This design can go under much improvement (not good design), it is just to illustrate how to wrap properties and add stuff that OP wants

like image 45
jmj Avatar answered Oct 03 '22 18:10

jmj