View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package ch.qos.logback.core.db;
12  
13  import java.sql.Connection;
14  import java.sql.SQLException;
15  
16  import javax.sql.DataSource;
17  
18  import ch.qos.logback.core.db.dialect.SQLDialectCode;
19  
20  /**
21   * The DataSourceConnectionSource is an implementation of
22   * {@link ConnectionSource} that obtains the Connection in the recommended JDBC
23   * manner based on a {@link javax.sql.DataSource DataSource}.
24   * <p>
25   * 
26   * For more information about this component, please refer to the online manual at
27   * http://logback.qos.ch/manual/appenders.html#DBAppender
28   * 
29   * @author Ray DeCampo
30   * @author Ceki G&uuml;lc&uuml;
31   */
32  public class DataSourceConnectionSource extends ConnectionSourceBase {
33  
34    private DataSource dataSource;
35  
36    @Override
37    public void start() {
38      if (dataSource == null) {
39        addWarn("WARNING: No data source specified");
40      } else {
41        Connection connection = null;
42        try {
43          connection = getConnection();
44        } catch (SQLException se) {
45          addWarn("Could not get a connection to discover the dialect to use.",
46              se);
47        }
48        if (connection != null) {
49          discoverConnnectionProperties();
50        }
51        if (!supportsGetGeneratedKeys()
52            && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) {
53          addWarn("Connection does not support GetGeneratedKey method and could not discover the dialect.");
54        }
55      }
56      super.start();
57    }
58  
59    /**
60     * @see ch.qos.logback.classic.db.ConnectionSource#getConnection()
61     */
62    public Connection getConnection() throws SQLException {
63      if (dataSource == null) {
64        addError("WARNING: No data source specified");
65        return null;
66      }
67  
68      if (getUser() == null) {
69        return dataSource.getConnection();
70      } else {
71        return dataSource.getConnection(getUser(), getPassword());
72      }
73    }
74  
75    public DataSource getDataSource() {
76      return dataSource;
77    }
78  
79    public void setDataSource(DataSource dataSource) {
80      this.dataSource = dataSource;
81    }
82  }