1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package it.tidalwave.role.impl;
27
28 import jakarta.annotation.Nonnull;
29 import java.util.ServiceLoader;
30 import java.util.Spliterators;
31 import java.util.stream.StreamSupport;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import it.tidalwave.util.LazySupplier;
35 import it.tidalwave.util.PreferencesHandler;
36 import it.tidalwave.role.spi.annotation.DefaultProvider;
37 import lombok.AccessLevel;
38 import lombok.NoArgsConstructor;
39 import static java.util.stream.Collectors.*;
40
41
42
43
44
45
46 @NoArgsConstructor(access = AccessLevel.PRIVATE)
47
48 public class ServiceLoaderLocator
49 {
50 public static final String PROPS_BASE_NAME = PreferencesHandler.class.getPackage().getName();
51
52
53 public static final String PROP_SUPPRESS_CONSOLE = PROPS_BASE_NAME + ".suppressConsoleOutput";
54
55
56
57
58 @Nonnull
59 public static <T> T findService (@Nonnull final Class<? extends T> serviceClass)
60 {
61 final var serviceClassName = serviceClass.getSimpleName();
62 final var classLoader = Thread.currentThread().getContextClassLoader();
63 final var iterator = ServiceLoader.load(serviceClass, classLoader).iterator();
64 final var spliterator = Spliterators.spliteratorUnknownSize(iterator, 0);
65 var providers = StreamSupport.stream(spliterator, false).collect(toList());
66
67 if (providers.isEmpty())
68 {
69 throw new RuntimeException("No ServiceProvider for " + serviceClassName);
70 }
71
72 if (providers.size() > 1)
73 {
74 getLogger().info("Too many instances of {}, using @DefaultProvider ...", serviceClassName);
75 providers = providers.stream()
76 .filter(p -> p.getClass().getAnnotation(DefaultProvider.class) == null)
77 .collect(toList());
78 }
79
80 if (providers.size() > 1)
81 {
82 throw new RuntimeException("Too many instances of " + serviceClassName + " : " + providers);
83 }
84
85 final var provider = providers.get(0);
86
87
88 if (!serviceClass.equals(PreferencesHandler.class))
89 {
90 getLogger().info("{} instantiated from META-INF/services: {}", serviceClassName, provider);
91 }
92 else if (!Boolean.getBoolean(PROP_SUPPRESS_CONSOLE))
93 {
94 System.out.printf("%s instantiated from META-INF/services: %s%n", serviceClassName, provider);
95 }
96
97 return provider;
98 }
99
100 @Nonnull
101 public static <T> LazySupplier<T> lazySupplierOf (@Nonnull final Class<? extends T> clazz)
102 {
103 return LazySupplier.of(() -> findService(clazz));
104 }
105
106 @Nonnull
107 private static Logger getLogger()
108 {
109 return LoggerFactory.getLogger(ServiceLoaderLocator.class);
110 }
111 }