Java 类org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy 实例源码

项目:spring-data-mybatis    文件:ReplicationRoutingDataSource.java   
public ReplicationRoutingDataSource(DataSource master, List<DataSource> slaves) {

        notNull(master, "master datasource mast be set.");
        this.master = new LazyConnectionDataSourceProxy(master);
        if (null != slaves) {
            this.slaves = slaves;
        }
        setDefaultTargetDataSource(this.master);

        Map<Object, Object> dataSourceMap = new HashMap<Object, Object>();
        dataSourceMap.put("master", this.master);
        if (null != slaves && !slaves.isEmpty()) {
            for (int i = 0; i < slaves.size(); i++) {
                dataSourceMap.put("slave_" + i, new LazyConnectionDataSourceProxy(slaves.get(i)));
            }
        }
        setTargetDataSources(dataSourceMap);
    }
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
/**
 * 關閉
 *
 * @return
 */
protected LazyConnectionDataSourceProxy[] shutdownLazyConnectionDataSourceProxys() throws Exception {
    try {
        if (this.lazyConnectionDataSourceProxys != null) {
            for (int i = 0; i < this.lazyConnectionDataSourceProxys.length; i++) {
                LazyConnectionDataSourceProxy oldInstance = this.lazyConnectionDataSourceProxys[i];
                // oldInstance.close();
                this.lazyConnectionDataSourceProxys[i] = null;
            }
            //
            this.lazyConnectionDataSourceProxys = null;
        }
    } catch (Exception e) {
        LOGGER.error(new StringBuilder("Exception encountered during shutdownLazyConnectionDataSourceProxys()")
                .toString(), e);
        throw e;
    }
    return this.lazyConnectionDataSourceProxys;
}
项目:uncode-dal-all    文件:ShardsDataSource.java   
@Override
public void afterPropertiesSet() throws Exception {
    if (this.shardsDataSources == null) {
        throw new IllegalArgumentException("Property 'shardsDataSources' is required");
    }
    this.resolvedShardsDataSources = new HashMap<Object, DataSource>(this.shardsDataSources.size());
    for (Map.Entry<Object, Object> entry : this.shardsDataSources.entrySet()) {
        DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());
        LazyConnectionDataSourceProxy lazyDataSourceProxy = new LazyConnectionDataSourceProxy();
        lazyDataSourceProxy.setTargetDataSource(dataSource);
        this.resolvedShardsDataSources.put(entry.getKey(), lazyDataSourceProxy);
    }
    if (this.defaultDataSource == null) {
        throw new IllegalArgumentException("Property 'defaultDataSource' is required");
    }
    if(this.defaultDataSource != null){
        resolvedDefaultDataSource = this.resolveSpecifiedDataSource(defaultDataSource);
    }

}
项目:spring-cloud-aws    文件:ReadOnlyRoutingDataSourceTest.java   
@Test
public void getConnection_NoReadReplicaAvailableNoTransactionActive_returnsDefaultDataSource() throws Exception {

    //Arrange
    DataSource defaultDataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);

    when(defaultDataSource.getConnection()).thenReturn(connection);

    ReadOnlyRoutingDataSource readOnlyRoutingDataSource = new ReadOnlyRoutingDataSource();
    readOnlyRoutingDataSource.setTargetDataSources(Collections.emptyMap());
    readOnlyRoutingDataSource.setDefaultTargetDataSource(defaultDataSource);
    readOnlyRoutingDataSource.afterPropertiesSet();

    LazyConnectionDataSourceProxy dataSource = new LazyConnectionDataSourceProxy(readOnlyRoutingDataSource);


    //Act
    Connection connectionReturned = dataSource.getConnection();

    //Assert
    assertSame(connection, ((ConnectionProxy) connectionReturned).getTargetConnection());
}
项目:springuni-particles    文件:AbstractJpaRepositoryConfiguration.java   
/**
 * Primary data source.
 *
 * @return the primary data source
 */
