001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.db;
015
016import java.sql.Connection;
017import java.sql.DriverManager;
018import java.sql.SQLException;
019
020/**
021 * The DriverManagerConnectionSource is an implementation of
022 * {@link ConnectionSource} that obtains the Connection in the traditional JDBC
023 * manner based on the connection URL.
024 * <p>
025 * For more information about this component, please refer to the online manual at
026 * http://logback.qos.ch/manual/appenders.html#DBAppender
027 * 
028 * @author <a href="mailto:rdecampo@twcny.rr.com">Ray DeCampo</a>
029 */
030public class DriverManagerConnectionSource extends ConnectionSourceBase {
031    private String driverClass = null;
032    private String url = null;
033
034    public void start() {
035        try {
036            if (driverClass != null) {
037                Class.forName(driverClass);
038                discoverConnectionProperties();
039            } else {
040                addError("WARNING: No JDBC driver specified for logback DriverManagerConnectionSource.");
041            }
042        } catch (final ClassNotFoundException cnfe) {
043            addError("Could not load JDBC driver class: " + driverClass, cnfe);
044        }
045    }
046
047    /**
048     * @see ch.qos.logback.core.db.ConnectionSource#getConnection()
049     */
050    public Connection getConnection() throws SQLException {
051        if (getUser() == null) {
052            return DriverManager.getConnection(url);
053        } else {
054            return DriverManager.getConnection(url, getUser(), getPassword());
055        }
056    }
057
058    /**
059     * Returns the url.
060     * 
061     * @return String
062     */
063    public String getUrl() {
064        return url;
065    }
066
067    /**
068     * Sets the url.
069     * 
070     * @param url
071     *          The url to set
072     */
073    public void setUrl(String url) {
074        this.url = url;
075    }
076
077    /**
078     * Returns the name of the driver class.
079     * 
080     * @return String
081     */
082    public String getDriverClass() {
083        return driverClass;
084    }
085
086    /**
087     * Sets the driver class.
088     * 
089     * @param driverClass
090     *          The driver class to set
091     */
092    public void setDriverClass(String driverClass) {
093        this.driverClass = driverClass;
094    }
095}