Example usage for javax.sql DataSource getConnection

List of usage examples for javax.sql DataSource getConnection

Introduction

In this page you can find the example usage for javax.sql DataSource getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Attempts to establish a connection with the data source that this DataSource object represents.

Usage

From source file:migration.ProjektMigration.java

/**
 * Inits the connection target db./*www .j  a v  a2 s  .com*/
 */
private void initConnectionTargetDb() {
    final DataSource ds = (DataSource) this.factory.getBean("dataSource");
    try {
        this.tgt_con = ds.getConnection();
    } catch (final SQLException e) {
        e.printStackTrace(); // To change body of catch statement use File |
                             // Settings | File Templates.
    }
}

From source file:com.saysth.commons.quartz.LocalDataSourceJobStore.java

@Override
public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException {

    // Absolutely needs thread-bound DataSource to initialize.
    this.dataSource = SchedulerFactoryBean.getConfigTimeDataSource();
    if (this.dataSource == null) {
        throw new SchedulerConfigException("No local DataSource found for configuration - "
                + "'dataSource' property must be set on SchedulerFactoryBean");
    }/*from   w w  w  .  j  a  v  a 2  s .  c o m*/

    // Configure transactional connection settings for Quartz.
    setDataSource(TX_DATA_SOURCE_PREFIX + getInstanceName());
    setDontSetAutoCommitFalse(true);

    // Register transactional ConnectionProvider for Quartz.
    DBConnectionManager.getInstance().addConnectionProvider(TX_DATA_SOURCE_PREFIX + getInstanceName(),
            new ConnectionProvider() {
                public Connection getConnection() throws SQLException {
                    // Return a transactional Connection, if any.
                    return DataSourceUtils.doGetConnection(dataSource);
                }

                public void shutdown() {
                    // Do nothing - a Spring-managed DataSource has its own
                    // lifecycle.
                }
            });

    // Non-transactional DataSource is optional: fall back to default
    // DataSource if not explicitly specified.
    DataSource nonTxDataSource = SchedulerFactoryBean.getConfigTimeNonTransactionalDataSource();
    final DataSource nonTxDataSourceToUse = (nonTxDataSource != null ? nonTxDataSource : this.dataSource);

    // Configure non-transactional connection settings for Quartz.
    setNonManagedTXDataSource(NON_TX_DATA_SOURCE_PREFIX + getInstanceName());

    // Register non-transactional ConnectionProvider for Quartz.
    DBConnectionManager.getInstance().addConnectionProvider(NON_TX_DATA_SOURCE_PREFIX + getInstanceName(),
            new ConnectionProvider() {
                public Connection getConnection() throws SQLException {
                    // Always return a non-transactional Connection.
                    return nonTxDataSourceToUse.getConnection();
                }

                public void shutdown() {
                    // Do nothing - a Spring-managed DataSource has its own
                    // lifecycle.
                }
            });

    // No, if HSQL is the platform, we really don't want to use locks
    try {
        String productName = JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName").toString();
        productName = JdbcUtils.commonDatabaseName(productName);
        if (productName != null && productName.toLowerCase().contains("hsql")) {
            setUseDBLocks(false);
            setLockHandler(new SimpleSemaphore());
        }
    } catch (MetaDataAccessException e) {
        logWarnIfNonZero(1, "Could not detect database type.  Assuming locks can be taken.");
    }

    super.initialize(loadHelper, signaler);

}

