internal.sdmxdl.file.spi.FileCachingLoader Maven / Gradle / Ivy
package internal.sdmxdl.file.spi;
import internal.sdmxdl.NoOpCaching;
import java.lang.Iterable;
import java.util.Collections;
import java.util.Comparator;
import java.util.ServiceLoader;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;
import sdmxdl.file.spi.FileCaching;
/**
* Custom service loader for {@link sdmxdl.file.spi.FileCaching}.
*
This class is thread-safe.
* Properties:
*
* - Quantifier: SINGLE
* - Fallback: {@link internal.sdmxdl.NoOpCaching}
* - Preprocessing: wrapper: none filters:[] sorters:[getFileCachingRank]
* - Mutability: NONE
* - Singleton: false
* - Name: internal.{{canonicalName}}Loader
* - Backend: null
* - Cleaner: null
* - Batch: false
* - Batch name: null
*
*/
public final class FileCachingLoader {
public static final Pattern ID_PATTERN = Pattern.compile("^[A-Z0-9]+(?:_[A-Z0-9]+)*$");
private final Iterable source = ServiceLoader.load(FileCaching.class);
private final Predicate filter = o -> ID_PATTERN.matcher(o.getFileCachingId()).matches();
private final Comparator sorter = Collections.reverseOrder(Comparator.comparingInt(FileCaching::getFileCachingRank));
private final FileCaching resource = doLoad();
private FileCaching doLoad() {
return StreamSupport.stream(source.spliterator(), false)
.filter(filter)
.sorted(sorter)
.findFirst()
.orElseGet(() -> NoOpCaching.INSTANCE);
}
/**
* Gets a {@link sdmxdl.file.spi.FileCaching} instance.
*
This method is thread-safe.
* @return the current non-null value
*/
public FileCaching get() {
return resource;
}
/**
* Gets a {@link sdmxdl.file.spi.FileCaching} instance.
*
This is equivalent to the following code: new FileCachingLoader().get()
*
Therefore, the returned value might be different at each call.
*
This method is thread-safe.
* @return a non-null value
*/
public static FileCaching load() {
return new FileCachingLoader().get();
}
}