ServiceLoaderLocator.java

  1. /*
  2.  * *********************************************************************************************************************
  3.  *
  4.  * TheseFoolishThings: Miscellaneous utilities
  5.  * http://tidalwave.it/projects/thesefoolishthings
  6.  *
  7.  * Copyright (C) 2009 - 2023 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
  12.  * the License. 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
  17.  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
  18.  * specific language governing permissions and limitations under the License.
  19.  *
  20.  * *********************************************************************************************************************
  21.  *
  22.  * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src
  23.  * git clone https://github.com/tidalwave-it/thesefoolishthings-src
  24.  *
  25.  * *********************************************************************************************************************
  26.  */
  27. package it.tidalwave.role.impl;

  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.  * @author  Fabrizio Giudici
  43.  *
  44.  **********************************************************************************************************************/
  45. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  46. // PreferencesHandler can be used to programmatically set the log folder, so don't inject logger
  47. public class ServiceLoaderLocator
  48.   {
  49.     /*******************************************************************************************************************
  50.      *
  51.      ******************************************************************************************************************/
  52.     @Nonnull
  53.     public static <T> T findService (@Nonnull final Class<? extends T> serviceClass)
  54.       {
  55.         final var serviceClassName = serviceClass.getSimpleName();
  56.         final var classLoader = Thread.currentThread().getContextClassLoader();
  57.         final var iterator = ServiceLoader.load(serviceClass, classLoader).iterator();
  58.         final var spliterator = Spliterators.spliteratorUnknownSize(iterator, 0);
  59.         var providers = StreamSupport.stream(spliterator, false).collect(toList());

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

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

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

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

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

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