Java Code Examples for javax.sql.DataSource

The following are top voted examples for showing how to use javax.sql.DataSource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: org.ops4j.pax.transx   File: HsqlTest.java   View source code 6 votes vote down vote up
@Test
public void testConnectionsWithTx() throws Exception {
    DataSource ds = wrap(createHsqlDataSource());

    Transaction tx = tm.begin();
    try {
        try (Connection con = ds.getConnection()) {
            try (Connection con2 = ds.getConnection()) {
                assertNotSame(con, con2);
            }
        }
        tx.commit();
    } catch (Throwable t) {
        tx.rollback();
        throw t;
    }
}
 
Example 2
Project: uavstack   File: MybatisHookProxy.java   View source code 6 votes vote down vote up
@Override
protected void collectDBPoolMetrics(MonitorElement clientElem) {

    if (this.datasources.size() == 0) {
        return;
    }

    for (DataSource cp : this.datasources) {
        String jdbcURL = (String) ReflectionHelper.invoke(cp.getClass().getName(), cp, "getUrl", null, null,
                cp.getClass().getClassLoader());

        MonitorElementInstance inst = this.matchElemInstance(clientElem, jdbcURL);

        if (inst == null) {
            continue;
        }

        collectDataSourceStat(inst, cp, webapploaderForMybatis);
    }
}
 
Example 3
Project: otter-G   File: DataSourceCreator.java   View source code 6 votes vote down vote up
/**
 * 扩展功能,可以自定义一些自己实现的 dataSource
 */
private DataSource preCreate(Long pipelineId, DbMediaSource dbMediaSource) {

    if (CollectionUtils.isEmpty(dataSourceHandlers)) {
        return null;
    }

    DataSource dataSource = null;
    for (DataSourceHanlder handler : dataSourceHandlers) {
        if (handler.support(dbMediaSource)) {
            dataSource = handler.create(pipelineId, dbMediaSource);
            if (dataSource != null) {
                return dataSource;
            }
        }
    }
    return null;
}
 
Example 4
Project: DHIS2-fhir-lab-app   File: FhirServerConfigDstu3.java   View source code 6 votes vote down vote up
/**
 * The following bean configures the database connection. The 'url' property value of "jdbc:derby:directory:jpaserver_derby_files;create=true" indicates that the server should save resources in a
 * directory called "jpaserver_derby_files".
 * 
 * A URL to a remote database could also be placed here, along with login credentials and other properties supported by BasicDataSource.
 */
@Bean(destroyMethod = "close")
public DataSource dataSource() {
	BasicDataSource retVal = new BasicDataSource();
	/*
	retVal.setDriver(new org.apache.derby.jdbc.EmbeddedDriver());
	retVal.setUrl("jdbc:derby:directory:target/jpaserver_derby_files;create=true");
	retVal.setUsername("");
	retVal.setPassword("");
	* */
	 
	
	try
	{
		retVal.setDriver(new com.mysql.jdbc.Driver());
	}
	catch (Exception exc)
	{
		exc.printStackTrace();
	}
	retVal.setUrl("jdbc:mysql://localhost:3306/dhis2_fhir");
	retVal.setUsername("root");
	retVal.setPassword("");
	return retVal;
}
 
Example 5
Project: SpringBoot-Study   File: ClusterDruidDataSourceConfig.java   View source code 6 votes vote down vote up
/**
 * SqlSessionFactory配置
 *
 * @return
 * @throws Exception
 */
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(
        @Qualifier("clusterDataSource") DataSource dataSource
) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    //配置mapper文件位置
    sqlSessionFactoryBean.setMapperLocations(resolver.getResources(clusterMapperLocations));

    //配置分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //设置插件
    sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
    return sqlSessionFactoryBean.getObject();
}
 
