package de.spieleck.pcs.factory;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
;
public class DefaultFactory implements Factory {
protected String configFile;
private Properties properties;
public DefaultFactory() {
properties = new Properties();
}
public DefaultFactory(String configFile) throws IllegalArgumentException,
FileNotFoundException{
this();
setConfigFile(configFile);
}
public String getConfigFile() {
return configFile;
}
public Object getNewObject(String key) throws FactoryException,
NoSuchKeyException {
if(getProperties() == null){
String cfg = getConfigFile();
if(cfg == null || cfg.length() == 0)
throw new FactoryException("Factory not configured yet");
try{
reloadConfiguration();
} catch(Exception e){
throw new FactoryException(e.getMessage());
}
}
if(getProperties() == null){
throw new FactoryException("Factory not configured yet");
}
String className = properties.getProperty(key);
if(className == null)
throw new NoSuchKeyException("No matching key could be found");
try{
return Class.forName(className).newInstance();
} catch (Exception e){
throw new FactoryException(e.getMessage());
}
}
public void resetConfig() {
try{
reloadConfiguration();
} catch(IOException ie){
System.err.println("Could not reset config of " + this);
ie.printStackTrace();
}
}
public void setConfigFile(String configFile) throws IllegalArgumentException,
FileNotFoundException{
this.configFile = configFile;
try{
reloadConfiguration();
} catch(IOException i){
throw new IllegalArgumentException("A problem occured during "
+ "reading config file " + configFile );
}
}
private void reloadConfiguration() throws IOException, FileNotFoundException{
synchronized(configFile){
properties.load(new FileInputStream(getConfigFile()));
}
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}