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.SQLException; 018 019import javax.sql.DataSource; 020 021import ch.qos.logback.core.db.dialect.SQLDialectCode; 022 023/** 024 * The DataSourceConnectionSource is an implementation of 025 * {@link ConnectionSource} that obtains the Connection in the recommended JDBC 026 * manner based on a {@link javax.sql.DataSource DataSource}. 027 * <p> 028 * 029 * For more information about this component, please refer to the online manual at 030 * http://logback.qos.ch/manual/appenders.html#DBAppender 031 * 032 * @author Ray DeCampo 033 * @author Ceki Gülcü 034 */ 035public class DataSourceConnectionSource extends ConnectionSourceBase { 036 037 private DataSource dataSource; 038 039 @Override 040 public void start() { 041 if (dataSource == null) { 042 addWarn("WARNING: No data source specified"); 043 } else { 044 discoverConnectionProperties(); 045 if (!supportsGetGeneratedKeys() && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) { 046 addWarn("Connection does not support GetGeneratedKey method and could not discover the dialect."); 047 } 048 } 049 super.start(); 050 } 051 052 /** 053 * @see ch.qos.logback.core.db.ConnectionSource#getConnection() 054 */ 055 public Connection getConnection() throws SQLException { 056 if (dataSource == null) { 057 addError("WARNING: No data source specified"); 058 return null; 059 } 060 061 if (getUser() == null) { 062 return dataSource.getConnection(); 063 } else { 064 return dataSource.getConnection(getUser(), getPassword()); 065 } 066 } 067 068 public DataSource getDataSource() { 069 return dataSource; 070 } 071 072 public void setDataSource(DataSource dataSource) { 073 this.dataSource = dataSource; 074 } 075}