Example 6
Project: xm-ms-balance   File: DatabaseConfiguration.java   View source code 6 votes vote down vote up
@Bean
@DependsOn("liquibase")
public MultiTenantSpringLiquibase multiTenantLiquibase(
    DataSource dataSource,
    LiquibaseProperties liquibaseProperties) {
    MultiTenantSpringLiquibase liquibase = new XmMultiTenantSpringLiquibase();
    liquibase.setDataSource(dataSource);
    liquibase.setChangeLog(CHANGE_LOG_PATH);
    liquibase.setContexts(liquibaseProperties.getContexts());
    liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
    liquibase.setDropFirst(liquibaseProperties.isDropFirst());
    liquibase.setSchemas(getSchemas());
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) {
        liquibase.setShouldRun(false);
    } else {
        liquibase.setShouldRun(liquibaseProperties.isEnabled());
        log.debug("Configuring Liquibase");
    }
    return liquibase;
}
 
Example 7
Project: lams   File: DataSourceUtils.java   View source code 6 votes vote down vote up
/**
 * Actually close the given Connection, obtained from the given DataSource.
 * Same as {@link #releaseConnection}, but throwing the original SQLException.
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param con the Connection to close if necessary
 * (if this is {@code null}, the call will be ignored)
 * @param dataSource the DataSource that the Connection was obtained from
 * (may be {@code null})
 * @throws SQLException if thrown by JDBC methods
 * @see #doGetConnection
 */
public static void doReleaseConnection(Connection con, DataSource dataSource) throws SQLException {
	if (con == null) {
		return;
	}
	if (dataSource != null) {
		ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
		if (conHolder != null && connectionEquals(conHolder, con)) {
			// It's the transactional Connection: Don't close it.
			conHolder.released();
			return;
		}
	}
	logger.debug("Returning JDBC Connection to DataSource");
	doCloseConnection(con, dataSource);
}
 
Example 8
Project: angit   File: DatasourceConfig.java   View source code 6 votes vote down vote up
/**
 * Dynamic sql session factory sql session factory.
 *
 * @param dynamicDataSource the dynamic data source
 * @param properties        the properties
 * @return the sql session factory
 */
@Bean
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public SqlSessionFactory dynamicSqlSessionFactory(
		@Qualifier("dynamicDataSource") DataSource dynamicDataSource,
		MybatisProperties properties) {
	final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
	sessionFactory.setDataSource(dynamicDataSource);
	sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(properties.getConfigLocation()));
	sessionFactory.setMapperLocations(properties.resolveMapperLocations());
	try {
		return sessionFactory.getObject();
	} catch (Exception e) {
		throw new SystemException(e);
	}
}
 
Example 9
Project: My-Blog   File: TaleUtils.java   View source code 6 votes vote down vote up
/**
 * 获取新的数据源
 *
 * @return
 */
public static DataSource getNewDataSource() {
    if (newDataSource == null) synchronized (TaleUtils.class) {
        if (newDataSource == null) {
            Properties properties = TaleUtils.getPropFromFile("application-default.properties");
            if (properties.size() == 0) {
                return newDataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            newDataSource = managerDataSource;
        }
    }
    return newDataSource;
}
 
Example 10
Project: Spring-Security-Third-Edition   File: DataSourceConfig.java   View source code 5 votes vote down vote up
/**
 * Embedded H2 database
 * Connect to running database with the following details:
 *
 * URL: jdbc:h2:mem:dataSource
 * Driver Class: org.h2.Driver
 * Username: sa
 * Password: [blank]
 *
 * @return
 */
@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    database = builder.setType(EmbeddedDatabaseType.H2)
            .setName("dataSource")
            .ignoreFailedDrops(true)
            .continueOnError(false)
            .addScript("classpath:database/h2/calendar-schema.sql")
            .addScript("classpath:database/h2/calendar-data.sql")
            .build();
    return database;
}
 
Example 11
Project: springboot-copy   File: MasterDataSourceConfig.java   View source code 5 votes vote down vote up
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example 12
Project: holon-datastore-jpa   File: ExampleJpaDatastoreSpring.java   View source code 5 votes vote down vote up
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory(DataSource dataSource) {
	LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	emf.setDataSource(dataSource);
	emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
	emf.setPackagesToScan("com.exmaple.test.entities");
	return emf;
}
 
