Search in sources :

Example 96 with DataSource

use of javax.sql.DataSource in project spring-framework by spring-projects.

the class JpaTransactionManagerTests method testTransactionCommitWithDataSource.

@Test
public void testTransactionCommitWithDataSource() throws SQLException {
    DataSource ds = mock(DataSource.class);
    tm.setDataSource(ds);
    given(manager.getTransaction()).willReturn(tx);
    final List<String> l = new ArrayList<>();
    l.add("test");
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    Object result = tt.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.hasResource(factory));
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
            return l;
        }
    });
    assertTrue(result == l);
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    verify(tx).commit();
    verify(manager).flush();
    verify(manager).close();
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) ArrayList(java.util.ArrayList) TransactionStatus(org.springframework.transaction.TransactionStatus) DataSource(javax.sql.DataSource) Test(org.junit.Test)

Example 97 with DataSource

use of javax.sql.DataSource in project spring-framework by spring-projects.

the class PersistenceXmlParsingTests method testExampleComplex.

@Test
public void testExampleComplex() throws Exception {
    DataSource ds = new DriverManagerDataSource();
    String resource = "/org/springframework/orm/jpa/persistence-complex.xml";
    MapDataSourceLookup dataSourceLookup = new MapDataSourceLookup();
    Map<String, DataSource> dataSources = new HashMap<>();
    dataSources.put("jdbc/MyPartDB", ds);
    dataSources.put("jdbc/MyDB", ds);
    dataSourceLookup.setDataSources(dataSources);
    PersistenceUnitReader reader = new PersistenceUnitReader(new PathMatchingResourcePatternResolver(), dataSourceLookup);
    PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
    assertEquals(2, info.length);
    PersistenceUnitInfo pu1 = info[0];
    assertEquals("pu1", pu1.getPersistenceUnitName());
    assertEquals("com.acme.AcmePersistence", pu1.getPersistenceProviderClassName());
    assertEquals(1, pu1.getMappingFileNames().size());
    assertEquals("ormap2.xml", pu1.getMappingFileNames().get(0));
    assertEquals(1, pu1.getJarFileUrls().size());
    assertEquals(new ClassPathResource("order.jar").getURL(), pu1.getJarFileUrls().get(0));
    assertFalse(pu1.excludeUnlistedClasses());
    assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, pu1.getTransactionType());
    Properties props = pu1.getProperties();
    assertEquals(2, props.keySet().size());
    assertEquals("on", props.getProperty("com.acme.persistence.sql-logging"));
    assertEquals("bar", props.getProperty("foo"));
    assertNull(pu1.getNonJtaDataSource());
    assertSame(ds, pu1.getJtaDataSource());
    assertFalse("Exclude unlisted should default false in 1.0.", pu1.excludeUnlistedClasses());
    PersistenceUnitInfo pu2 = info[1];
    assertSame(PersistenceUnitTransactionType.JTA, pu2.getTransactionType());
    assertEquals("com.acme.AcmePersistence", pu2.getPersistenceProviderClassName());
    assertEquals(1, pu2.getMappingFileNames().size());
    assertEquals("order2.xml", pu2.getMappingFileNames().get(0));
    // the following assertions fail only during coverage runs
    // assertEquals(1, pu2.getJarFileUrls().size());
    // assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), pu2.getJarFileUrls().get(0));
    assertTrue(pu2.excludeUnlistedClasses());
    assertNull(pu2.getJtaDataSource());
    assertEquals(ds, pu2.getNonJtaDataSource());
    assertTrue("Exclude unlisted should be true when no value.", pu2.excludeUnlistedClasses());
}
Also used : HashMap(java.util.HashMap) DriverManagerDataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) Properties(java.util.Properties) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo) ClassPathResource(org.springframework.core.io.ClassPathResource) DataSource(javax.sql.DataSource) DriverManagerDataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) MapDataSourceLookup(org.springframework.jdbc.datasource.lookup.MapDataSourceLookup) Test(org.junit.Test)

Example 98 with DataSource

use of javax.sql.DataSource in project spring-framework by spring-projects.

the class PersistenceXmlParsingTests method testExample4.

@Test
public void testExample4() throws Exception {
    SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
    DataSource ds = new DriverManagerDataSource();
    builder.bind("java:comp/env/jdbc/MyDB", ds);
    PersistenceUnitReader reader = new PersistenceUnitReader(new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
    String resource = "/org/springframework/orm/jpa/persistence-example4.xml";
    PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);
    assertNotNull(info);
    assertEquals(1, info.length);
    assertEquals("OrderManagement4", info[0].getPersistenceUnitName());
    assertEquals(1, info[0].getMappingFileNames().size());
    assertEquals("order-mappings.xml", info[0].getMappingFileNames().get(0));
    assertEquals(3, info[0].getManagedClassNames().size());
    assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0));
    assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1));
    assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2));
    assertTrue("Exclude unlisted should be true when no value.", info[0].excludeUnlistedClasses());
    assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType());
    assertEquals(0, info[0].getProperties().keySet().size());
    builder.clear();
}
Also used : SimpleNamingContextBuilder(org.springframework.tests.mock.jndi.SimpleNamingContextBuilder) DriverManagerDataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) JndiDataSourceLookup(org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo) DataSource(javax.sql.DataSource) DriverManagerDataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) Test(org.junit.Test)

Example 99 with DataSource

use of javax.sql.DataSource in project spring-framework by spring-projects.

the class SqlScriptsTestExecutionListener method getDataSourceFromTransactionManager.

private DataSource getDataSourceFromTransactionManager(PlatformTransactionManager transactionManager) {
    try {
        Method getDataSourceMethod = transactionManager.getClass().getMethod("getDataSource");
        Object obj = ReflectionUtils.invokeMethod(getDataSourceMethod, transactionManager);
        if (obj instanceof DataSource) {
            return (DataSource) obj;
        }
    } catch (Exception ex) {
    // ignore
    }
    return null;
}
Also used : Method(java.lang.reflect.Method) DataSource(javax.sql.DataSource)

Example 100 with DataSource

use of javax.sql.DataSource in project spring-framework by spring-projects.

the class SqlScriptsTestExecutionListener method executeSqlScripts.

/**
	 * 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}.
	 * @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;
        });
    }
}
Also used : TransactionAttribute(org.springframework.transaction.interceptor.TransactionAttribute) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) ResourceDatabasePopulator(org.springframework.jdbc.datasource.init.ResourceDatabasePopulator) ClassPathResource(org.springframework.core.io.ClassPathResource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Resource(org.springframework.core.io.Resource) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) ByteArrayResource(org.springframework.core.io.ByteArrayResource) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) DataSource(javax.sql.DataSource)

Aggregations

DataSource (javax.sql.DataSource)546 Connection (java.sql.Connection)200 Test (org.junit.Test)192 SQLException (java.sql.SQLException)118 Context (javax.naming.Context)70 ResultSet (java.sql.ResultSet)59 Statement (java.sql.Statement)59 NamingException (javax.naming.NamingException)57 InitialContext (javax.naming.InitialContext)55 EJBException (javax.ejb.EJBException)40 HashMap (java.util.HashMap)38 PreparedStatement (java.sql.PreparedStatement)37 Properties (java.util.Properties)35 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)34 RemoteException (java.rmi.RemoteException)32 BasicDataSource (org.apache.commons.dbcp.BasicDataSource)31 UserTransaction (javax.transaction.UserTransaction)30 IOException (java.io.IOException)29 ArrayList (java.util.ArrayList)26 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)21