@Nonnull
    @SuppressWarnings("unchecked")
    public static <T extends Factory> T getFactoryByIdentifier(
            String identifier, Class<T> factoryClass) {

        final ServiceLoader<Factory> loader = ServiceLoader.load(Factory.class);
        final List<Factory> factoryList = new ArrayList<>();

        for (Factory factory : loader) {
            if (factory != null
                    && factory.identifier().equals(identifier)
                    && factoryClass.isAssignableFrom(factory.getClass())) {
                factoryList.add(factory);
            }
        }

        if (factoryList.isEmpty()) {
            throw new RuntimeException(
                    String.format(
                            "Cannot find factory with identifier \"%s\" in the classpath.\n\n"
                                    + "Available factory classes are:\n\n"
                                    + "%s",
                            identifier,
                            StreamSupport.stream(loader.spliterator(), false)
                                    .map(f -> f.getClass().getName())
                                    .sorted()
                                    .collect(Collectors.joining("\n"))));
        }

        if (factoryList.size() > 1) {
            throw new RuntimeException(
                    String.format(
                            "Multiple factories found in the classpath.\n\n"
                                    + "Ambiguous factory classes are:\n\n"
                                    + "%s",
                            factoryList.stream()
                                    .map(f -> f.getClass().getName())
                                    .sorted()
                                    .collect(Collectors.joining("\n"))));
        }

        return (T) factoryList.get(0);
    }
@Test
    void getFactoryByIdentifier() {
        assertThat(
                        FactoryDiscoveryUtils.getFactoryByIdentifier(
                                "data-source-factory-1", Factory.class))
                .isInstanceOf(DataSourceFactory1.class);

        assertThat(
                        FactoryDiscoveryUtils.getFactoryByIdentifier(
                                "data-sink-factory-1", Factory.class))
                .isInstanceOf(DataSinkFactory1.class);

        assertThatThrownBy(
                        () ->
                                FactoryDiscoveryUtils.getFactoryByIdentifier(
                                        "data-sink-factory-3", Factory.class))
                .hasMessageStartingWith(
                        "Cannot find factory with identifier \"data-sink-factory-3\" in the classpath");
    }