Example 13
Project: EasyTransaction   File: DefaultTransStatusLoggerImpl.java   View source code 5 votes vote down vote up
@Override
public Boolean checkTransactionStatus(String appId, String busCode, String trxId) {
	
	DataSource dataSource = selctor.selectDataSource(appId, busCode, trxId);
	JdbcTemplate jdbcTemplate = getJdbcTemplate(dataSource);
	
	//select * for update
	List<Integer> statusList = jdbcTemplate.queryForList("select status from executed_trans where app_id = ? and bus_code = ? and trx_id = ? for update;", new Object[]{appId,busCode,trxId}, Integer.class);
	
	if(statusList == null || statusList.size() == 0) {
		return false;
	} else {
		//it can only be 1 record,because it's search by primary key
		int status = statusList.get(0);
		
		switch(status){
		case TransactionStatus.UNKNOWN:
			//parent transaction status unknown
			return null;
		case TransactionStatus.COMMITTED:
			//success
			return true;
		case TransactionStatus.ROLLBACKED:
			return false;
		default:
			throw new IllegalArgumentException("unknown transaction status:" + status);
		}
	}
}
 
Example 14
Project: plugin-bt-jira   File: JiraExportPluginResource.java   View source code 5 votes vote down vote up
/**
 * Return a simple export data without any computation.
 * 
 * @param subscription
 *            The subscription identifier.
 * @return the SLA configuration
 */
protected JiraSimpleExport getSimpleData(final int subscription) {

	// Find the project corresponding to the given JIRA project
	final long start = System.currentTimeMillis();
	final Map<String, String> parameters = subscriptionResource.getParameters(subscription);
	final int jira = Integer.parseInt(parameters.get(JiraBaseResource.PARAMETER_PROJECT));
	final String pkey = parameters.get(JiraBaseResource.PARAMETER_PKEY);
	final DataSource dataSource = getDataSource(parameters);

	// Get issues of this project
	log.info("Get issues of {}({})", pkey, jira);
	final List<JiraIssueRow> issues = jiraDao.getIssues(dataSource, jira, pkey);
	log.info("Retrieved changes : {}", issues.size());

	final Map<Integer, String> statusText = jiraDao.getStatuses(dataSource);
	final Map<Integer, String> priorityText = jiraDao.getPriorities(dataSource);
	final Map<Integer, String> resolutionText = jiraDao.getResolutions(dataSource);
	final Map<Integer, String> typeText = jiraDao.getTypes(dataSource, jira);
	log.info("Fetch done of {} for {} issues, {} status, {} priorities, {} types, {} resolutions", subscription,
			issues.size(), statusText.size(), priorityText.size(), typeText.size(), resolutionText.size());

	final JiraSimpleExport jiraComputations = new JiraSimpleExport();
	jiraComputations.setIssues(issues);
	jiraComputations.setStatusText(statusText);
	jiraComputations.setPriorityText(priorityText);
	jiraComputations.setResolutionText(resolutionText);
	jiraComputations.setTypeText(typeText);
	log.info("End of simple export, took {}",
			DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));
	return jiraComputations;
}
 
Example 15
Project: druid-spring-boot   File: DruidDataSourceInitializer.java   View source code 5 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
    if (resources.isEmpty()) {
        return;
    }
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(this.properties.isContinueOnError());
    populator.setSeparator(this.properties.getSeparator());
    if (this.properties.getSqlScriptEncoding() != null) {
        populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
    }
    for (Resource resource : resources) {
        populator.addScript(resource);
    }
    DataSource dataSource = this.dataSource;
    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
                .driverClassName(this.properties.determineDriverClassName())
                .url(this.properties.determineUrl()).username(username)
                .password(password).build();
    }
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 16
Project: microservices-tcc-alfa   File: AuthorizationServerConfiguration.java   View source code 5 votes vote down vote up
@Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
	DataSourceInitializer initializer = new DataSourceInitializer();
	initializer.setDataSource(dataSource);
	initializer.setDatabasePopulator(databasePopulator());
	return initializer;
}
 
Example 17
Project: SpringMvcLoginSecureExample   File: SpringConfig.java   View source code 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));
    dataSource.setPassword(env.getProperty("spring.datasource.password"));
    return dataSource;
}
 
