| 1 |
/* |
| 2 |
* Copyright (c) 2021 Red Hat and others |
| 3 |
* |
| 4 |
* This program and the accompanying materials are made available under the |
| 5 |
* Apache Software License 2.0 which is available at: |
| 6 |
* https://www.apache.org/licenses/LICENSE-2.0. |
| 7 |
* |
| 8 |
* SPDX-License-Identifier: Apache-2.0 |
| 9 |
*/ |
| 10 |
|
| 11 |
package jakarta.enterprise.inject.build.compatible.spi; |
| 12 |
|
| 13 |
import java.util.Collections; |
| 14 |
import java.util.Comparator; |
| 15 |
import java.util.ServiceConfigurationError; |
| 16 |
import java.util.ServiceLoader; |
| 17 |
import java.util.Set; |
| 18 |
import java.util.TreeSet; |
| 19 |
|
| 20 |
final class BuildServicesResolver { |
| 21 |
private static final Object lock = new Object(); |
| 22 |
private static volatile Set<BuildServices> discoveredBuildServices; |
| 23 |
private static volatile BuildServices configuredBuildServices; |
| 24 |
|
| 25 |
static BuildServices get() { |
| 26 |
if (configuredBuildServices != null) { |
| 27 |
return configuredBuildServices; |
| 28 |
} |
| 29 |
|
| 30 |
if (discoveredBuildServices == null) { |
| 31 |
synchronized (lock) { |
| 32 |
if (discoveredBuildServices == null) { |
| 33 |
discoverFactories(); |
| 34 |
} |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
configuredBuildServices = discoveredBuildServices.iterator().next(); |
| 39 |
|
| 40 |
return configuredBuildServices; |
| 41 |
} |
| 42 |
|
| 43 |
private static void discoverFactories() { |
| 44 |
Set<BuildServices> factories = new TreeSet<>( |
| 45 |
Comparator.comparingInt(BuildServices::getPriority).reversed()); |
| 46 |
|
| 47 |
ServiceLoader<BuildServices> loader = SecurityActions.loadService( |
| 48 |
BuildServices.class, BuildServicesResolver.class.getClassLoader()); |
| 49 |
|
| 50 |
if (!loader.iterator().hasNext()) { |
| 51 |
throw new IllegalStateException("Unable to locate AnnotationBuilderFactory implementation"); |
| 52 |
} |
| 53 |
|
| 54 |
try { |
| 55 |
for (BuildServices buildServicies : loader) { |
| 56 |
factories.add(buildServicies); |
| 57 |
} |
| 58 |
} catch (ServiceConfigurationError e) { |
| 59 |
throw new IllegalStateException(e); |
| 60 |
} |
| 61 |
|
| 62 |
BuildServicesResolver.discoveredBuildServices = Collections.unmodifiableSet(factories); |
| 63 |
} |
| 64 |
} |