DynamicDataSourceProxy extends DelegatingDataSource { public void switchDataSource(BoneCPConfig newConfig) throws SQLException { logger.info("Switch to new datasource requested. New Config: "+newConfig); DataSource oldDS = getTargetDataSource(); if (!(oldDS instanceof BoneCPDataSource)){ throw new SQLException("Unknown datasource type! Was expecting BoneCPDataSource but received "+oldDS.getClass()+". Not switching datasource!"); } BoneCPDataSource newDS = new BoneCPDataSource(newConfig); newDS.getConnection().close(); setTargetDataSource(newDS); logger.info("Shutting down old datasource slowly. Old Config: "+oldDS); ((BoneCPDataSource)oldDS).close(); } DynamicDataSourceProxy(DataSource targetDataSource);  DynamicDataSourceProxy(); void switchDataSource(BoneCPConfig newConfig);  }
@Test public void testSwitchDataSource() throws SQLException, ClassNotFoundException { BoneCPDataSource mockDataSource = createNiceMock(BoneCPDataSource.class); DynamicDataSourceProxy ddsp = new DynamicDataSourceProxy(); ddsp.setTargetDataSource(new DelegatingDataSource()); try{ ddsp.switchDataSource(null); fail("Should throw an exception"); } catch(SQLException e){ } BoneCPConfig config = new BoneCPConfig(); config.setJdbcUrl("jdbc:mock"); config.setUsername("sa"); config.setPassword(""); config.setMinConnectionsPerPartition(2); config.setMaxConnectionsPerPartition(2); config.setPartitionCount(1); ddsp = new DynamicDataSourceProxy(mockDataSource); mockDataSource.close(); expectLastCall().once(); replay(mockDataSource); ddsp.switchDataSource(config); assertNotSame(mockDataSource, ddsp.getTargetDataSource()); verify(mockDataSource); }