1 /*
2 * *************************************************************************************************************************************************************
3 *
4 * TheseFoolishThings: Miscellaneous utilities
5 * http://tidalwave.it/projects/thesefoolishthings
6 *
7 * Copyright (C) 2009 - 2024 by Tidalwave s.a.s. (http://tidalwave.it)
8 *
9 * *************************************************************************************************************************************************************
10 *
11 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
17 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
18 *
19 * *************************************************************************************************************************************************************
20 *
21 * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src
22 * git clone https://github.com/tidalwave-it/thesefoolishthings-src
23 *
24 * *************************************************************************************************************************************************************
25 */
26 package it.tidalwave.role.impl;
27
28 import javax.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 * @author Fabrizio Giudici
44 *
45 **************************************************************************************************************************************************************/
46 @NoArgsConstructor(access = AccessLevel.PRIVATE)
47 // PreferencesHandler can be used to programmatically set the log folder, so don't inject logger
48 public class ServiceLoaderLocator
49 {
50 public static final String PROPS_BASE_NAME = PreferencesHandler.class.getPackage().getName();
51
52 /** Suppress any console output. @since 3.2-ALPHA-21 */
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) // filter out the default one
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 // PreferencesHandler can be used to programmatically set the log folder, so don't log yet
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 }