package org.mapache.business.configuration;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.mapache.business.MapacheException;
import org.mapache.data.DAOFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class ConfigurationManager {
public static ConfigurationManager instance;
private Configuration configuration;
private ConfigurationManager() {
try {
configuration = readConfiguration();
} catch (MapacheException e) {
e.printStackTrace();
}
}
public static ConfigurationManager getInstance() {
if (instance == null)
instance = new ConfigurationManager();
return instance;
}
public DAOFactory getDAOFactory() {
if (configuration.getDatabaseType() == DAOFactory.MYSQL)
return DAOFactory.getDAOFactory(DAOFactory.MYSQL);
return null;
}
public Configuration getConfiguraton() {
return configuration;
}
private Configuration readConfiguration() throws MapacheException {
File configFile;
//try {
configFile =// new File("/home/web/student3/maenhoutw/www/www.awosy.be/public_html/WEB-INF/config.xml");
new File(((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/WEB-INF/config.xml"));
/*} catch (MalformedURLException e) {
throw new MapacheException("Unable to read configuration file",e);
}*/
Document document;
Configuration config = new Configuration();
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(configFile);
XPathFactory xpFactory = XPathFactory.newInstance();
XPath xpath = xpFactory.newXPath();
config.setDatabaseType(Integer.parseInt(xpath.evaluate("/config/database/type",document)));
config.setDatabaseServerPath(xpath.evaluate("/config/database/serverPath",document));
config.setDatabaseSchema(xpath.evaluate("/config/database/schema",document));
config.setDatabaseUser(xpath.evaluate("/config/database/user",document));
config.setDatabasePass(xpath.evaluate("/config/database/pass",document));
config.setEmail(xpath.evaluate("/config/blog/administrator-email",document));
config.setSmtp(xpath.evaluate("/config/blog/administrator-smtp",document));
} catch (SAXException e) {
throw new MapacheException("Unable to read configuration file",e);
} catch (IOException e) {
throw new MapacheException("Unable to read configuration file",e);
} catch (XPathExpressionException e) {
throw new MapacheException("Unable to read configuration file",e);
} catch (ParserConfigurationException e) {
throw new MapacheException("Unable to read configuration file",e);
}
return config;
}
}