ServiceLoaderLocator.java

  1. /*
  2.  * *************************************************************************************************************************************************************
  3.  *
  4.  * TheseFoolishThings: Miscellaneous utilities
  5.  * http://tidalwave.it/projects/thesefoolishthings
  6.  *
  7.  * Copyright (C) 2009 - 2025 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.util.impl;

  27. import jakarta.annotation.Nonnull;
  28. import java.util.ServiceLoader;
  29. import java.util.Spliterators;
  30. import java.util.stream.StreamSupport;
  31. import org.slf4j.Logger;
  32. import org.slf4j.LoggerFactory;
  33. import it.tidalwave.util.LazySupplier;
  34. import it.tidalwave.util.PreferencesHandler;
  35. import it.tidalwave.role.spi.annotation.DefaultProvider;
  36. import lombok.AccessLevel;
  37. import lombok.NoArgsConstructor;
  38. import static java.util.stream.Collectors.*;

  39. /***************************************************************************************************************************************************************
  40.  *
  41.  * @author  Fabrizio Giudici
  42.  *
  43.  **************************************************************************************************************************************************************/
  44. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  45. // PreferencesHandler can be used to programmatically set the log folder, so don't inject logger
  46. public class ServiceLoaderLocator
  47.   {
  48.     public static final String PROPS_BASE_NAME = PreferencesHandler.class.getPackage().getName();

  49.     /** Suppress any console output. @since 3.2-ALPHA-21 */
  50.     public static final String PROP_SUPPRESS_CONSOLE = PROPS_BASE_NAME + ".suppressConsoleOutput";

  51.     /***********************************************************************************************************************************************************
  52.      *
  53.      **********************************************************************************************************************************************************/
  54.     @Nonnull
  55.     public static <T> T findService (@Nonnull final Class<? extends T> serviceClass)
  56.       {
  57.         final var serviceClassName = serviceClass.getSimpleName();
  58.         final var classLoader = Thread.currentThread().getContextClassLoader();
  59.         final var iterator = ServiceLoader.load(serviceClass, classLoader).iterator();
  60.         final var spliterator = Spliterators.spliteratorUnknownSize(iterator, 0);
  61.         var providers = StreamSupport.stream(spliterator, false).collect(toList());

  62.         if (providers.isEmpty())
  63.           {
  64.             throw new RuntimeException("No ServiceProvider for " + serviceClassName);
  65.           }

  66.         if (providers.size() > 1) // filter out the default one
  67.           {
  68.             getLogger().info("Too many instances of {}, using @DefaultProvider ...", serviceClassName);
  69.             providers = providers.stream()
  70.                                  .filter(p -> p.getClass().getAnnotation(DefaultProvider.class) == null)
  71.                                  .collect(toList());
  72.           }

  73.         if (providers.size() > 1)
  74.           {
  75.             throw new RuntimeException("Too many instances of " + serviceClassName + " : " + providers);
  76.           }

  77.         final var provider = providers.get(0);
  78.        
  79.         // PreferencesHandler can be used to programmatically set the log folder, so don't log yet
  80.         if (!serviceClass.equals(PreferencesHandler.class))
  81.           {
  82.             getLogger().info("{} instantiated from META-INF/services: {}", serviceClassName, provider);
  83.           }
  84.         else if (!Boolean.getBoolean(PROP_SUPPRESS_CONSOLE))
  85.           {
  86.             System.out.printf("%s instantiated from META-INF/services: %s%n", serviceClassName, provider);
  87.           }

  88.         return provider;
  89.       }

  90.     @Nonnull
  91.     public static <T> LazySupplier<T> lazySupplierOf (@Nonnull final Class<? extends T> clazz)
  92.       {
  93.         return LazySupplier.of(() -> findService(clazz));
  94.       }

  95.     @Nonnull
  96.     private static Logger getLogger()
  97.       {
  98.         return LoggerFactory.getLogger(ServiceLoaderLocator.class);
  99.       }
  100.   }