001 /*****************************************************************************
002 * Copyright (c) PicoContainer Organization. All rights reserved. *
003 * ------------------------------------------------------------------------- *
004 * The software in this package is published under the terms of the BSD *
005 * style license a copy of which has been included with this distribution in *
006 * the license.html file. *
007 * *
008 * Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant *
009 *****************************************************************************/
010 package org.nanocontainer.persistence.jdbc;
011
012 import java.sql.Connection;
013 import java.sql.SQLException;
014
015 import javax.sql.DataSource;
016
017 import org.nanocontainer.persistence.ExceptionHandler;
018 import org.picocontainer.Startable;
019
020 /**
021 * Connection component implementation which obtains a connection instance using a injected datasource. It has failover
022 * support.
023 *
024 * @author Juze Peleteiro <juze -a-t- intelli -dot- biz>
025 */
026 public class FailoverDataSourceConnection extends AbstractConnection implements Startable {
027
028 private DataSource dataSource;
029
030 private Connection connection;
031
032 /**
033 * @param dataSource The DataSource instance where connections will be requested.
034 */
035 public FailoverDataSourceConnection(DataSource dataSource) {
036 this.dataSource = dataSource;
037 }
038
039 /**
040 * @param dataSource The DataSource instance where connections will be requested.
041 * @param jdbcExceptionHandler The ExceptionHandler component instance.
042 */
043 public FailoverDataSourceConnection(DataSource dataSource, ExceptionHandler exceptionHandler) {
044 super(exceptionHandler);
045 this.dataSource = dataSource;
046 }
047
048 /**
049 * @see org.nanocontainer.persistence.jdbc.AbstractConnection#getDelegatedConnection()
050 */
051 protected Connection getDelegatedConnection() throws SQLException {
052 if (connection == null) {
053 connection = dataSource.getConnection();
054 }
055
056 return connection;
057 }
058
059 /**
060 * @see org.nanocontainer.persistence.jdbc.AbstractConnection#invalidateDelegatedConnection()
061 */
062 protected void invalidateDelegatedConnection() {
063 try {
064 connection.rollback();
065 } catch (SQLException e) {
066 // Do nothing
067 }
068 try {
069 connection.close();
070 } catch (SQLException e) {
071 // Do nothing
072 }
073
074 connection = null;
075 }
076
077 /**
078 * @see org.picocontainer.Startable#start()
079 */
080 public void start() {
081 // Do nothing
082 }
083
084 /**
085 * @see org.picocontainer.Startable#stop()
086 */
087 public void stop() {
088 try {
089 connection.close();
090 } catch (Exception e) {
091 // Do nothing?
092 }
093 }
094
095 }