001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Florent Guillaume
016 */
017package org.nuxeo.ecm.core.persistence;
018
019import java.sql.Connection;
020import java.sql.SQLException;
021import java.util.Properties;
022
023import javax.naming.NamingException;
024import javax.sql.DataSource;
025import org.hibernate.HibernateException;
026import org.hibernate.cfg.Environment;
027import org.hibernate.connection.ConnectionProvider;
028import org.nuxeo.runtime.datasource.DataSourceHelper;
029
030/**
031 * ConnectionProvider for Hibernate that looks up the datasource
032 * from the nuxeo's container.
033 *
034 * @since 5.7
035 */
036public class NuxeoConnectionProvider implements ConnectionProvider {
037
038    protected DataSource ds;
039
040    @Override
041    public void configure(Properties props) {
042        String name = props.getProperty(Environment.DATASOURCE);
043        try {
044            ds = DataSourceHelper.getDataSource(name);
045        } catch (NamingException cause) {
046            throw new HibernateException("Cannot lookup datasource by name " + name, cause);
047        }
048    }
049
050    @Override
051    public Connection getConnection() throws SQLException {
052        return ds.getConnection();
053    }
054
055    @Override
056    public void closeConnection(Connection connection) throws SQLException {
057        connection.close();
058    }
059
060    @Override
061    public void close() throws HibernateException {
062        ds = null;
063    }
064
065    @Override
066    public boolean supportsAggressiveRelease() {
067        // don't try to close the connection after each statement
068        // (not used if connection release mode is auto)
069        return false;
070    }
071
072}