Skip to content

Commit a55afb4

Browse files
committed
add ability to load external properties files
1 parent 79e0eea commit a55afb4

1 file changed

Lines changed: 39 additions & 9 deletions

File tree

src/main/java/de/rwth/idsg/steve/utils/PropertiesFileLoader.java

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
import com.google.common.base.Strings;
44
import lombok.extern.slf4j.Slf4j;
55

6+
import java.io.FileInputStream;
67
import java.io.FileNotFoundException;
8+
import java.io.IOException;
79
import java.io.InputStream;
810
import java.util.Properties;
911

@@ -18,15 +20,21 @@ public class PropertiesFileLoader {
1820

1921
private Properties prop;
2022

21-
public PropertiesFileLoader(String fileName) {
22-
try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
23-
if (is == null) {
24-
throw new FileNotFoundException("Property file '" + fileName + "' is not found in classpath");
25-
}
26-
prop = new Properties();
27-
prop.load(is);
28-
} catch (Exception e) {
29-
throw new RuntimeException(e);
23+
/**
24+
* The name parameter acts as
25+
* 1) the file name to load from classpath, and
26+
* 2) the system property which can be set to load from file system.
27+
*/
28+
public PropertiesFileLoader(String name) {
29+
String systemFileName = System.getProperty(name);
30+
31+
if (systemFileName == null) {
32+
log.info("Hint: The Java system property '{}' can be set to point to an external properties file, " +
33+
"which will be prioritized over the bundled one", name);
34+
loadFromClasspath(name);
35+
36+
} else {
37+
loadFromSystem(systemFileName);
3038
}
3139
}
3240

@@ -92,6 +100,28 @@ public Integer getOptionalInt(String key) {
92100
// Private helpers
93101
// -------------------------------------------------------------------------
94102

103+
private void loadFromSystem(String systemFileName) {
104+
try (FileInputStream inputStream = new FileInputStream(systemFileName)) {
105+
prop = new Properties();
106+
prop.load(inputStream);
107+
log.info("Loaded properties from {}", systemFileName);
108+
} catch (IOException e) {
109+
throw new RuntimeException(e);
110+
}
111+
}
112+
113+
private void loadFromClasspath(String fileName) {
114+
try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
115+
if (is == null) {
116+
throw new FileNotFoundException("Property file '" + fileName + "' is not found in classpath");
117+
}
118+
prop = new Properties();
119+
prop.load(is);
120+
} catch (Exception e) {
121+
throw new RuntimeException(e);
122+
}
123+
}
124+
95125
private static String trim(String key, String value) {
96126
String trimmed = value.trim();
97127
if (!trimmed.equals(value)) {

0 commit comments

Comments
 (0)