Java tutorial
/* * Copyright 2010-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.reusables.dbunit.handler; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.reusables.test.SpringTestUtils; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.test.context.TestContext; /** * Handler for a JDBC task using a {@link DataSource} bean from a Spring test context. * * @author marcel */ public class DataSourceOperationHandler extends AbstractOperationHandler { /** * @param testContext The Spring test context containing the application context. */ public DataSourceOperationHandler(final TestContext testContext) { super(testContext); } /** * @param task The task to handle. * @return False if the {@link DataSource} bean was not present. */ @Override public boolean handleOperation(final JdbcTask task) { final DataSource dataSource = getDataSource(); if (dataSource != null) { Connection connection = null; try { connection = dataSource.getConnection(); task.execute(connection); connection.close(); return true; } catch (final SQLException e) { throw new RuntimeException("Error executing JDBC task.", e); } finally { JdbcUtils.closeConnection(connection); } } return false; } /** * @return The {@link DataSource} to use. */ protected DataSource getDataSource() { return SpringTestUtils.findBeanByType(getTestContext().getApplicationContext(), DataSource.class); } }