Example 18
Project: spring-i18n-support   File: WebappConfig.java   View source code 5 votes vote down vote up
@Bean
public DataSource dataSource() {
	EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
	EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2)
	                             .addScript("/jdbc/schema.sql")
	                             .addScript("/jdbc/data.sql")
	                             .build();
	return db;
}
 
Example 19
Project: xm-ms-entity   File: DatabaseConfiguration.java   View source code 5 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
                                                                   MultiTenantConnectionProvider multiTenantConnectionProviderImpl,
                                                                   CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl,
                                                                   LocalValidatorFactoryBean localValidatorFactoryBean) {
    Map<String, Object> properties = new HashMap<>();
    properties.putAll(jpaProperties.getHibernateProperties(dataSource));
    properties.put(org.hibernate.cfg.Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
    properties
        .put(org.hibernate.cfg.Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl);
    properties
        .put(org.hibernate.cfg.Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl);

    properties.put(JPA_VALIDATION_FACTORY, localValidatorFactoryBean);

    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan(JPA_PACKAGES);
    em.setJpaVendorAdapter(jpaVendorAdapter());
    em.setJpaPropertyMap(properties);
    return em;
}
 
Example 20
Project: lams   File: DataSourceUtils.java   View source code 5 votes vote down vote up
/**
 * Determine the connection synchronization order to use for the given
 * DataSource. Decreased for every level of nesting that a DataSource
 * has, checked through the level of DelegatingDataSource nesting.
 * @param dataSource the DataSource to check
 * @return the connection synchronization order to use
 * @see #CONNECTION_SYNCHRONIZATION_ORDER
 */
private static int getConnectionSynchronizationOrder(DataSource dataSource) {
	int order = CONNECTION_SYNCHRONIZATION_ORDER;
	DataSource currDs = dataSource;
	while (currDs instanceof DelegatingDataSource) {
		order--;
		currDs = ((DelegatingDataSource) currDs).getTargetDataSource();
	}
	return order;
}
 
Example 21
Project: monarch   File: BlockingTimeOutJUnitTest.java   View source code 5 votes vote down vote up
private static void createTable(String tableName) throws Exception {
  Context ctx = cache.getJNDIContext();
  DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
  String sql = "create table " + tableName
      + " (id integer NOT NULL, name varchar(50), CONSTRAINT the_key PRIMARY KEY(id))";
  logger.debug(sql);
  Connection conn = ds.getConnection();
  Statement sm = conn.createStatement();
  sm.execute(sql);
  sm.close();
  sm = conn.createStatement();
  for (int i = 1; i <= 10; i++) {
    sql = "insert into " + tableName + " values (" + i + ",'name" + i + "')";
    sm.addBatch(sql);
    logger.debug(sql);
  }
  sm.executeBatch();
  conn.close();
}
 
Example 22
Project: springuni-particles   File: AbstractJpaRepositoryConfiguration.java   View source code 5 votes vote down vote up
/**
 * Creates the entity manager factory.
 *
 * @param dataSource the data source to use
 * @return entity manager factory
 */
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
  LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
      new LocalContainerEntityManagerFactoryBean();

  entityManagerFactoryBean.setDataSource(dataSource);

  JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter();
  entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);

  Map<String, String> jpaPropertyMap = getJpaPropertyMap();
  entityManagerFactoryBean.setJpaPropertyMap(jpaPropertyMap);

  getMappingResources().ifPresent(entityManagerFactoryBean::setMappingResources);
  getPackagesToScan().ifPresent(entityManagerFactoryBean::setPackagesToScan);

  // https://hibernate.atlassian.net/browse/HHH-5303#comment-44439
  entityManagerFactoryBean.setSharedCacheMode(ENABLE_SELECTIVE);

  customizeEntityManagerFactoryBean(entityManagerFactoryBean);

  return entityManagerFactoryBean;
}
 
