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

au.net.causal.maven.plugins.boxdb.db.BoxLookup Maven / Gradle / Ivy

package au.net.causal.maven.plugins.boxdb.db;

import org.apache.maven.plugin.logging.Log;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Utility class for using SPI mechanism to look up box database factories.
 */
public class BoxLookup
{
    private final Map bundledTypeFactoryMap;
    private final Map nonBundledTypeFactoryMap;

    /**
     * Constructor for lookup.
     *
     * @param log logger to use for logging warnings.
     * @param loader classloader to use for finding service configuration resources.
     */
    public BoxLookup(Log log, ClassLoader loader)
    {
        this.bundledTypeFactoryMap = new HashMap<>();
        this.nonBundledTypeFactoryMap = new HashMap<>();

        for (BoxDatabaseFactory factory : ServiceLoader.load(BoxDatabaseFactory.class, loader))
        {
            //Special handling for bundled factories
            Map typeFactoryMap;
            boolean bundled = factory.getClass().isAnnotationPresent(BoxDbBundled.class);
            if (bundled)
                typeFactoryMap = bundledTypeFactoryMap;
            else
                typeFactoryMap = nonBundledTypeFactoryMap;

            BoxDatabaseFactory old = typeFactoryMap.put(factory.name(), factory);
            if (old != null)
                log.warn("Multiple box factories for type '" + factory.name() + "'");
        }
    }

    /**
     * Finds a factory by database type.
     *
     * @param type the database type.  e.g. 'postgres'
     *
     * @return the factory for this database type, or null if none exists.
     */
    public BoxDatabaseFactory findFactory(String type)
    {
        return nonBundledTypeFactoryMap.getOrDefault(type, bundledTypeFactoryMap.get(type));
    }

    /**
     * @return a list of all registered box database factories in the system.
     */
    public List getAvailableBoxFactories()
    {
        return Stream.concat(nonBundledTypeFactoryMap.values().stream(), bundledTypeFactoryMap.values().stream())
                     .sorted(Comparator.comparing(BoxDatabaseFactory::name))
                     .collect(Collectors.toList());
    }

    /**
     * @return a list of the names of all registered box database factories in the system.
     */
    public List getAvailableBoxFactoryNames()
    {
        return getAvailableBoxFactories().stream().map(BoxDatabaseFactory::name).distinct().collect(Collectors.toList());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy