TaskProviderFactory.java
package de.dlr.bt.stc.task;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import org.apache.commons.lang3.tuple.Pair;
import de.dlr.bt.stc.config.ConfigurationManager;
import de.dlr.bt.stc.exceptions.STCException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public final class TaskProviderFactory {
private static TaskProviderFactory theInstance = null;
private final Map<Class<?>, Function<ConfigurationManager, ITaskProvider>> creators = new HashMap<>();
private TaskProviderFactory() {
}
public static synchronized TaskProviderFactory getInstance() {
if (theInstance == null)
theInstance = new TaskProviderFactory();
return theInstance;
}
public Function<ConfigurationManager, ITaskProvider> getCreator(Class<?> forClass) {
return creators.get(forClass);
}
public void registerCreator(Class<?> forClass, Function<ConfigurationManager, ITaskProvider> creator) {
creators.put(forClass, creator);
}
public ITaskProvider createInstance(Class<?> forClass, ConfigurationManager config) throws STCException {
if (!creators.containsKey(forClass))
throw new STCException("Cannot create provider for " + forClass.getName());
var creator = creators.get(forClass);
return creator.apply(config);
}
public Pair<TaskProviderSet, Boolean> createInstances(ConfigurationManager config) {
Set<Class<?>> cfgClasses = new HashSet<>();
for (var cfg : config.getConfigurations().values())
cfgClasses.add(cfg.getClass());
Boolean ok = true;
TaskProviderSet providers = new TaskProviderSet();
for (var cfgClass : cfgClasses) {
ITaskProvider instance;
try {
instance = createInstance(cfgClass, config);
} catch (STCException ste) {
ok = false;
log.error("Failed to create instance for {}, Exception {}", cfgClass, ste);
continue;
}
providers.addTaskProvider(instance);
}
return Pair.of(providers, ok);
}
}