All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ursaj.hfs.tools.HfsDbAdapter Maven / Gradle / Ivy

/**
 * Copyright (C) 2011 UrsaJ Ltd (http://ursaj.com)
 *
 * 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 com.ursaj.hfs.tools;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Adapter to handle operations over DB. */
abstract class HfsDbAdapter {
    /** JNDI data source bean name. */
    public static final String DATA_SOURCE_BEAN_NAME = "dataSource";

    /** Class logger. */
    private static final Logger log = LoggerFactory.getLogger(HfsDbAdapter.class);

    /** Persistence data source. */
    private DataSource dataSource;

    /**
     * Gets persistence data source.
     *
     * @return Persistence data source.
     */
    public DataSource getDataSource() {
        if (dataSource == null) {
            try {
                dataSource = (DataSource) new InitialContext().lookup(getDataSourceName());
            }
            catch (NamingException e) {
                throw new IllegalStateException("Failed to lookup data source in local context.", e);
            }
        }

        return dataSource;
    }

    /**
     * Sets persistence data source.
     *
     * @param dataSource Persistence data source.
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * Gets persistence data source name in JNDI.
     *
     * @return Persistence data source name in JNDI.
     */
    public String getDataSourceName() {
        return DATA_SOURCE_BEAN_NAME;
    }

    /**
     * Do some activity within DB connection.
     *
     * @param action Unit of work to do within connection.
     * @param     Action result type.
     * @return Action result value.
     * @throws IOException In case of any IO exception.
     */
    protected  T doWithinConnection(Action action) throws IOException {
        Connection connection = null;

        try {
            connection = getDataSource().getConnection();
            connection.setAutoCommit(false);

            T result = action.execute(connection);

            connection.commit();
            connection.close();
            connection = null;

            return result;
        }
        catch (SQLException e) {
            throw new IOException("Failed to execute SQL request.", e);
        }
        finally {
            closeConnection(connection);
        }
    }

    /**
     * Close DB connection.
     *
     * @param connection DB connection to close.
     */
    private void closeConnection(Connection connection) {
        if (connection == null)
            return;

        try {
            connection.rollback();
        }
        catch (Throwable t) {
            log.info("Failed to rollback connection.", t);
        }

        try {
            connection.close();
        }
        catch (Throwable t) {
            log.info("Failed to close connection.", t);
        }
    }

    /**
     * Action to perform within DB connection.
     *
     * @param  Action result type.
     */
    protected interface Action {
        /**
         * Unit of work to perform within DB connection.
         *
         * @param connection DB connection to work with.
         * @return Operation result.
         * @throws IOException  Exception to throw on any IO error.
         * @throws SQLException Exception to throw on any SQL error.
         */
        T execute(Connection connection) throws SQLException, IOException;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy