/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.stonehenge.stocktrader.dal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stonehenge.stocktrader.mssql.MSSQLConnectionProvider;
import org.apache.stonehenge.stocktrader.mysql.MySQLConnectionProvider;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public final class DAOFactory {
private static final String PROP_DB_TYPE = "org.apache.stonehenge.stocktrader.database.type";
private static Properties prop = null;
private static ConnectionProvider connectionProvider;
private static DAOFactory self;
private ConfigServiceDAOImpl configServiceDAO;
private DAOFactory() {
configServiceDAO = new ConfigServiceDAOImpl();
loadProperties();
}
public static DAOFactory getFacotry() {
if (self == null) {
self = new DAOFactory();
}
return self;
}
public ConfigServiceDAO getConfigServiceDAO() {
if ("mysql".equals(prop.getProperty(PROP_DB_TYPE))) {
connectionProvider = new MySQLConnectionProvider();
} else if ("mssql".equals(prop.getProperty(PROP_DB_TYPE))) {
connectionProvider = new MSSQLConnectionProvider();
} else {
throw new IllegalArgumentException("Unknown Database type " + prop.getProperty(PROP_DB_TYPE));
}
Connection connection;
try {
connection = connectionProvider.provide(prop);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
configServiceDAO.setConnection(connection);
return configServiceDAO;
}
private static void loadProperties() {
Log logger = LogFactory.getLog(DAOFactory.class);
if (prop == null) {
prop = new Properties();
InputStream is = DAOFactory.class.getClassLoader().getResourceAsStream("db.properties");
if (is != null) {
try {
prop.load(is);
} catch (IOException e) {
logger.debug(
"Unable to load mysql-db properties file and using [jdbc:mysql://localhost/stocktraderdb?user=trade&password=trade] as the default connection",
e);
}
} else {
logger.debug(
"Unable to load mysql-db properties file and using [jdbc:mysql://localhost/stocktraderdb?user=trade&password=trade] as the default connection");
}
}
}
}