Example usage for org.springframework.jdbc.datasource DataSourceUtils getConnection

List of usage examples for org.springframework.jdbc.datasource DataSourceUtils getConnection

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceUtils getConnection.

Prototype

public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException 

Source Link

Document

Obtain a Connection from the given DataSource.

Usage

From source file:org.apache.syncope.core.provisioning.java.job.JobManagerImpl.java

private boolean isRunningElsewhere(final JobKey jobKey) throws SchedulerException {
    if (!scheduler.getScheduler().getMetaData().isJobStoreClustered()) {
        return false;
    }//from   w  ww . j ava  2 s .  c o m

    DataSource dataSource = domainsHolder.getDomains().get(SyncopeConstants.MASTER_DOMAIN);
    Connection conn = DataSourceUtils.getConnection(dataSource);
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    try {
        stmt = conn.prepareStatement("SELECT 1 FROM " + Constants.DEFAULT_TABLE_PREFIX + "FIRED_TRIGGERS "
                + "WHERE JOB_NAME = ? AND JOB_GROUP = ?");
        stmt.setString(1, jobKey.getName());
        stmt.setString(2, jobKey.getGroup());

        resultSet = stmt.executeQuery();
        return resultSet.next();
    } catch (SQLException e) {
        throw new SchedulerException(e);
    } finally {
        IOUtil.quietClose(resultSet);
        IOUtil.quietClose(stmt);
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}

From source file:org.apache.syncope.core.util.ContentExporter.java

public void export(final OutputStream os, final String wfTablePrefix)
        throws SAXException, TransformerConfigurationException {

    if (StringUtils.isNotBlank(wfTablePrefix)) {
        TABLE_PREFIXES_TO_BE_EXCLUDED.add(wfTablePrefix);
    }// www  .  ja v  a2  s  .c  o m

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, SyncopeConstants.DEFAULT_ENCODING);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    Connection conn = null;
    ResultSet rs = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
        final DatabaseMetaData meta = conn.getMetaData();

        final String schema = dbSchema;

        rs = meta.getTables(null, schema, null, new String[] { "TABLE" });

        final Set<String> tableNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            LOG.debug("Found table {}", tableName);
            if (isTableAllowed(tableName)) {
                tableNames.add(tableName);
            }
        }

        LOG.debug("Tables to be exported {}", tableNames);

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames)) {
            try {
                doExportTable(handler, conn, tableName, TABLES_TO_BE_FILTERED.get(tableName.toUpperCase()));
            } catch (Exception e) {
                LOG.error("Failure exporting table {}", tableName, e);
            }
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }

        DataSourceUtils.releaseConnection(conn, dataSource);
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException e) {
                LOG.error("While releasing connection", e);
            }
        }
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:org.connid.bundles.soap.wssample.ProvisioningImpl.java

/**
 * Establish a connection to underlying db.
 *
 * @return//from  w  w w.  ja v a 2 s .  c  o m
 * @throws ClassNotFoundException
 * @throws SQLException
 */
private Connection connect() throws SQLException {

    if (DefaultContentLoader.localDataSource == null) {
        LOG.error("Data Source is null");
        return null;
    }

    Connection conn = DataSourceUtils.getConnection(DefaultContentLoader.localDataSource);

    if (conn == null) {
        LOG.error("Connection is null");
    }

    return conn;

}

From source file:org.eurekastreams.testing.DBUnitFixtureSetup.java

/**
 * Load up the XML dataset found at the input file path, using the data source found in the bean "dataSource" in
 * Spring files found in "classpath:applicationContext*-test.xml".
 *
 * @param newDatasetPath/*from  ww  w. ja v a2s .  c  o m*/
 *            The resource path of the dataset xml file - for example: "/dataset.xml"
 * @throws Exception
 *             on any errors
 */
public static void loadDataSet(final String newDatasetPath) throws Exception {
    if (currentlyLoadedDatasetPath != null && currentlyLoadedDatasetPath.equalsIgnoreCase(newDatasetPath)) {
        System.out.println("Dataset '" + newDatasetPath + "' is currently loaded - skipping.");
        return;
    }
    long start = System.currentTimeMillis();
    System.out.println("Loading dataset '" + newDatasetPath + "'.");

    // Get the Spring application context
    ApplicationContext appContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT_LOCATIONS);

    // Get the data source from Spring
    DataSource dataSource = (DataSource) appContext.getBean(DATA_SOURCE_BEAN_NAME);

    logger.info("About to load up the test dataset at path '" + newDatasetPath + "'");

    // Get the connection to the database
    Connection connection = DataSourceUtils.getConnection(dataSource);
    IDatabaseConnection dbUnitCon = new DatabaseConnection(connection);

    // Get the data from the file at the input resource path
    IDataSet dataSet = new FlatXmlDataSet(DBUnitFixtureSetup.class.getResourceAsStream(newDatasetPath));

    // insert the data set into the database with a clean insert
    try {
        DatabaseOperation.CLEAN_INSERT.execute(dbUnitCon, dataSet);
    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }

    System.out.println(
            "Loaded dataset '" + newDatasetPath + "' in " + (System.currentTimeMillis() - start) + "ms");
    currentlyLoadedDatasetPath = newDatasetPath;
}

