CfgFactory.java
package de.dlr.bt.stc.config;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.configuration2.HierarchicalConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import com.google.common.base.Strings;
public final class CfgFactory {
private static CfgFactory theInstance = null;
private Map<String, Function<HierarchicalConfiguration<?>, ACfg>> creators = new HashMap<>();
private CfgFactory() {
}
public static synchronized CfgFactory getInstance() {
if (theInstance == null)
theInstance = new CfgFactory();
return theInstance;
}
public void registerCreator(String cfgType, Function<HierarchicalConfiguration<?>, ACfg> creator) {
creators.put(cfgType.toLowerCase(), creator);
}
public ACfg create(String cfgType, HierarchicalConfiguration<?> config) throws ConfigurationException {
if (Strings.isNullOrEmpty(cfgType))
throw new ConfigurationException("No type specified for " + config.getRootElementName());
var cfg = cfgType.toLowerCase();
if (!creators.containsKey(cfg))
throw new ConfigurationException("Cannot find creator for " + cfgType);
var creator = creators.get(cfg);
return creator.apply(config);
}
}