|
| 1 | +package org.cryptomator.integrations.common; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Comparator; |
| 5 | +import java.util.Optional; |
| 6 | +import java.util.ServiceLoader; |
| 7 | +import java.util.stream.Stream; |
| 8 | + |
| 9 | +public class IntegrationsLoader { |
| 10 | + |
| 11 | + /** |
| 12 | + * Loads the best suited service, i.e. the one with the highest priority that is supported. |
| 13 | + * <p> |
| 14 | + * If two services are available with the same priority, it is unspecified which one will be returned. |
| 15 | + * |
| 16 | + * @param clazz Service class |
| 17 | + * @param <T> Type of the service |
| 18 | + * @return Highest priority service or empty if no supported service was found |
| 19 | + */ |
| 20 | + public static <T> Optional<T> load(Class<T> clazz) { |
| 21 | + return loadAll(clazz).findFirst(); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Loads all suited services ordered by priority in descending order. |
| 26 | + * |
| 27 | + * @param clazz Service class |
| 28 | + * @param <T> Type of the service |
| 29 | + * @return An ordered stream of all suited service candidates |
| 30 | + */ |
| 31 | + public static <T> Stream<T> loadAll(Class<T> clazz) { |
| 32 | + return ServiceLoader.load(clazz) |
| 33 | + .stream() |
| 34 | + .filter(IntegrationsLoader::isSupportedOperatingSystem) |
| 35 | + .sorted(Comparator.comparingInt(IntegrationsLoader::getPriority).reversed()) |
| 36 | + .map(ServiceLoader.Provider::get); |
| 37 | + } |
| 38 | + |
| 39 | + private static int getPriority(ServiceLoader.Provider<?> provider) { |
| 40 | + var prio = provider.type().getAnnotation(Priority.class); |
| 41 | + return prio == null ? Priority.DEFAULT : prio.value(); |
| 42 | + } |
| 43 | + |
| 44 | + private static boolean isSupportedOperatingSystem(ServiceLoader.Provider<?> provider) { |
| 45 | + var annotations = provider.type().getAnnotationsByType(OperatingSystem.class); |
| 46 | + return annotations.length == 0 || Arrays.stream(annotations).anyMatch(OperatingSystem.Value::isCurrent); |
| 47 | + } |
| 48 | + |
| 49 | +} |
0 commit comments