All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.cucumber.core.runtime.BackendServiceLoader Maven / Gradle / Ivy

There is a newer version: 7.20.1
Show newest version
package io.cucumber.core.runtime;

import io.cucumber.core.backend.Backend;
import io.cucumber.core.backend.BackendProviderService;
import io.cucumber.core.backend.ObjectFactory;
import io.cucumber.core.exception.CucumberException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ServiceLoader;
import java.util.function.Supplier;

/**
 * Supplies instances of {@link Backend} created by using a
 * {@link ServiceLoader} to locate instance of {@link BackendSupplier}.
 */
public final class BackendServiceLoader implements BackendSupplier {

    private final Supplier classLoaderSupplier;
    private final ObjectFactorySupplier objectFactorySupplier;

    public BackendServiceLoader(
            Supplier classLoaderSupplier, ObjectFactorySupplier objectFactorySupplier
    ) {
        this.classLoaderSupplier = classLoaderSupplier;
        this.objectFactorySupplier = objectFactorySupplier;
    }

    @Override
    public Collection get() {
        ClassLoader classLoader = classLoaderSupplier.get();
        return get(ServiceLoader.load(BackendProviderService.class, classLoader));
    }

    Collection get(Iterable serviceLoader) {
        Collection backends = loadBackends(serviceLoader);
        if (backends.isEmpty()) {
            throw new CucumberException(
                "No backends were found. Please make sure you have a backend module on your CLASSPATH.");
        }
        return backends;
    }

    private Collection loadBackends(Iterable serviceLoader) {
        List backends = new ArrayList<>();
        for (BackendProviderService backendProviderService : serviceLoader) {
            ObjectFactory objectFactory = objectFactorySupplier.get();
            backends.add(backendProviderService.create(objectFactory, objectFactory, classLoaderSupplier));
        }
        return backends;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy