Example usage for javax.sql DataSource getClass

List of usage examples for javax.sql DataSource getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:onlinefrontlines.admin.web.ServerInfoAction.java

/**
 * Query data source status/*from   ww  w  .  jav a  2 s. c om*/
 * 
 * @param dataSourceName Name of the data source
 */
private String getDataSourceStatus(String dataSourceName) {
    DataSource dataSource = (DataSource) DbConnectionPool.getInstance().getDataSources().get(dataSourceName);
    if (dataSource.getClass().getName().equals("org.apache.commons.dbcp.BasicDataSource")
            && dataSource instanceof org.apache.commons.dbcp.BasicDataSource) {
        org.apache.commons.dbcp.BasicDataSource s = (org.apache.commons.dbcp.BasicDataSource) dataSource;
        return "Busy: " + s.getNumActive() + " (" + (int) (s.getNumActive() * 100 / s.getMaxActive())
                + "%), Connections: " + (s.getNumIdle() + s.getNumActive()) + ", Max: " + s.getMaxActive();
    } else if (dataSource.getClass().getName().equals("org.apache.tomcat.dbcp.dbcp.BasicDataSource")
            && dataSource instanceof org.apache.tomcat.dbcp.dbcp.BasicDataSource) {
        org.apache.tomcat.dbcp.dbcp.BasicDataSource s = (org.apache.tomcat.dbcp.dbcp.BasicDataSource) dataSource;
        return "Busy: " + s.getNumActive() + " (" + (int) (s.getNumActive() * 100 / s.getMaxActive())
                + "%), Connections: " + (s.getNumIdle() + s.getNumActive()) + ", Max: " + s.getMaxActive();
    } else {
        return "Unknown datasource: " + dataSource.getClass().getName();
    }
}

From source file:org.apache.ode.utils.LoggingInterceptor.java

public static DataSource createLoggingDS(DataSource ds, Log log) {
    return (DataSource) Proxy.newProxyInstance(ds.getClass().getClassLoader(), new Class[] { DataSource.class },
            new LoggingInterceptor<DataSource>(ds, log));
}

From source file:org.eclipse.gyrex.persistence.eclipselink.internal.EclipseLinkRepositoryImpl.java

/**
 * Attempts to close a DataSource by searching for a "close" method.
 *//*from   ww w  . j a v  a 2s . co  m*/
static void closeQuietly(final DataSource ds) {
    try {
        final Method closeMethod = ds.getClass().getMethod("close");
        closeMethod.invoke(ds);
    } catch (final Exception e) {
        // no close
    }
}

From source file:org.gogoego.util.db.DBSessionFactory.java

public static String getDSType(final DataSource ds) {
    if (ds == null)
        return null;
    String name = ds.getClass().getName();
    if (ds instanceof org.apache.commons.dbcp.BasicDataSource)
        name = ((org.apache.commons.dbcp.BasicDataSource) ds).getDriverClassName();
    return name;//  ww  w . ja va2 s. c  om
}

From source file:org.hawkular.inventory.impl.tinkerpop.sql.impl.SqlGraph.java

private void setupDataSource(DataSource dataSource, Configuration configuration) throws Exception {
    BeanInfo beanInfo = Introspector.getBeanInfo(dataSource.getClass());
    PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
    Map<String, PropertyDescriptor> propsByName = new HashMap<>();
    for (PropertyDescriptor p : properties) {
        propsByName.put(p.getName().toLowerCase(), p);
    }/*from www. ja v a 2s . com*/

    Iterator it = configuration.getKeys("sql.datasource");
    while (it.hasNext()) {
        String key = (String) it.next();
        String property = key.substring("sql.datasource.".length()).toLowerCase();

        PropertyDescriptor d = propsByName.get(property);

        if (d == null) {
            continue;
        }

        Method write = d.getWriteMethod();
        if (write != null) {
            write.invoke(dataSource, configuration.getProperty(key));
        }
    }
}

From source file:org.kuali.rice.web.health.HealthServletTest.java

private void stubDataSource(DataSource dataSource) throws SQLException {
    Connection connection = mock(Connection.class);
    when(dataSource.getConnection()).thenReturn(connection);
    Statement statement = mock(Statement.class);
    when(connection.createStatement()).thenReturn(statement);

    if (dataSource instanceof StandardXAPoolDataSource) {
        StandardXAPoolDataSource ds = (StandardXAPoolDataSource) dataSource;
        when(ds.getLockedObjectCount()).thenReturn(10);
        when(ds.getMinSize()).thenReturn(5);
        when(ds.getMaxSize()).thenReturn(20);
    } else if (dataSource instanceof PoolingDataSource) {
        PoolingDataSource ds = (PoolingDataSource) dataSource;
        when(ds.getTotalPoolSize()).thenReturn(15L);
        when(ds.getInPoolSize()).thenReturn(5L);
        when(ds.getMinPoolSize()).thenReturn(5);
        when(ds.getMaxPoolSize()).thenReturn(20);
    } else if (dataSource instanceof BasicDataSource) {
        BasicDataSource ds = (BasicDataSource) dataSource;
        when(ds.getNumActive()).thenReturn(10);
        when(ds.getMinIdle()).thenReturn(5);
        when(ds.getMaxActive()).thenReturn(20);
    } else {/*from  w  w  w . j  a v a 2s.  co m*/
        fail("Invalid datasource class: " + dataSource.getClass());
    }

}

From source file:org.openkoala.koala.monitor.support.JdbcPoolStatusCollector.java

/**
 * ??//from   ww w .  j a v  a2 s . c o m
 */
public synchronized void registerDataSource(DataSource ds) {
    if (collectors.containsKey(ds))
        return;
    Class<?> clazz = null;
    try {
        String clazzName = ds.getClass().getName();
        if (clazzName.toLowerCase().contains("dbcp")) {
            clazz = Class.forName("org.openkoala.koala.monitor.support.DbcpDataSourceCollector");
        } else if (clazzName.toLowerCase().contains("c3p0")) {
            clazz = Class.forName("org.openkoala.koala.monitor.support.C3p0DataSourceCollector");
        } else if (clazzName.toLowerCase().contains("proxool")) {
            clazz = Class.forName("org.openkoala.koala.monitor.support.ProxoolDataSourceCollector");
        }
        Collector collector = (Collector) clazz.newInstance();
        collector.assignDataSource(ds);
        collectors.put(ds, collector);
    } catch (Exception e) {
        clazz = null;
        log.error("??[" + ds + "]", e);
    }

}

From source file:org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationTests.java

@Test
public void explicitType() {
    EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.driverClassName:org.hsqldb.jdbcDriver",
            "spring.datasource.url:jdbc:hsqldb:mem:testdb",
            "spring.datasource.type:" + HikariDataSource.class.getName());
    this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    this.context.refresh();
    DataSource bean = this.context.getBean(DataSource.class);
    assertNotNull(bean);// w  ww .  j av a2 s . c o  m
    assertEquals(HikariDataSource.class, bean.getClass());
}

From source file:org.springframework.jdbc.support.SQLErrorCodesFactory.java

/**
 * Build an identification String for the given {@link DataSource},
 * primarily for logging purposes./*www.  j  a  v  a  2  s. co  m*/
 * @param dataSource the {@code DataSource} to introspect
 * @return the identification String
 */
private String identify(DataSource dataSource) {
    return dataSource.getClass().getName() + '@' + Integer.toHexString(dataSource.hashCode());
}

From source file:org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.java

/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.// w w w .  jav  a  2s .co  m
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext,
        boolean classLevel) throws Exception {

    if (executionPhase != sql.executionPhase()) {
        return;
    }

    MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                mergedSqlConfig, executionPhase, testContext));
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
    populator.setSeparator(mergedSqlConfig.getSeparator());
    populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
    populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
    populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
    populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

    String[] scripts = getScripts(sql, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    List<Resource> scriptResources = TestContextResourceUtils
            .convertToResourceList(testContext.getApplicationContext(), scripts);
    for (String stmt : sql.statements()) {
        if (StringUtils.hasText(stmt)) {
            stmt = stmt.trim();
            scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
        }
    }
    populator.setScripts(scriptResources.toArray(new Resource[scriptResources.size()]));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
    }

    String dsName = mergedSqlConfig.getDataSource();
    String tmName = mergedSqlConfig.getTransactionManager();
    DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
    PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext,
            tmName);
    boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

    if (txMgr == null) {
        Assert.state(!newTxRequired,
                () -> String.format(
                        "Failed to execute SQL scripts for test context %s: "
                                + "cannot execute SQL scripts using Transaction Mode "
                                + "[%s] without a PlatformTransactionManager.",
                        testContext, TransactionMode.ISOLATED));
        Assert.state(dataSource != null,
                () -> String.format("Failed to execute SQL scripts for test context %s: "
                        + "supply at least a DataSource or PlatformTransactionManager.", testContext));
        // Execute scripts directly against the DataSource
        populator.execute(dataSource);
    } else {
        DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
        // Ensure user configured an appropriate DataSource/TransactionManager pair.
        if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
            throw new IllegalStateException(String.format(
                    "Failed to execute SQL scripts for test context %s: "
                            + "the configured DataSource [%s] (named '%s') is not the one associated with "
                            + "transaction manager [%s] (named '%s').",
                    testContext, dataSource.getClass().getName(), dsName, txMgr.getClass().getName(), tmName));
        }
        if (dataSource == null) {
            dataSource = dataSourceFromTxMgr;
            Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for "
                    + "test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
                    testContext, txMgr.getClass().getName(), tmName));
        }
        final DataSource finalDataSource = dataSource;
        int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                : TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
                testContext, new DefaultTransactionAttribute(propagation));
        new TransactionTemplate(txMgr, txAttr).execute(status -> {
            populator.execute(finalDataSource);
            return null;
        });
    }
}