Example 23
Project: bean-searcher   File: SearchPlugin.java   View source code 5 votes vote down vote up
@Override
public boolean start() {
	if (scanPackage == null) {
		throw new RuntimeException("SearchPlugin: scanPackage 不能为 空!");
	}
	DataSource dataSource = dataSourceProvider.getDataSource();
	if (dataSource == null) {
		throw new RuntimeException("Can not get DataSource from IDataSourceProvider, "
				+ "please confirm IDataSourceProvider is in front of SearchPlugin");
	}
	Ioc.add(Searcher.class, SearcherBuilder.builder()
			.configSearchSqlExecutor(new MainSearchSqlExecutor(dataSource))
			.build());
	if (scanJar != null) {
		return starter.start(scanJar, scanPackage);
	} else {
		return starter.start(scanPackage);
	}
}
 
Example 24
Project: OftenPorter   File: MyBatisBridge.java   View source code 5 votes vote down vote up
/**
 * @param dataSourceClass {@linkplain DataSource}实现类.
 * @param properties
 * @return
 */
public static DataSource buildDataSource(String dataSourceClass, Properties properties)
{
    try
    {
        Class<?> clazz = PackageUtil.newClass(dataSourceClass, null);
        DataSource dataSource = (DataSource) WPTool.newObject(clazz);
        DataSourceFactory factory = new TempFactory(dataSource);
        factory.setProperties(properties);
        return factory.getDataSource();
    } catch (Exception e)
    {
        throw new DBException(e);
    }
}
 
Example 25
Project: simple-openid-provider   File: JdbcClientRepositoryIntegrationTests.java   View source code 5 votes vote down vote up
@Bean
DataSource dataSource() {
	// @formatter:off
	return new EmbeddedDatabaseBuilder()
			.generateUniqueName(true)
			.setType(EmbeddedDatabaseType.H2)
			.addScript("schema-clients.sql")
			.build();
	// @formatter:on
}
 
Example 26
Project: springboot   File: ClusterDataSourceConfig.java   View source code 5 votes vote down vote up
@Bean(name = "clusterDataSource")
public DataSource ClusterDataSource(){
	DruidDataSource datasource = new DruidDataSource();
	datasource.setUrl(url);
	datasource.setUsername(user);
	datasource.setPassword(password);
	datasource.setDriverClassName(driverClass);
	return datasource;
}
 
Example 27
Project: Spring-Security-Third-Edition   File: DataSourceConfig.java   View source code 5 votes vote down vote up
/**
 * Embedded H2 database
 * Connect to running database with the following details:
 *
 * URL: jdbc:h2:mem:dataSource
 * Driver Class: org.h2.Driver
 * Username: sa
 * Password: [blank]
 *
 * @return
 */
@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    database = builder.setType(EmbeddedDatabaseType.H2)
            .setName("dataSource")
            .ignoreFailedDrops(true)
            .continueOnError(false)
            .addScript("classpath:database/h2/calendar-schema.sql")
            .addScript("classpath:database/h2/calendar-data.sql")
            .build();
    return database;
}
 
Example 28
Project: org.ops4j.pax.transx   File: ManagedDataSourceBuilder.java   View source code 5 votes vote down vote up
private static AbstractJdbcManagedConnectionFactory<?, ?, ?> create(CommonDataSource dataSource) {
    if (dataSource instanceof XADataSource) {
        return new XADataSourceMCF((XADataSource) dataSource);
    }
    else if (dataSource instanceof ConnectionPoolDataSource) {
        return new ConnectionPoolDataSourceMCF((ConnectionPoolDataSource) dataSource);
    }
    else if (dataSource instanceof DataSource) {
        return new LocalDataSourceMCF((DataSource) dataSource);
    }
    else {
        throw new UnsupportedOperationException();
    }
}
 
Example 29
Project: Agent-Benchmarks   File: DataSourceConfiguration.java   View source code 5 votes vote down vote up
@Bean
@Primary
public DataSource getDataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName("com.mysql.jdbc.Driver");
    config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    config.setUsername("root");
    config.setPassword("root");
    config.setMaximumPoolSize(500);
    config.setMinimumIdle(10);
    return new HikariDataSource(config);
}
 
Example 30
Project: monarch   File: TransactionTimeOutJUnitTest.java   View source code 5 votes vote down vote up
@Test
public void test7Commit() throws Exception {
  Context ctx = cache.getJNDIContext();
  DataSource ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
  ds2.getConnection();
  GemFireTransactionDataSource ds =
      (GemFireTransactionDataSource) ctx.lookup("java:/XAPooledDataSource");
  UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
  utx.begin();
  Connection conn = ds.getConnection();
  String sql = "create table newTable1 (id integer)";
  Statement sm = conn.createStatement();
  sm.execute(sql);
  utx.setTransactionTimeout(30);
  Thread.sleep(5000);
  utx.setTransactionTimeout(20);
  utx.setTransactionTimeout(10);
  sql = "insert into newTable1  values (1)";
  sm.execute(sql);
  utx.commit();
  sql = "select * from newTable1 where id = 1";
  ResultSet rs = sm.executeQuery(sql);
  if (!rs.next()) {
    fail("Transaction not committed");
  }
  sql = "drop table newTable1";
  sm.execute(sql);
  sm.close();
  conn.close();
}
 
Example 31
Project: traccar-service   File: WebServer.java   View source code 5 votes vote down vote up
public WebServer(Config config, DataSource dataSource) {
    this.config = config;
    this.dataSource = dataSource;

    sessionManager = new HashSessionManager();
    int sessionTimeout = config.getInteger("web.sessionTimeout");
    if (sessionTimeout != 0) {
        sessionManager.setMaxInactiveInterval(sessionTimeout);
    }

    initServer();
    initApi();
    if (config.getBoolean("web.console")) {
        initConsole();
    }
    switch (config.getString("web.type", "new")) {
        case "old":
            initOldWebApp();
            break;
        default:
            initWebApp();
            break;
    }
    initClientProxy();
    server.setHandler(handlers);

    server.addBean(new ErrorHandler() {
        @Override
        protected void handleErrorPage(
                HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>"
                    + code + " - " + HttpStatus.getMessage(code) + "</body></html>");
        }
    }, false);
}
 
Example 32
Project: rjb-blog-multitenancy   File: MultiTenantDataSourceConfig.java   View source code 5 votes vote down vote up
@Bean
public DataSource dataSource() {
	MultiTenantDataSource returnVal = new MultiTenantDataSource(contextConfig.tenantResolver());
	Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
	targetDataSources.putAll(propertiesConfig.getTenantJndiDataSourceMappings());
	returnVal.setTargetDataSources(targetDataSources);
	returnVal.setLenientFallback(false);
	return returnVal;
}
 
Example 33
Project: otus_java_2017_10   File: MainAnnotationsExample.java   View source code 5 votes vote down vote up
private DataSource getH2DataSource() {
    PooledDataSource ds = new PooledDataSource();

    ds.setDriver("org.h2.Driver");
    ds.setUrl("jdbc:h2:mem:test");
    ds.setUsername("sa");

    return ds;
}
 
Example 34
Project: spring-cloud-dashboard   File: DataflowRdbmsInitializer.java   View source code 5 votes vote down vote up
private String getDatabaseType(DataSource dataSource) {
	try {
		return DatabaseType.fromMetaData(dataSource).toString().toLowerCase();
	}
	catch (MetaDataAccessException ex) {
		throw new IllegalStateException("Unable to detect database type", ex);
	}
}
 
Example 35
Project: spring-boot-data-source-decorator   File: ProxyDataSourceConfigurationTests.java   View source code 5 votes vote down vote up
@Test
public void testRegisterLogAndSlowQueryLogUsingSlf4j() throws Exception {
    EnvironmentTestUtils.addEnvironment(context,
            "decorator.datasource.datasource-proxy.logging:slf4j");
    context.register(DataSourceAutoConfiguration.class,
            DataSourceDecoratorAutoConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class);
    context.refresh();

    DataSource dataSource = context.getBean(DataSource.class);
    ProxyDataSource proxyDataSource = (ProxyDataSource) ((DecoratedDataSource) dataSource).getDecoratedDataSource();
    ChainListener chainListener = proxyDataSource.getProxyConfig().getQueryListener();
    assertThat(chainListener.getListeners()).extracting("class").contains(SLF4JSlowQueryListener.class);
    assertThat(chainListener.getListeners()).extracting("class").contains(SLF4JQueryLoggingListener.class);
}
 
Example 36
Project: elastic-job-example   File: JavaMain.java   View source code 5 votes vote down vote up
private static DataSource setUpEventTraceDataSource() {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(EVENT_RDB_STORAGE_DRIVER);
    result.setUrl(EVENT_RDB_STORAGE_URL);
    result.setUsername(EVENT_RDB_STORAGE_USERNAME);
    result.setPassword(EVENT_RDB_STORAGE_PASSWORD);
    return result;
}
 
Example 37
Project: lams   File: LocalSessionFactoryBean.java   View source code 5 votes vote down vote up
/**
 * Execute schema update script, determined by the Configuration object
 * used for creating the SessionFactory. A replacement for Hibernate's
 * SchemaUpdate class, for automatically executing schema update scripts
 * on application startup. Can also be invoked manually.
 * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed
 * SessionFactory to be able to invoke this method, e.g. via
 * {@code LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");}.
 * <p>Uses the SessionFactory that this bean generates for accessing a
 * JDBC connection to perform the script.
 * @throws DataAccessException in case of script execution errors
 * @see #setSchemaUpdate
 * @see org.hibernate.cfg.Configuration#generateSchemaUpdateScript
 * @see org.hibernate.tool.hbm2ddl.SchemaUpdate
 */
public void updateDatabaseSchema() throws DataAccessException {
	logger.info("Updating database schema for Hibernate SessionFactory");
	DataSource dataSource = getDataSource();
	if (dataSource != null) {
		// Make given DataSource available for the schema update.
		configTimeDataSourceHolder.set(dataSource);
	}
	try {
		SessionFactory sessionFactory = getSessionFactory();
		final Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect();
		HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
		hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER);
		hibernateTemplate.execute(
			new HibernateCallback<Object>() {
				@Override
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					@SuppressWarnings("deprecation")
					Connection con = session.connection();
					DatabaseMetadata metadata = new DatabaseMetadata(con, dialect);
					String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata);
					executeSchemaScript(con, sql);
					return null;
				}
			}
		);
	}
	finally {
		if (dataSource != null) {
			configTimeDataSourceHolder.remove();
		}
	}
}
 
Example 38
Project: curiostack   File: DatabaseModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
static DataSource dataSource(DatabaseConfig config) {
  HikariConfig hikari = new HikariConfig();
  hikari.setJdbcUrl(config.getJdbcUrl());
  hikari.setUsername(config.getUsername());
  hikari.setPassword(config.getPassword());
  hikari.addDataSourceProperty("cachePrepStmts", "true");
  hikari.addDataSourceProperty(
      "statementInterceptors", "brave.mysql.TracingStatementInterceptor");
  hikari.addDataSourceProperty("useUnicode", "yes");
  hikari.setMetricsTrackerFactory(new PrometheusMetricsTrackerFactory());
  return new HikariDataSource(hikari);
}
 
Example 39
Project: spring-data-examples   File: OrderConfig.java   View source code 5 votes vote down vote up
@Bean
DataSource orderDataSource() {

	return new EmbeddedDatabaseBuilder().//
			setType(EmbeddedDatabaseType.HSQL).//
			setName("orders").//
			build();
}
 
Example 40
Project: spring-boot-data-source-decorator   File: FlexyPoolConfigurationTests.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends DataSource> FlexyPoolDataSource<T> assertDataSourceOfType(DataSource dataSource, Class<T> realDataSourceClass) {
    assertThat(dataSource).isInstanceOf(DecoratedDataSource.class);
    DataSource decoratedDataSource = ((DecoratedDataSource) dataSource).getDecoratedDataSource();
    assertThat(decoratedDataSource).isInstanceOf(FlexyPoolDataSource.class);
    Field field = ReflectionUtils.findField(FlexyPoolDataSource.class, "targetDataSource");
    ReflectionUtils.makeAccessible(field);
    Object targetDataSource = ReflectionUtils.getField(field, decoratedDataSource);
    assertThat(targetDataSource).isInstanceOf(realDataSourceClass);
    return (FlexyPoolDataSource<T>) decoratedDataSource;
}