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