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