Skip to content

Commit 98f6ccb

Browse files
author
Soroosh Sarabadani
committed
Generalize mapping provider
1 parent bcbe1ce commit 98f6ccb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package io.javaoperatorsdk.operator;
2+
3+
import org.apache.commons.lang3.ClassUtils;
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
6+
7+
import java.io.BufferedReader;
8+
import java.io.IOException;
9+
import java.io.InputStreamReader;
10+
import java.net.URL;
11+
import java.util.*;
12+
import java.util.stream.Collectors;
13+
14+
15+
class ClassMappingProvider {
16+
private static final Logger log = LoggerFactory.getLogger(ClassMappingProvider.class);
17+
18+
static <T, V> Map<T, V> provide(final String resourcePath, T key, V value) {
19+
Map<T, V> result = new HashMap();
20+
try {
21+
final var classLoader = Thread.currentThread().getContextClassLoader();
22+
final Enumeration<URL> customResourcesMetadataList = classLoader.getResources(resourcePath);
23+
for (Iterator<URL> it = customResourcesMetadataList.asIterator(); it.hasNext(); ) {
24+
URL url = it.next();
25+
26+
List<String> classNamePairs = retrieveClassNamePairs(url);
27+
classNamePairs.forEach(clazzPair -> {
28+
try {
29+
final String[] classNames = clazzPair.split(",");
30+
if (classNames.length != 2) {
31+
throw new IllegalStateException(String.format("%s is not valid Mapping metadata, defined in %s", clazzPair, url.toString()));
32+
}
33+
34+
result.put(
35+
(T) ClassUtils.getClass(classNames[0]),
36+
(V) ClassUtils.getClass(classNames[1])
37+
);
38+
} catch (ClassNotFoundException e) {
39+
throw new RuntimeException(e);
40+
}
41+
});
42+
}
43+
log.debug("Loaded Controller to CustomResource mappings {}", result);
44+
return result;
45+
} catch (IOException e) {
46+
throw new RuntimeException(e);
47+
}
48+
}
49+
50+
private static List<String> retrieveClassNamePairs(URL url) throws IOException {
51+
return new BufferedReader(
52+
new InputStreamReader(url.openStream())
53+
).lines().collect(Collectors.toList());
54+
}
55+
}

0 commit comments

Comments
 (0)