org.deephacks.tools4j.config.model.Lookup Maven / Gradle / Ivy
package org.deephacks.tools4j.config.model;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
/**
* 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 static final Logger log = LoggerFactory.getLogger(Lookup.class);
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();
log.trace("System property successfully overrides default lookup to {}",
overrideClassName);
} else {
LOOKUP = new Lookup();
}
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(
"Could not find class indicated by system property %s, using default lookup instead.",
overrideClassName, e);
}
log.warn(
"Could not find class indicated by system property %s, using default lookup instead.",
overrideClassName);
}
ServiceLoaderLookup serviceLoaderLookup = new ServiceLoaderLookup();
LOOKUP.lookupProviders.add(serviceLoaderLookup);
Collection providers = serviceLoaderLookup
.lookupAll(LookupProvider.class);
LOOKUP.lookupProviders.addAll(providers);
log.debug("{}", LOOKUP);
}
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();
}
}