aboutsummaryrefslogtreecommitdiff
path: root/v1/src/main/java/com/xtremelabs/robolectric/util/PropertiesHelper.java
blob: 9d62bf573868eddbd831fa7e0a1345be46ccd458 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.xtremelabs.robolectric.util;

import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PropertiesHelper {

    public static String doSingleSubstitution(String originalValue, Properties properties) {
        if (originalValue == null) {
            return null;
        }

        Pattern variablePattern = Pattern.compile("([^$]*)\\$\\{(.*?)\\}(.*)");

        String expandedValue = originalValue;
        Matcher variableMatcher = variablePattern.matcher(expandedValue);
        while (variableMatcher.matches()) {
            String propertyName = variableMatcher.group(2);
            String propertyValue = null;
            if (properties != null) {
                propertyValue = properties.getProperty(propertyName);
            }
            if (propertyValue == null) {
                propertyValue = System.getProperty(propertyName);
            }
            if (propertyValue == null) {
                return originalValue;
            }

            String sdkPathStart = variableMatcher.group(1);
            String sdkPathEnd = variableMatcher.group(3);
            expandedValue = sdkPathStart + propertyValue + sdkPathEnd;
            variableMatcher = variablePattern.matcher(expandedValue);
        }

        return expandedValue;
    }

    public static void doSubstitutions(Properties properties) {
        Enumeration<?> propertyNames = properties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String) propertyNames.nextElement();
            String propertyValue = properties.getProperty(propertyName);
            String expandedPropertyValue = doSingleSubstitution(propertyValue, properties);
            properties.setProperty(propertyName, expandedPropertyValue);
        }
    }
}