package eu.dnetlib.utils.sql;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * This factory class is used for retrieving a singleton JDBC connection. 
 * @author thanos@di.uoa.gr
 *
 */
public class ConnectionFactory {
	private String driver;
	private String url;
	private Connection connection;
	
	/**
	 * Set the driver.
	 * @param driver the new JDBC driver that this factory will use
	 */
	public void setDriver(String driver) {
		this.driver = driver;
	}
	
	/**
	 * Set the URL.
	 * @param url the new URL that this factory will connect to
	 */
	public void setUrl(String url) {
		this.url = url;
	}
	
	/**
	 * Get the connection.
	 * @return the JDBC connection created by this connection factory
	 */
	public Connection getConnection() {
		return connection;
	}
	
	/**
	 * Open JDBC connection to the specified URL using the specified JDBC driver (used for Spring initialization).
	 * @throws ConnectionFactoryException if any errors occur
	 */
	public void init() throws ConnectionFactoryException {
		try {
			Class.forName(driver).newInstance();
			connection = DriverManager.getConnection(url);
		} catch (Exception e) {
			throw new ConnectionFactoryException("error connecting to " + url + " using JDBC driver " + driver, e);
		}
	}
	
	/**
	 * Close JDBC connection (used for Spring finalization).
	 * @throws ConnectionFactoryException if any errors occur
	 */
	public void destroy() throws ConnectionFactoryException {
		try {
			connection.close();
		} catch (Exception e) {
			throw new ConnectionFactoryException("error closing connection", e);
		}
	}
}
