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

org.deephacks.tools4j.config.model.LookupProvider Maven / Gradle / Ivy

package org.deephacks.tools4j.config.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

public abstract class LookupProvider {
    protected final ConcurrentHashMap, Object> objectRegistry = new ConcurrentHashMap, Object>();

    /**
    * Look up an object matching a given interface.
    * 
    * @param clazz The type of the object we want to lookup.
    * @return The object, if found, otherwise null.
    */
    public abstract  T lookup(Class clazz);

    /**
    * Look up a list of objects that match a given interface.
    * 
    * @param clazz The type of the object we want to lookup.
    * @return The object(s), if found, otherwise null.
    */
    public abstract  Collection lookupAll(Class clazz);

    /**
     * ServiceLoaderLookup is responsible for handling standard java service loader lookup.
     */
    static class ServiceLoaderLookup extends LookupProvider {

        public ServiceLoaderLookup() {

        }

        public final  T lookup(Class clazz) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            for (T standardJavaProvider : java.util.ServiceLoader.load(clazz, cl)) {
                // return first provider found. May need more elaborate mechanism in future.
                if (standardJavaProvider == null) {
                    continue;
                }
                // return the provider that was first found.
                return standardJavaProvider;
            }
            return null;
        }

        @Override
        public  Collection lookupAll(Class clazz) {
            ArrayList result = new ArrayList();
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            for (T o : java.util.ServiceLoader.load(clazz, cl)) {
                // return first provider found. May need more elaborate mechanism in future.
                result.add(o);
            }
            return result;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy