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

io.ultreia.java4all.util.ServiceLoaders Maven / Gradle / Ivy

There is a newer version: 1.2.1
Show newest version
package io.ultreia.java4all.util;

/*-
 * #%L
 * Java Util extends by Ultreia.io
 * %%
 * Copyright (C) 2018 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * Created by tchemit on 30/05/2018.
 *
 * @author Tony Chemit - [email protected]
 */
public class ServiceLoaders {

    /**
     * Get service loader for given {@code serviceType}, applying a {@link ServiceLoader#reload()} before returns.
     *
     * @param serviceType type of service to load
     * @param          generic type of service to load
     * @return the service loader {@code reloaded}.
     * @since 1.0.10
     */
    public static  ServiceLoader reload(Class serviceType) {
        ServiceLoader result = ServiceLoader.load(serviceType);
        result.reload();
        return result;
    }

    /**
     * Load the unique implementation of the given {@code serviceType}.
     *
     * @param serviceType type of service to load
     * @param          generic type of service to load
     * @return the unique service found
     * @throws IllegalStateException if could not find the servcie, or if there is more than one implementations found.
     */
    public static  S loadUniqueService(Class serviceType) {
        Iterator iterator = ServiceLoader.load(serviceType).iterator();
        if (!iterator.hasNext()) {
            throw new IllegalStateException("No instance found for " + serviceType.getName());
        }
        S result = iterator.next();
        if (iterator.hasNext()) {
            throw new IllegalStateException("Found more than one instance for " + serviceType.getName());
        }
        return result;
    }

    /**
     * Load of classes of the given {@code serviceType} using {@link java.util.ServiceLoader} mecanism, but without
     * loading any of those services.
     *
     * @param serviceType type of service to seek
     * @param          type of service to seek
     * @return list of all implementation found via {@link java.util.ServiceLoader} mechanism for given type
     */
    public static  List> loadTypes(Class serviceType) {

        try {
            Enumeration resources = ServiceLoaders.class.getClassLoader().getResources("META-INF/services/" + serviceType.getName());
            List> result = new LinkedList<>();
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        line = line.trim();
                        if (!line.isEmpty()) {
                            try {
                                @SuppressWarnings("unchecked") Class aClass = (Class) Class.forName(line);
                                result.add(aClass);
                            } catch (ClassNotFoundException e) {
                                throw new IllegalStateException("Can't get class: " + line);
                            }
                        }
                    }
                }
            }
            return result;
        } catch (IOException e) {
            throw new IllegalStateException("Can't get loaders", e);
        }
    }
}