View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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        Connection connection = null;
45        try {
46          connection = getConnection();
47        } catch (SQLException se) {
48          addWarn("Could not get a connection to discover the dialect to use.",
49              se);
50        }
51        if (connection != null) {
52          discoverConnnectionProperties();
53        }
54        if (!supportsGetGeneratedKeys()
55            && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) {
56          addWarn("Connection does not support GetGeneratedKey method and could not discover the dialect.");
57        }
58      }
59      super.start();
60    }
61  
62    /**
63     * @see ch.qos.logback.classic.db.ConnectionSource#getConnection()
64     */
65    public Connection getConnection() throws SQLException {
66      if (dataSource == null) {
67        addError("WARNING: No data source specified");
68        return null;
69      }
70  
71      if (getUser() == null) {
72        return dataSource.getConnection();
73      } else {
74        return dataSource.getConnection(getUser(), getPassword());
75      }
76    }
77  
78    public DataSource getDataSource() {
79      return dataSource;
80    }
81  
82    public void setDataSource(DataSource dataSource) {
83      this.dataSource = dataSource;
84    }
85  }