From source file:org.eurekastreams.testing.FeedReaderDBUnitFixtureSetup.java

/**
 * Load up the XML dataset found at the input file path, using the data
 * source found in the bean "dataSource" in Spring files found in
 * "classpath:applicationContext*-test.xml".
 * /*from  www  . jav a 2  s  .co m*/
 * @param newDatasetPath
 *            The resource path of the dataset xml file - for example:
 *            "/dataset.xml"
 * @throws Exception
 *             on any errors
 */
public static void loadDataSet(final String newDatasetPath) throws Exception {
    // Get the Spring application context
    ApplicationContext appContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT_LOCATIONS);

    // Get the data source from Spring
    DataSource dataSource = (DataSource) appContext.getBean(DATA_SOURCE_BEAN_NAME);

    logger.info("About to load up the test dataset at path '" + newDatasetPath + "'");

    // Get the connection to the database
    Connection connection = DataSourceUtils.getConnection(dataSource);
    IDatabaseConnection dbUnitCon = new DatabaseConnection(connection);

    // Get the data from the file at the input resource path
    IDataSet dataSet = new FlatXmlDataSet(
            FeedReaderDBUnitFixtureSetup.class.getResourceAsStream(newDatasetPath));

    // insert the data set into the database with a clean insert
    try {
        DatabaseOperation.CLEAN_INSERT.execute(dbUnitCon, dataSet);
    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }
}

From source file:org.jamwiki.db.DatabaseConnection.java

/**
 *
 *//*from  w ww .j  a  va 2 s .c om*/
protected static Connection getConnection() throws SQLException {
    if (dataSource == null) {
        // DataSource has not yet been created, obtain it now
        configDataSource();
    }
    return DataSourceUtils.getConnection(dataSource);
}

From source file:org.libreplan.business.common.test.dbunit.DBUnitTestExecutionListener.java

@Override
public void beforeTestMethod(TestContext testContext) throws Exception {

    super.beforeTestMethod(testContext);

    DataSource dataSource = getDataSource(testContext);
    Connection conn = DataSourceUtils.getConnection(dataSource);
    IDatabaseConnection dbUnitConn = getDBUnitConnection(conn);

    try {//from   w  ww.  ja v  a 2 s .c o m
        IDataSet dataSets[] = getDataSets(testContext);
        for (IDataSet dataSet : dataSets) {
            DatabaseOperation.CLEAN_INSERT.execute(dbUnitConn, dataSet);
            logger.debug("Performed CLEAN_INSERT of IDataSet.");
        }
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}

From source file:org.mifos.framework.util.DbUnitUtilities.java

public void loadDataFromFile(String filename, DriverManagerDataSource dataSource)
        throws DatabaseUnitException, SQLException, IOException {
    Connection jdbcConnection = null;
    IDataSet dataSet = getDataSetFromDataSetDirectoryFile(filename);
    try {/*from w ww . ja va2  s . c o m*/
        jdbcConnection = DataSourceUtils.getConnection(dataSource);
        IDatabaseConnection databaseConnection = new DatabaseConnection(jdbcConnection);
        DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataSet);
    } finally {
        if (jdbcConnection != null) {
            jdbcConnection.close();
        }
        DataSourceUtils.releaseConnection(jdbcConnection, dataSource);
    }
}

From source file:org.mifos.framework.util.DbUnitUtilities.java

/**
 * Returns a DbUnit DataSet for several tables.
 * @param driverManagerDataSource TODO//from  w  ww.java  2 s. c  om
 * @param tableNames
 * @return IDataSet
 * @throws Exception
 */
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
public IDataSet getDataSetForTables(DriverManagerDataSource driverManagerDataSource, String[] tableNames)
        throws Exception {
    Connection jdbcConnection = null;
    IDataSet databaseDataSet = null;
    try {
        jdbcConnection = DataSourceUtils.getConnection(driverManagerDataSource);
        IDatabaseTester databaseTester = new DataSourceDatabaseTester(driverManagerDataSource);
        IDatabaseConnection databaseConnection = databaseTester.getConnection();
        databaseDataSet = databaseConnection.createDataSet(tableNames);
    } finally {
        jdbcConnection.close();
        DataSourceUtils.releaseConnection(jdbcConnection, driverManagerDataSource);
    }
    return databaseDataSet;
}

From source file:org.opoo.oqs.spring.jdbc.TransactionSupportConnectionManager.java

public Connection getConnection() throws DataAccessException {
    if (dataSource == null) {
        throw new IllegalArgumentException("No DataSource specified");
    }/*from  ww w. j a v a  2s . c om*/

    Connection conn = (Connection) TransactionSynchronizationManager.getResource(dataSource);
    if (conn != null) {
        log.debug("Get connection from ThreadLocal.");
    } else { //(conn == null)
        conn = DataSourceUtils.getConnection(dataSource);
    }
    return conn;
}