@Bean
@Primary
public DataSource dataSource() throws SQLException {
  DataSource dataSourceTarget = new HikariDataSource(getHikariConfig());
  return new LazyConnectionDataSourceProxy(dataSourceTarget);
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
/**
 * 建構
 * 
 * @return
 */
protected LazyConnectionDataSourceProxy[] createLazyConnectionDataSourceProxys(DataSource[] dataSources)
        throws Exception {
    AssertHelper.notNull(dataSources, "The DataSources must not be null");
    //
    LazyConnectionDataSourceProxy[] result = null;
    try {
        int size = dataSources.length;
        result = new LazyConnectionDataSourceProxy[size];
        for (int i = 0; i < size; i++) {
            LazyConnectionDataSourceProxy lazyConnectionDataSourceProxy = new LazyConnectionDataSourceProxy(
                    dataSources[i]);
            result[i] = lazyConnectionDataSourceProxy;
        }
    } catch (Exception e) {
        LOGGER.error(
                new StringBuilder("Exception encountered during createLazyConnectionDataSourceProxys()").toString(),
                e);
        try {
            result = (LazyConnectionDataSourceProxy[]) shutdownLazyConnectionDataSourceProxys();
        } catch (Exception sie) {
            throw sie;
        }
        throw e;
    }
    return result;
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
/**
 * 重啟
 *
 * @return
 */
protected LazyConnectionDataSourceProxy[] restartLazyConnectionDataSourceProxys() throws Exception {
    try {
        if (this.lazyConnectionDataSourceProxys != null) {
            this.lazyConnectionDataSourceProxys = shutdownLazyConnectionDataSourceProxys();
            this.lazyConnectionDataSourceProxys = createLazyConnectionDataSourceProxys(this.dataSources);
        }
    } catch (Exception e) {
        LOGGER.error(new StringBuilder("Exception encountered during restartLazyConnectionDataSourceProxys()")
                .toString(), e);
        throw e;
    }
    return this.lazyConnectionDataSourceProxys;
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBeanTest.java   
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    applicationContext = new ClassPathXmlApplicationContext(new String[] { //
            "applicationContext-init.xml", //
            "org/openyu/commons/spring/jdbc/datasource/testContext-lazy-group.xml",//

    });
    lazyConnectionDataSourceProxys = applicationContext.getBean("lazyConnectionDataSourceProxyGroupFactoryBean",
            LazyConnectionDataSourceProxy[].class);
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBeanTest.java   
@Test
@BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0, concurrency = 1)
public void lazyConnectionDataSourceProxys() throws Exception {
    System.out.println(lazyConnectionDataSourceProxys);
    assertNotNull(lazyConnectionDataSourceProxys);
    //
    for (LazyConnectionDataSourceProxy lazyConnectionDataSourceProxy : lazyConnectionDataSourceProxys) {
        System.out.println(lazyConnectionDataSourceProxy.getTargetDataSource().getConnection());
    }
}
项目:class-guard    文件:LobTypeHandlerTests.java   
@Test
public void testClobStringTypeWithSynchronizedConnection() throws Exception {
    DataSource dsTarget = new DriverManagerDataSource();
    DataSource ds = new LazyConnectionDataSourceProxy(dsTarget);

    given(lobHandler.getClobAsString(rs, 1)).willReturn("content");

    ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler);
    assertEquals("content", type.valueOf("content"));
    assertEquals("content", type.getResult(rs, "column"));
    assertEquals("content", type.getResult(rs, 1));

    TransactionSynchronizationManager.initSynchronization();
    try {
        DataSourceUtils.getConnection(ds);
        type.setParameter(ps, 1, "content", null);
        List synchs = TransactionSynchronizationManager.getSynchronizations();
        assertEquals(2, synchs.size());
        assertTrue(synchs.get(0).getClass().getName().endsWith("LobCreatorSynchronization"));
        ((TransactionSynchronization) synchs.get(0)).beforeCompletion();
        ((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
        ((TransactionSynchronization) synchs.get(1)).beforeCompletion();
        ((TransactionSynchronization) synchs.get(1)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
    }
    finally {
        TransactionSynchronizationManager.clearSynchronization();
    }
    verify(lobCreator).setClobAsString(ps, 1, "content");
}
项目:spring-cloud-aws    文件:AmazonRdsReadReplicaAwareDataSourceFactoryBean.java   
/**
 * Constructs a {@link org.springframework.cloud.aws.jdbc.datasource.ReadOnlyRoutingDataSource} data source that contains the
 * regular data source as a default, and all read-replicas as additional data source. The {@link
 * org.springframework.cloud.aws.jdbc.datasource.ReadOnlyRoutingDataSource} is additionally wrapped with a {@link
 * org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy}, because the read-only flag is only available
 * after the transactional context has been established. This is only the case if the physical connection is
 * requested after the transaction start and not while starting a transaction.
 *
 * @return a ReadOnlyRoutingDataSource that is wrapped with a LazyConnectionDataSourceProxy
 * @throws Exception
 *         if the underlying data source setup throws any exception
 */
@Override
protected DataSource createInstance() throws Exception {
    DBInstance dbInstance = getDbInstance(getDbInstanceIdentifier());

    //If there is no read replica available, delegate to super class
    if (dbInstance.getReadReplicaDBInstanceIdentifiers().isEmpty()) {
        return super.createInstance();
    }

    HashMap<Object, Object> replicaMap = new HashMap<>(
            dbInstance.getReadReplicaDBInstanceIdentifiers().size());

    for (String replicaName : dbInstance.getReadReplicaDBInstanceIdentifiers()) {
        replicaMap.put(replicaName, createDataSourceInstance(replicaName));
    }

    //Create the data source
    ReadOnlyRoutingDataSource dataSource = new ReadOnlyRoutingDataSource();
    dataSource.setTargetDataSources(replicaMap);
    dataSource.setDefaultTargetDataSource(createDataSourceInstance(getDbInstanceIdentifier()));

    //Initialize the class
    dataSource.afterPropertiesSet();

    return new LazyConnectionDataSourceProxy(dataSource);
}
项目:spring-cloud-aws    文件:AmazonRdsReadReplicaAwareDataSourceFactoryBean.java   
@Override
protected void destroyInstance(DataSource instance) throws Exception {
    if (instance instanceof LazyConnectionDataSourceProxy) {
        DataSource targetDataSource = ((LazyConnectionDataSourceProxy) instance).getTargetDataSource();
        if (targetDataSource instanceof ReadOnlyRoutingDataSource) {
            List<Object> dataSources = ((ReadOnlyRoutingDataSource) targetDataSource).getDataSources();
            for (Object candidate : dataSources) {
                if (candidate instanceof DataSource) {
                    super.destroyInstance(instance);
                }
            }
        }
    }
}
项目:spring-cloud-aws    文件:ReadOnlyRoutingDataSourceTest.java   
@Test
public void getConnection_NoReadReplicaAvailableReadOnlyTransactionActive_returnsDefaultDataSource() throws Exception {

    //Arrange
    DataSource defaultDataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);

    when(defaultDataSource.getConnection()).thenReturn(connection);

    ReadOnlyRoutingDataSource readOnlyRoutingDataSource = new ReadOnlyRoutingDataSource();
    readOnlyRoutingDataSource.setTargetDataSources(Collections.emptyMap());
    readOnlyRoutingDataSource.setDefaultTargetDataSource(defaultDataSource);
    readOnlyRoutingDataSource.afterPropertiesSet();

    LazyConnectionDataSourceProxy dataSource = new LazyConnectionDataSourceProxy(readOnlyRoutingDataSource);

    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setReadOnly(true);

    TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource), transactionDefinition);

    //Act
    Connection connectionReturned = transactionTemplate.execute(status -> {
        try {
            return ((ConnectionProxy) dataSource.getConnection()).getTargetConnection();
        } catch (SQLException e) {
            fail(e.getMessage());
        }
        return null;
    });

    //Assert
    assertSame(connection, connectionReturned);
}
项目:spring-cloud-aws    文件:ReadOnlyRoutingDataSourceTest.java   
@Test
public void getConnection_ReadReplicaAvailableReadOnlyTransactionActive_returnsReadReplicaDataSource() throws Exception {

    //Arrange
    DataSource defaultDataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);

    DataSource readOnlyDataSource = mock(DataSource.class);
    Connection readOnlyConnection = mock(Connection.class);


    when(readOnlyDataSource.getConnection()).thenReturn(readOnlyConnection);
    when(defaultDataSource.getConnection()).thenReturn(connection);

    ReadOnlyRoutingDataSource readOnlyRoutingDataSource = new ReadOnlyRoutingDataSource();
    readOnlyRoutingDataSource.setTargetDataSources(Collections.singletonMap("read1", readOnlyDataSource));
    readOnlyRoutingDataSource.setDefaultTargetDataSource(defaultDataSource);
    readOnlyRoutingDataSource.afterPropertiesSet();

    LazyConnectionDataSourceProxy dataSource = new LazyConnectionDataSourceProxy(readOnlyRoutingDataSource);

    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setReadOnly(true);

    TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource), transactionDefinition);

    //Act
    Connection connectionReturned = transactionTemplate.execute(status -> {
        try {
            return ((ConnectionProxy) dataSource.getConnection()).getTargetConnection();
        } catch (SQLException e) {
            fail(e.getMessage());
        }
        return null;
    });

    //Assert
    assertSame(readOnlyConnection, connectionReturned);
}
项目:spring-cloud-aws    文件:ReadOnlyRoutingDataSourceTest.java   
@Test
public void getConnection_ReadReplicaAvailableWriteTransactionActive_returnsDefaultDataSource() throws Exception {

    //Arrange
    DataSource defaultDataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);

    DataSource readOnlyDataSource = mock(DataSource.class);
    Connection readOnlyConnection = mock(Connection.class);


    when(readOnlyDataSource.getConnection()).thenReturn(readOnlyConnection);
    when(defaultDataSource.getConnection()).thenReturn(connection);

    ReadOnlyRoutingDataSource readOnlyRoutingDataSource = new ReadOnlyRoutingDataSource();
    readOnlyRoutingDataSource.setTargetDataSources(Collections.singletonMap("read1", readOnlyDataSource));
    readOnlyRoutingDataSource.setDefaultTargetDataSource(defaultDataSource);
    readOnlyRoutingDataSource.afterPropertiesSet();

    LazyConnectionDataSourceProxy dataSource = new LazyConnectionDataSourceProxy(readOnlyRoutingDataSource);

    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setReadOnly(false);

    TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource), transactionDefinition);

    //Act
    Connection connectionReturned = transactionTemplate.execute(status -> {
        try {
            return ((ConnectionProxy) dataSource.getConnection()).getTargetConnection();
        } catch (SQLException e) {
            fail(e.getMessage());
        }
        return null;
    });

    //Assert
    assertSame(connection, connectionReturned);
}
项目:opennmszh    文件:TemporaryDatabaseExecutionListener.java   
@Override
public void prepareTestInstance(final TestContext testContext) throws Exception {
    System.err.println(String.format("TemporaryDatabaseExecutionListener.prepareTestInstance(%s)", testContext));
    final JUnitTemporaryDatabase jtd = findAnnotation(testContext);

    if (jtd == null) {
        return;
    }

    m_database = m_databases.remove();
    final PooledDataSource pooledDataSource = (PooledDataSource)DataSources.pooledDataSource(m_database);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try { pooledDataSource.close(); }
            catch (final Throwable t) { LogUtils.debugf(this, t, "failed to close pooled data source"); }
        }
    });

    final LazyConnectionDataSourceProxy proxy = new LazyConnectionDataSourceProxy(pooledDataSource);
    DataSourceFactory.setInstance(proxy);

    testContext.setAttribute("org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener.pooledDataSource", pooledDataSource);
    System.err.println(String.format("TemporaryDatabaseExecutionListener.prepareTestInstance(%s) prepared db %s", testContext, m_database.toString()));
       System.err.println("Temporary Database Name: " + m_database.getTestDatabase());
}
项目:cobarclient    文件:DefaultCobarDataSourceService.java   
public void afterPropertiesSet() throws Exception {
    if (getHaDataSourceCreator() == null) {
        setHaDataSourceCreator(new NonHADataSourceCreator());
    }
    if (CollectionUtils.isEmpty(dataSourceDescriptors)) {
        return;
    }

    for (CobarDataSourceDescriptor descriptor : getDataSourceDescriptors()) {
        Validate.notEmpty(descriptor.getIdentity());
        Validate.notNull(descriptor.getTargetDataSource());

        DataSource dataSourceToUse = descriptor.getTargetDataSource();

        if (descriptor.getStandbyDataSource() != null) {
            dataSourceToUse = getHaDataSourceCreator().createHADataSource(descriptor);
            if (CollectionUtils.isNotEmpty(dataSourcePostProcessor)) {
                for (IDataSourcePostProcessor pp : dataSourcePostProcessor) {
                    dataSourceToUse = pp.postProcess(dataSourceToUse);
                }
            }
        }

        dataSources.put(descriptor.getIdentity(), new LazyConnectionDataSourceProxy(
                dataSourceToUse));
    }
}
项目:OpenNMS    文件:TemporaryDatabaseExecutionListener.java   
@Override
public void prepareTestInstance(final TestContext testContext) throws Exception {
    System.err.println(String.format("TemporaryDatabaseExecutionListener.prepareTestInstance(%s)", testContext));
    final JUnitTemporaryDatabase jtd = findAnnotation(testContext);

    if (jtd == null) {
        return;
    }

    m_database = m_databases.remove();
    final PooledDataSource pooledDataSource = (PooledDataSource)DataSources.pooledDataSource(m_database);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try { pooledDataSource.close(); }
            catch (final Throwable t) { LogUtils.debugf(this, t, "failed to close pooled data source"); }
        }
    });

    final LazyConnectionDataSourceProxy proxy = new LazyConnectionDataSourceProxy(pooledDataSource);
    DataSourceFactory.setInstance(proxy);

    testContext.setAttribute("org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener.pooledDataSource", pooledDataSource);
    System.err.println(String.format("TemporaryDatabaseExecutionListener.prepareTestInstance(%s) prepared db %s", testContext, m_database.toString()));
       System.err.println("Temporary Database Name: " + m_database.getTestDatabase());
}
项目:spring-data-mybatis    文件:TestConfig.java   
@Bean
public DataSource dataSource(@Qualifier("routingDataSource") DataSource routingDataSource) {
    return new LazyConnectionDataSourceProxy(routingDataSource);
}
项目:spring4-understanding    文件:HibernateTransactionManagerTests.java   
@Test
public void testTransactionCommitWithNonExistingDatabaseAndLazyConnection() throws Exception {
    DriverManagerDataSource dsTarget = new DriverManagerDataSource();
    final LazyConnectionDataSourceProxy ds = new LazyConnectionDataSourceProxy();
    ds.setTargetDataSource(dsTarget);
    ds.setDefaultAutoCommit(true);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    //ds.setDefaultTransactionIsolationName("TRANSACTION_READ_COMMITTED");

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(ds);
    Properties props = new Properties();
    props.setProperty("hibernate.dialect", HSQLDialect.class.getName());
    props.setProperty("hibernate.cache.provider_class", NoCacheProvider.class.getName());
    props.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
    lsfb.setHibernateProperties(props);
    lsfb.afterPropertiesSet();
    final SessionFactory sf = lsfb.getObject();

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);
    tm.afterPropertiesSet();
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    tt.setTimeout(10);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            HibernateTemplate ht = new HibernateTemplate(sf);
            return ht.find("from java.lang.Object");
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
}
项目:spring4-understanding    文件:HibernateTransactionManagerTests.java   
@Test
public void testTransactionCommitWithNonExistingDatabaseAndLazyConnection() throws Exception {
    DriverManagerDataSource dsTarget = new DriverManagerDataSource();
    final LazyConnectionDataSourceProxy ds = new LazyConnectionDataSourceProxy();
    ds.setTargetDataSource(dsTarget);
    ds.setDefaultAutoCommit(true);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    //ds.setDefaultTransactionIsolationName("TRANSACTION_READ_COMMITTED");

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(ds);
    Properties props = new Properties();
    props.setProperty("hibernate.dialect", HSQLDialect.class.getName());
    props.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
    lsfb.setHibernateProperties(props);
    lsfb.afterPropertiesSet();
    final SessionFactory sf = lsfb.getObject();

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);
    tm.afterPropertiesSet();
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    tt.setTimeout(10);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession();
            return session.createQuery("from java.lang.Object").list();
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
public LazyConnectionDataSourceProxy[] getLazyConnectionDataSourceProxys() {
    return lazyConnectionDataSourceProxys;
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
public void setLazyConnectionDataSourceProxys(LazyConnectionDataSourceProxy[] lazyConnectionDataSourceProxys) {
    this.lazyConnectionDataSourceProxys = lazyConnectionDataSourceProxys;
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
@Override
public LazyConnectionDataSourceProxy[] getObject() throws Exception {
    return lazyConnectionDataSourceProxys;
}
项目:openyu-commons    文件:LazyConnectionDataSourceProxyGroupFactoryBean.java   
@Override
public Class<?> getObjectType() {
    return ((this.lazyConnectionDataSourceProxys != null) ? this.lazyConnectionDataSourceProxys.getClass()
            : LazyConnectionDataSourceProxy[].class);
}
项目:class-guard    文件:HibernateTransactionManagerTests.java   
@Test
public void testTransactionCommitWithNonExistingDatabaseAndLazyConnection() throws Exception {
    DriverManagerDataSource dsTarget = new DriverManagerDataSource();
    final LazyConnectionDataSourceProxy ds = new LazyConnectionDataSourceProxy();
    ds.setTargetDataSource(dsTarget);
    ds.setDefaultAutoCommit(true);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    //ds.setDefaultTransactionIsolationName("TRANSACTION_READ_COMMITTED");

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(ds);
    Properties props = new Properties();
    props.setProperty("hibernate.dialect", HSQLDialect.class.getName());
    props.setProperty("hibernate.cache.provider_class", NoCacheProvider.class.getName());
    props.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
    lsfb.setHibernateProperties(props);
    lsfb.afterPropertiesSet();
    final SessionFactory sf = lsfb.getObject();

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);
    tm.afterPropertiesSet();
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    tt.setTimeout(10);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            HibernateTemplate ht = new HibernateTemplate(sf);
            return ht.find("from java.lang.Object");
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
}
项目:class-guard    文件:HibernateTransactionManagerTests.java   
@Test
public void testTransactionCommitWithNonExistingDatabaseAndLazyConnection() throws Exception {
    DriverManagerDataSource dsTarget = new DriverManagerDataSource();
    final LazyConnectionDataSourceProxy ds = new LazyConnectionDataSourceProxy();
    ds.setTargetDataSource(dsTarget);
    ds.setDefaultAutoCommit(true);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    //ds.setDefaultTransactionIsolationName("TRANSACTION_READ_COMMITTED");

    LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(ds);
    Properties props = new Properties();
    props.setProperty("hibernate.dialect", HSQLDialect.class.getName());
    props.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
    lsfb.setHibernateProperties(props);
    lsfb.afterPropertiesSet();
    final SessionFactory sf = lsfb.getObject();

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);
    tm.afterPropertiesSet();
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    tt.setTimeout(10);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    tt.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
            Session session = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession();
            return session.createQuery("from java.lang.Object").list();
        }
    });

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
}
项目:spring-cloud-aws    文件:AmazonRdsReadReplicaAwareDataSourceFactoryBeanTest.java   
@Test
public void afterPropertiesSet_instanceWithReadReplica_createsDataSourceRouter() throws Exception {
    //Arrange
    AmazonRDS amazonRDS = mock(AmazonRDS.class);
    DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);


    when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))).thenReturn(
            new DescribeDBInstancesResult().
                    withDBInstances(new DBInstance().
                            withDBInstanceStatus("available").
                            withDBName("test").
                            withDBInstanceIdentifier("test").
                            withEngine("mysql").
                            withMasterUsername("admin").
                            withEndpoint(new Endpoint().
                                    withAddress("localhost").
                                    withPort(3306)
                            ).withReadReplicaDBInstanceIdentifiers("read1", "read2")
                    )
    );

    when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("read1"))).thenReturn(
            new DescribeDBInstancesResult().
                    withDBInstances(new DBInstance().
                            withDBInstanceStatus("available").
                            withDBName("read1").
                            withDBInstanceIdentifier("read1").
                            withEngine("mysql").
                            withMasterUsername("admin").
                            withEndpoint(new Endpoint().
                                    withAddress("localhost").
                                    withPort(3306)
                            )
                    )
    );

    when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("read2"))).thenReturn(
            new DescribeDBInstancesResult().
                    withDBInstances(new DBInstance().
                            withDBInstanceStatus("available").
                            withDBName("read2").
                            withDBInstanceIdentifier("read2").
                            withEngine("mysql").
                            withMasterUsername("admin").
                            withEndpoint(new Endpoint().
                                    withAddress("localhost").
                                    withPort(3306)
                            )
                    )
    );

    DataSource createdDataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);

    when(dataSourceFactory.createDataSource(new DataSourceInformation(DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret"))).thenReturn(createdDataSource);
    when(dataSourceFactory.createDataSource(new DataSourceInformation(DatabaseType.MYSQL, "localhost", 3306, "read1", "admin", "secret"))).thenReturn(createdDataSource);
    when(dataSourceFactory.createDataSource(new DataSourceInformation(DatabaseType.MYSQL, "localhost", 3306, "read2", "admin", "secret"))).thenReturn(createdDataSource);
    when(createdDataSource.getConnection()).thenReturn(connection);

    AmazonRdsReadReplicaAwareDataSourceFactoryBean amazonRdsDataSourceFactoryBean = new AmazonRdsReadReplicaAwareDataSourceFactoryBean(amazonRDS, "test", "secret");
    amazonRdsDataSourceFactoryBean.setDataSourceFactory(dataSourceFactory);

    //Act
    amazonRdsDataSourceFactoryBean.afterPropertiesSet();

    //Assert
    DataSource datasource = amazonRdsDataSourceFactoryBean.getObject();
    assertNotNull(datasource);
    assertTrue(datasource instanceof LazyConnectionDataSourceProxy);

    ReadOnlyRoutingDataSource source = (ReadOnlyRoutingDataSource) ((LazyConnectionDataSourceProxy) datasource).getTargetDataSource();
    assertEquals(3, source.getDataSources().size());
}
项目:mev    文件:PresetPersistenceConfiguration.java   
@Bean(name="presets-lazy-connection-datasource") @Inject
public LazyConnectionDataSourceProxy lazyConnectionDataSource(@Named("presets-datasource") DataSource datasource) {
    return new LazyConnectionDataSourceProxy(datasource);
}
项目:mev    文件:PresetPersistenceConfiguration.java   
@Bean(name="presets-transaction-aware-datasrouce") @Inject
public TransactionAwareDataSourceProxy transactionAwareDataSource(@Named("presets-lazy-connection-datasource") LazyConnectionDataSourceProxy lazyProxy) {
    return new TransactionAwareDataSourceProxy(lazyProxy);
}
项目:mev    文件:ProbeAnnotationsPersistenceConfiguration.java   
@Bean
public LazyConnectionDataSourceProxy lazyConnectionDataSource() {
    return new LazyConnectionDataSourceProxy(dataSource());
}
项目:b4    文件:B4CoreRootConfig.java   
@Bean
public DataSource dataSource() {
    return new LazyConnectionDataSourceProxy(mainDataSource());
}
项目:communote-server    文件:C3P0DataSourceConnectionProvider.java   
/**
 * Method that is called after DataSource creation to allow further modifications of the
 * DataSource. The default implementation will wrap the DataSource into a
 * LazyConnectionDataSourceProxy.
 *
 * @param dataSource
 *            the DataSource that was just created
 * @return the final, lazily connecting DataSource
 */
protected DataSource postDataSourceCreation(DataSource dataSource) {
    LazyConnectionDataSourceProxy lazyDataSource = new LazyConnectionDataSourceProxy(dataSource);
    return lazyDataSource;
}
项目:replication-datasource    文件:WithRoutingDataSourceConfig.java   
/**
 * {@link org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy}로 감싸서
 * 트랜잭션 동기화가 이루어진 뒤에 실제 커넥션을 확보하도록 해준다.
 *
 * @param routingDataSource
 * @return
 */
@Bean
public DataSource dataSource(@Qualifier("routingDataSource") DataSource routingDataSource) {
    return new LazyConnectionDataSourceProxy(routingDataSource);
}
项目:replication-datasource    文件:WithRoutingDataSourceConfig.java   
/**
 * {@link org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy}로 감싸서
 * 트랜잭션 동기화가 이루어진 뒤에 실제 커넥션을 확보하도록 해준다.
 *
 * @param routingDataSource
 * @return
 */
@Bean
public DataSource dataSource(@Qualifier("routingDataSource") DataSource routingDataSource) {
    return new LazyConnectionDataSourceProxy(routingDataSource);
}