Skip to content

Commit 2e2bd41

Browse files
committed
refactor: improve conversion code
Signed-off-by: Chris Laprun <metacosm@gmail.com>
1 parent 0a8a4de commit 2e2bd41

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/loader/DefaultConfigProvider.java

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,38 +38,47 @@ public DefaultConfigProvider() {
3838
* variable takes precedence when both are set.
3939
*/
4040
@Override
41-
@SuppressWarnings("unchecked")
4241
public <T> Optional<T> getValue(String key, Class<T> type) {
4342
String raw = resolveRaw(key);
4443
if (raw == null) {
4544
return Optional.empty();
4645
}
47-
return Optional.of(type.cast(convert(raw, type)));
46+
return Optional.of(convert(raw, type));
4847
}
4948

5049
private String resolveRaw(String key) {
51-
String envKey = key.replace('.', '_').replace('-', '_').toUpperCase();
50+
if(key == null) {
51+
return null;
52+
}
53+
String envKey = toEnvKey(key);
5254
String envValue = envLookup.apply(envKey);
5355
if (envValue != null) {
5456
return envValue;
5557
}
5658
return System.getProperty(key);
5759
}
5860

59-
private Object convert(String raw, Class<?> type) {
61+
private static String toEnvKey(String key) {
62+
return key.trim().replace('.', '_').replace('-', '_').toUpperCase();
63+
}
64+
65+
private static <T> T convert(String raw, Class<T> type) {
66+
final Object converted;
6067
if (type == String.class) {
61-
return raw;
68+
converted = raw;
6269
} else if (type == Boolean.class) {
63-
return Boolean.parseBoolean(raw);
70+
converted = Boolean.parseBoolean(raw);
6471
} else if (type == Integer.class) {
65-
return Integer.parseInt(raw);
72+
converted = Integer.parseInt(raw);
6673
} else if (type == Long.class) {
67-
return Long.parseLong(raw);
74+
converted = Long.parseLong(raw);
6875
} else if (type == Double.class) {
69-
return Double.parseDouble(raw);
76+
converted = Double.parseDouble(raw);
7077
} else if (type == Duration.class) {
71-
return Duration.parse(raw);
78+
converted = Duration.parse(raw);
79+
} else {
80+
throw new IllegalArgumentException("Unsupported config type: " + type.getName());
7281
}
73-
throw new IllegalArgumentException("Unsupported config type: " + type.getName());
82+
return type.cast(converted);
7483
}
7584
}

0 commit comments

Comments
 (0)