org.deephacks.tools4j.config.model.Lookup Maven / Gradle / Ivy
package org.deephacks.tools4j.config.model;
import com.google.common.base.Objects;
import java.util.ArrayList;
import java.util.Collection;
/**
* Lookup is responsible for solving the problem of dynamic service discovery. Service providers
* register themselves and clients query for a suitable provider, without knowing how lookup is
* performed. The purpose is to achieve modularity and separation between components.
*/
public class Lookup extends LookupProvider {
private ArrayList lookupProviders;
private static Lookup LOOKUP;
protected Lookup() {
lookupProviders = new ArrayList();
}
/**
* Aquire the Lookup registry.
* @return The lookup registry.
*/
public static Lookup get() {
if (LOOKUP != null) {
return LOOKUP;
}
synchronized (Lookup.class) {
// allow for override of the Lookup.class
String overrideClassName = System.getProperty(Lookup.class.getName());
ClassLoader l = Thread.currentThread().getContextClassLoader();
try {
if (overrideClassName != null && !"".equals(overrideClassName)) {
LOOKUP = (Lookup) Class.forName(overrideClassName, true, l).newInstance();
} else {
LOOKUP = new Lookup();
}
} catch (Exception e) {
// ignore
}
ServiceLoaderLookup serviceLoaderLookup = new ServiceLoaderLookup();
LOOKUP.lookupProviders.add(serviceLoaderLookup);
Collection providers = serviceLoaderLookup
.lookupAll(LookupProvider.class);
LOOKUP.lookupProviders.addAll(providers);
}
return LOOKUP;
}
@Override
public Collection lookupAll(Class clazz) {
ArrayList result = new ArrayList<>();
for (LookupProvider lp : lookupProviders) {
result.addAll(lp.lookupAll(clazz));
}
return result;
}
@SuppressWarnings("unchecked")
public T lookup(Class clazz) {
Object object = objectRegistry.get(clazz);
if (object != null) {
return (T) object;
}
for (LookupProvider lp : lookupProviders) {
T result = lp.lookup(clazz);
if (result != null)
return result;
}
return null;
}
public void register(Class clazz, T object) {
objectRegistry.put(clazz, object);
}
public void registerLookup(LookupProvider provider) {
lookupProviders.add(provider);
}
public void unregisterLookup(LookupProvider provider) {
lookupProviders.remove(provider);
}
public String toString() {
return Objects.toStringHelper(Lookup.class).add("LOOKUP", LOOKUP.getClass().getName())
.add("lookupProviders", lookupProviders).toString();
}
}