From source file:net.testdriven.psiprobe.controllers.sql.ConnectionTestController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    DataSource dataSource = null;

    try {// w  w  w  . j  a  va  2  s  .c o m
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName);
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        try {
            // TODO: use Spring's jdbc template?
            try (Connection conn = dataSource.getConnection()) {
                DatabaseMetaData md = conn.getMetaData();

                List<Map<String, String>> dbMetaData = new ArrayList<>();

                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdName",
                        md.getDatabaseProductName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.dbProdVersion",
                        md.getDatabaseProductVersion());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverName",
                        md.getDriverName());
                addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcDriverVersion",
                        md.getDriverVersion());
                //                    addDbMetaDataEntry(dbMetaData, "probe.jsp.dataSourceTest.dbMetaData.jdbcVersion", String.valueOf(md.getJDBCMajorVersion()));

                return new ModelAndView(getViewName(), "dbMetaData", dbMetaData);
            }
        } catch (SQLException e) {
            String message = getMessageSourceAccessor()
                    .getMessage("probe.src.dataSourceTest.connection.failure", new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:com.netspective.axiom.connection.JakartaCommonsDbcpConnectionProvider.java

public final Connection getConnection(ValueContext vc, String dataSourceId)
        throws NamingException, SQLException {
    if (dataSourceId == null)
        throw new NamingException("name is NULL in " + this.getClass().getName() + ".getConnection(String)");

    DataSource source = getDataSource(vc, dataSourceId);

    if (source == null) {
        if (log.isDebugEnabled())
            log.debug("name not found in " + JakartaCommonsDbcpConnectionProvider.class.getName()
                    + ".getConnection('" + dataSourceId + "'). Available: " + getAvailableDataSources());
        throw new NamingException(
                "Data source '" + dataSourceId + "' not found in Jakarta Commons DBCP provider.");
    }/* www  .  j  a  v a 2s .c  o m*/

    return source.getConnection();
}

From source file:org.intalio.deploy.deployment.impl.DeployServiceDeployTest.java

public void setUp() throws Exception {
    PropertyConfigurator.configure(new File(TestUtils.getTestBase(), "log4j.properties").getAbsolutePath());

    Utils.deleteRecursively(_deployDir);

    manager = new MockComponentManager("MockEngine");

    service = loadDeploymentService("test1.xml");
    service.setDeployDirectory(_deployDir.getAbsolutePath());
    service.init();/*from w  ww .ja  v  a2 s .com*/

    DataSource ds = service.getDataSource();

    ClassPathResource script = new ClassPathResource("deploy.derby.sql");
    if (script == null)
        throw new IOException("Unable to find file: deploy.derby.sql");
    SQLScript sql = new SQLScript(script.getInputStream(), ds);
    sql.setIgnoreErrors(true);
    sql.setInteractive(false);
    sql.executeScript();

    Connection c = ds.getConnection();
    EasyStatement.execute(c, "DELETE FROM DEPLOY_RESOURCES");
    EasyStatement.execute(c, "DELETE FROM DEPLOY_COMPONENTS");
    EasyStatement.execute(c, "DELETE FROM DEPLOY_ASSEMBLIES");
    c.close();
}

From source file:com.alibaba.druid.benckmark.pool.Case3.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {
    final AtomicInteger count = new AtomicInteger();
    final AtomicInteger errorCount = new AtomicInteger();

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from w w w .  j a v a2  s.c o  m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery(sql);
                        while (rs.next()) {
                            rs.getInt(1);
                        }
                        rs.close();
                        stmt.close();

                        conn.close();
                        count.incrementAndGet();
                    }
                } catch (Throwable ex) {
                    errorCount.incrementAndGet();
                    ex.printStackTrace();
                } finally {
                    endLatch.countDown();
                }
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    Assert.assertEquals(LOOP_COUNT * threadCount, count.get());
    Thread.sleep(1);

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.funambol.server.db.RoutingDataSource.java

/**
 * Returns a routed connection based on the given partitioniningKey.
 * <br>/* w  ww .  j  a v a2  s. co  m*/
 * The defaultDataSource is used if:
 * <ui>
 *   <li>the partitioning criteria is null</li>
 *   <li>the partition returned by the partitioning criteria is null</li>
 *   <li>the partition returned by the partitioning criteria is unknown</li>
 *   <li>the partitioning criteria is null</li>
 * </ui>
 * If the used partitioning criteria throws a PartitioningCriteriaException
 * (see also LockedPartitionException) a SQLException is thrown to the caller.
 *
 * @param partitioningKey the partition key
 * @return a connection to the partition to use
 * @throws java.sql.SQLException if an error occurs
 */
public Connection getRoutedConnection(String partitioningKey) throws SQLException {
    if (lock.isLocked()) {
        //
        // If the datasource is locked, we try to acquire the lock with 20 seconds
        // as timeout. If we are able to get the lock, it means the datasource 
        // has been unlocked in the meantime. See configure method to see 
        // where the lock is acquired.
        // If we are not able to acquire the lock in 20 seconds an exception is
        // thrown. This means the configure() method requires more than 20 seconds
        // ...really bad case.
        //
        try {
            if (!lock.tryLock(20, TimeUnit.SECONDS)) {
                //
                // we don't have the lock !
                //
                throw new SQLException("Timeout expired waiting for a locked datasource");
            }
            lock.unlock();
        } catch (SQLException e) {
            throw e;
        } catch (Throwable e) {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
            SQLException sqlEx = new SQLException("Error waiting for unlocking event");
            sqlEx.initCause(e);
            throw sqlEx;
        }
    }

    if (!configured) {
        if (!initialized) {
            try {
                init();
            } catch (Exception e) {
                SQLException sqlEx = new SQLException("Error in initialization");
                sqlEx.initCause(e);
                throw sqlEx;
            }
        }
        try {
            configure();
        } catch (Exception e) {
            SQLException sqlEx = new SQLException("Error in configuration");
            sqlEx.initCause(e);
            throw sqlEx;
        }
    }

    if (partitioningCriteria == null) {
        return defaultDataSource.getConnection();
    }

    Partition partition = null;
    try {
        partition = partitioningCriteria.getPartition(partitioningKey);
        if (partition != null) {
            if (!partition.isActive()) {
                throw new SQLException("The partition for '" + partitioningKey + "' is locked");
            }
        }
    } catch (LockedPartitionException e) {
        SQLException sqlException = new SQLException("The partition for '" + partitioningKey + "' is locked");
        sqlException.initCause(e);
        throw sqlException;
    } catch (PartitioningCriteriaException e) {
        SQLException sqlException = new SQLException(
                "Unable to identify the target partition for '" + partitioningKey + "'");
        sqlException.initCause(e);
        throw sqlException;
    }

    if (partition == null) {
        return defaultDataSource.getConnection();
    }
    String partitionName = partition.getName();
    DataSource ds = dataSources.get(partitionName);

    if (ds == null) {
        return defaultDataSource.getConnection();
    }

    return ds.getConnection();
}

From source file:com.haiegoo.framework.ibatis.SqlMapClientMasterSlaveTemplate.java

/**
 * Execute the given data access action on a SqlMapExecutor.
 * @param action callback object that specifies the data access action
 * @return a result object returned by the action, or <code>null</code>
 * @throws DataAccessException in case of SQL Maps errors
 *///from  ww w  .  jav  a2 s.co m
public <T> T execute(SqlMapClientCallback<T> action, SqlMapClient sqlMapClient) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");
    Assert.notNull(sqlMapClient, "No SqlMapClient specified");

    // We always need to use a SqlMapSession, as we need to pass a Spring-managed
    // Connection (potentially transactional) in. This shouldn't be necessary if
    // we run against a TransactionAwareDataSourceProxy underneath, but unfortunately
    // we still need it to make iBATIS batch execution work properly: If iBATIS
    // doesn't recognize an existing transaction, it automatically executes the
    // batch for every single statement...

    SqlMapSession session = sqlMapClient.openSession();
    if (logger.isDebugEnabled()) {
        logger.debug("Opened SqlMapSession [" + session + "] for iBATIS operation");
    }
    Connection ibatisCon = null;

    try {
        Connection springCon = null;
        DataSource dataSource = sqlMapClient.getDataSource();
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

        // Obtain JDBC Connection to operate on...
        try {
            ibatisCon = session.getCurrentConnection();
            if (ibatisCon == null) {
                springCon = (transactionAware ? dataSource.getConnection()
                        : DataSourceUtils.doGetConnection(dataSource));
                session.setUserConnection(springCon);
                if (logger.isDebugEnabled()) {
                    logger.debug("Obtained JDBC Connection [" + springCon + "] for iBATIS operation");
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reusing JDBC Connection [" + ibatisCon + "] for iBATIS operation");
                }
            }
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        // Execute given callback...
        try {
            return action.doInSqlMapClient(session);
        } catch (SQLException ex) {
            throw getExceptionTranslator().translate("SqlMapClient operation", null, ex);
        } finally {
            try {
                if (springCon != null) {
                    if (transactionAware) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Connection", ex);
            }
        }

        // Processing finished - potentially session still to be closed.
    } finally {
        // Only close SqlMapSession if we know we've actually opened it
        // at the present level.
        if (ibatisCon == null) {
            session.close();
        }
    }
}

From source file:org.apache.openaz.xacml.admin.view.components.SQLPIPConfigurationComponent.java

protected void testJNDIConnection() {
    try {//www .ja  v  a  2 s.  c  o m
        Context initialContext = new InitialContext();
        DataSource dataSource = (DataSource) initialContext.lookup(this.textFieldDataSource.getValue());
        try (Connection connection = dataSource.getConnection()) {
            new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                    .show(Page.getCurrent());
        }
    } catch (NamingException e) {
        logger.error(e);
        new Notification("JNDI Naming Exception",
                "<br/>" + e.getLocalizedMessage()
                        + "<br/>Is the context defined in this J2EE Container instance?",
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    } catch (SQLException e) {
        logger.error(e);
        new Notification("SQL Exception",
                "<br/>" + e.getLocalizedMessage() + "<br/>Are the configuration parameters correct?",
                Type.ERROR_MESSAGE, true).show(Page.getCurrent());
    }
}