Java Code Examples for org.springframework.boot.autoconfigure.jdbc.DataSourceProperties

The following are top voted examples for showing how to use org.springframework.boot.autoconfigure.jdbc.DataSourceProperties. 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: infobip-spring-data-jpa-querydsl   File: SqlServerFlywayTestMigrationStrategy.java   Source Code and License 6 votes vote down vote up
public SqlServerFlywayTestMigrationStrategy(DataSourceProperties dataSourceProps) {
    Pattern jdbcBaseUrlWithDbNamePattern = Pattern.compile(DB_URL_PATTERN);
    Matcher matcher = jdbcBaseUrlWithDbNamePattern.matcher(dataSourceProps.getUrl());

    if(!matcher.matches()) {
        throw new IllegalArgumentException(dataSourceProps.getUrl() + " does not match " + DB_URL_PATTERN);
    }

    String jdbcBaseUrl = matcher.group("jdbcBaseUrl");
    String databaseName = matcher.group("databaseName");
    databaseExistsQuery = String.format("SELECT count(*) FROM sys.databases WHERE name='%s'", databaseName);
    createDatabaseQuery = String.format("CREATE DATABASE %s", databaseName);
    this.template = new JdbcTemplate(new SimpleDriverDataSource(
            getDriver(jdbcBaseUrl),
            jdbcBaseUrl,
            dataSourceProps.getUsername(),
            dataSourceProps.getPassword()));
}
 
Example 2
Project: jhipster-ribbon-hystrix   File: DatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariDataSource hikariDataSource =  (HikariDataSource) DataSourceBuilder
            .create(dataSourceProperties.getClassLoader())
            .type(HikariDataSource.class)
            .driverClassName(dataSourceProperties.getDriverClassName())
            .url(dataSourceProperties.getUrl())
            .username(dataSourceProperties.getUsername())
            .password(dataSourceProperties.getPassword())
            .build();

    if (metricRegistry != null) {
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    return hikariDataSource;
}
 
Example 3
Project: jhipster-ribbon-hystrix   File: _HerokuDatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource(DataSourceProperties dataSourceProperties<% if (hibernateCache == 'hazelcast') { %>, CacheManager cacheManager<% } %>) {
        log.debug("Configuring Heroku Datasource");

        String herokuUrl = System.getenv("JDBC_DATABASE_URL");
        if (herokuUrl != null) {
            return DataSourceBuilder
                .create(dataSourceProperties.getClassLoader())
                .type(HikariDataSource.class)
                .url(herokuUrl)
                .build();
        } else {
            throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL");
        }
    }
}
 
Example 4
Project: jhipster-ribbon-hystrix   File: DatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariDataSource hikariDataSource =  (HikariDataSource) DataSourceBuilder
            .create(dataSourceProperties.getClassLoader())
            .type(HikariDataSource.class)
            .driverClassName(dataSourceProperties.getDriverClassName())
            .url(dataSourceProperties.getUrl())
            .username(dataSourceProperties.getUsername())
            .password(dataSourceProperties.getPassword())
            .build();

    if (metricRegistry != null) {
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    return hikariDataSource;
}
 
Example 5
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void dataSourceHealthIndicatorWithCustomValidationQuery() {
	this.context.register(PropertyPlaceholderAutoConfiguration.class,
			ManagementServerProperties.class, DataSourceProperties.class,
			DataSourceConfig.class,
			DataSourcePoolMetadataProvidersConfiguration.class,
			HealthIndicatorAutoConfiguration.class);
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.test.validation-query:SELECT from FOOBAR",
			"management.health.diskspace.enabled:false");
	this.context.refresh();
	Map<String, HealthIndicator> beans = this.context
			.getBeansOfType(HealthIndicator.class);
	assertThat(beans).hasSize(1);
	HealthIndicator healthIndicator = beans.values().iterator().next();
	assertThat(healthIndicator.getClass()).isEqualTo(DataSourceHealthIndicator.class);
	DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator;
	assertThat(dataSourceHealthIndicator.getQuery()).isEqualTo("SELECT from FOOBAR");
}
 
Example 6
Project: haven-platform   File: DataSourceConfig.java   Source Code and License 6 votes vote down vote up
@Bean
@Primary
public DataSourceProperties dataSourceProperties() {
    DataSourceProperties properties = new DataSourceProperties();
    properties.setInitialize(false);
    // dbName.serviceName example: user-db.mysql (we must )
    final String serviceId = environment.getProperty(MYSQL_SERVICE_ID);
    if (discoveryClient != null && serviceId != null) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        if (!instances.isEmpty()) {
            properties.setUrl(getJdbcUrl(instances, fetchDBName(serviceId)));
        }  else {
            LOGGER.warn("there is no services with id {} in service discovery", serviceId);
        }
    }
    return properties;
}
 
Example 7
Project: blackhole   File: DatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariDataSource hikariDataSource =  (HikariDataSource) DataSourceBuilder
            .create(dataSourceProperties.getClassLoader())
            .type(HikariDataSource.class)
            .driverClassName(dataSourceProperties.getDriverClassName())
            .url(dataSourceProperties.getUrl())
            .username(dataSourceProperties.getUsername())
            .password(dataSourceProperties.getPassword())
            .build();

    if (metricRegistry != null) {
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    return hikariDataSource;
}
 
Example 8
Project: oyd-pia   File: HerokuDatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Heroku Datasource");

    String herokuUrl = System.getenv("JDBC_DATABASE_URL");
    if (herokuUrl != null) {
 HikariConfig config = new HikariConfig();

 //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
 if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
            config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
            config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
            config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
        }

        config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
        config.addDataSourceProperty("url", herokuUrl);
        return new HikariDataSource(config);
    } else {
        throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL");
    }
}
 
Example 9
Project: spring-boot-concourse   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void dataSourceHealthIndicatorWithCustomValidationQuery() {
	this.context.register(PropertyPlaceholderAutoConfiguration.class,
			ManagementServerProperties.class, DataSourceProperties.class,
			DataSourceConfig.class,
			DataSourcePoolMetadataProvidersConfiguration.class,
			HealthIndicatorAutoConfiguration.class);
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.test.validation-query:SELECT from FOOBAR",
			"management.health.diskspace.enabled:false");
	this.context.refresh();
	Map<String, HealthIndicator> beans = this.context
			.getBeansOfType(HealthIndicator.class);
	assertThat(beans).hasSize(1);
	HealthIndicator healthIndicator = beans.values().iterator().next();
	assertThat(healthIndicator.getClass()).isEqualTo(DataSourceHealthIndicator.class);
	DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator;
	assertThat(dataSourceHealthIndicator.getQuery()).isEqualTo("SELECT from FOOBAR");
}
 
Example 10
Project: contestparser   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void dataSourceHealthIndicatorWithCustomValidationQuery() {
	this.context.register(PropertyPlaceholderAutoConfiguration.class,
			ManagementServerProperties.class, DataSourceProperties.class,
			DataSourceConfig.class,
			DataSourcePoolMetadataProvidersConfiguration.class,
			HealthIndicatorAutoConfiguration.class);
	EnvironmentTestUtils.addEnvironment(this.context,
			"spring.datasource.validation-query:SELECT from FOOBAR",
			"management.health.diskspace.enabled:false");
	this.context.refresh();
	Map<String, HealthIndicator> beans = this.context
			.getBeansOfType(HealthIndicator.class);
	assertEquals(1, beans.size());
	HealthIndicator healthIndicator = beans.values().iterator().next();
	assertEquals(DataSourceHealthIndicator.class, healthIndicator.getClass());
	DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator;
	assertEquals("SELECT from FOOBAR", dataSourceHealthIndicator.getQuery());
}
 
Example 11
Project: p2p-webtv   File: HerokuDatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public DataSource dataSource(DataSourceProperties dataSourceProperties, ApplicationProperties applicationProperties) {
  log.debug("Configuring Heroku Datasource");

  String herokuUrl = System.getenv("JDBC_DATABASE_URL");
  if (herokuUrl != null) {
    HikariConfig config = new HikariConfig();

    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
      config.addDataSourceProperty("cachePrepStmts", applicationProperties.getDatasource().isCachePrepStmts());
      config.addDataSourceProperty("prepStmtCacheSize", applicationProperties.getDatasource().getPrepStmtCacheSize());
      config.addDataSourceProperty("prepStmtCacheSqlLimit", applicationProperties.getDatasource().getPrepStmtCacheSqlLimit());
    }

    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", herokuUrl);
    return new HikariDataSource(config);
  } else {
    throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL");
  }
}
 
Example 12
Project: p2p-webtv   File: DatabaseConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, ApplicationProperties applicationProperties) {
  log.debug("Configuring Datasource");
  if (dataSourceProperties.getUrl() == null) {
    log.error("Your database connection pool configuration is incorrect! The application cannot start. " +
      "Please check your Spring profile, current profiles are: {}", Arrays.toString(environment.getActiveProfiles()));
    throw new ApplicationContextException("Database connection pool is not configured correctly");
  }
  HikariConfig config = new HikariConfig();
  config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
  config.addDataSourceProperty("url", dataSourceProperties.getUrl());
  config.addDataSourceProperty("user", dataSourceProperties.getUsername() != null ? dataSourceProperties.getUsername() : "");
  config.addDataSourceProperty("password", dataSourceProperties.getPassword() != null ? dataSourceProperties.getPassword() : "");
  if (metricRegistry != null) {
    config.setMetricRegistry(metricRegistry);
  }
  return new HikariDataSource(config);
}
 
Example 13
Project: orchestrator   File: DatasourceConfig.java   Source Code and License 6 votes vote down vote up
private XADataSource createXaDataSource(DataSourceProperties properties)
    throws ClassNotFoundException, LinkageError {
  String className = Optional
      .ofNullable(properties.getXa())
      .map(Xa::getDataSourceClassName)
      .map(String::trim)
      .map(Strings::emptyToNull)
      .orElseGet(() -> DatabaseDriver
          .fromJdbcUrl(properties.determineUrl())
          .getXaDataSourceClassName());
  Assert.state(StringUtils.hasLength(className),
      "No XA DataSource class name specified or inferred");
  XADataSource dataSource = createXaDataSourceInstance(className);
  bindXaProperties(dataSource, properties);
  return dataSource;
}
 
Example 14
Project: buenojo   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 15
Project: springboot-security-wechat   File: AuditDsConfig.java   Source Code and License 5 votes vote down vote up
/**
 * 数据源配置对象
 * Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入
 * @return
 */
@Bean
@Primary
@ConfigurationProperties("first.datasource")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}
 
Example 16
Project: spring-boot-multidatasource   File: DataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.datasource1.url")
@ConfigurationProperties(prefix = "spring.datasource1")
public DataSourceInitializer dataSourceInitializer1(DataSourceProperties properties,
		ApplicationContext applicationContext) {
	return new DataSourceInitializer(properties, applicationContext, 1);
}
 
Example 17
Project: spring-boot-multidatasource   File: DataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.datasource2.url")
@ConfigurationProperties(prefix = "spring.datasource2")
public DataSourceInitializer dataSourceInitializer2(DataSourceProperties properties,
		ApplicationContext applicationContext) {
	return new DataSourceInitializer(properties, applicationContext, 2);
}
 
Example 18
Project: spring-boot-multidatasource   File: DataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.datasource3.url")
@ConfigurationProperties(prefix = "spring.datasource3")
public DataSourceInitializer dataSourceInitializer3(DataSourceProperties properties,
		ApplicationContext applicationContext) {
	return new DataSourceInitializer(properties, applicationContext, 3);
}
 
Example 19
Project: spring-boot-multidatasource   File: DataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.datasource4.url")
@ConfigurationProperties(prefix = "spring.datasource4")
public DataSourceInitializer dataSourceInitializer4(DataSourceProperties properties,
		ApplicationContext applicationContext) {
	return new DataSourceInitializer(properties, applicationContext, 4);
}
 
Example 20
Project: spring-boot-multidatasource   File: DataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.datasource5.url")
@ConfigurationProperties(prefix = "spring.datasource5")
public DataSourceInitializer dataSourceInitializer5(DataSourceProperties properties,
		ApplicationContext applicationContext) {
	return new DataSourceInitializer(properties, applicationContext, 5);
}
 
Example 21
Project: spring-boot-multidatasource   File: DataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = "spring.datasource6.url")
@ConfigurationProperties(prefix = "spring.datasource6")
public DataSourceInitializer dataSourceInitializer6(DataSourceProperties properties,
		ApplicationContext applicationContext) {
	return new DataSourceInitializer(properties, applicationContext, 6);
}
 
Example 22
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
protected org.apache.tomcat.jdbc.pool.DataSource createTomcatDataSource(DataSourceProperties properties) {
	org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource(
			properties, org.apache.tomcat.jdbc.pool.DataSource.class);
	DatabaseDriver databaseDriver = DatabaseDriver
			.fromJdbcUrl(properties.determineUrl());
	String validationQuery = databaseDriver.getValidationQuery();
	if (validationQuery != null) {
		dataSource.setTestOnBorrow(true);
		dataSource.setValidationQuery(validationQuery);
	}
	return dataSource; 
}
 
Example 23
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.tomcat")
public org.apache.tomcat.jdbc.pool.DataSource dataSource(
		@Qualifier("dataSourceProperties") DataSourceProperties properties) {
	return createTomcatDataSource(properties);
}
 
Example 24
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.dbcp2")
public org.apache.commons.dbcp2.BasicDataSource dataSource(
		@Qualifier("dataSourceProperties") DataSourceProperties properties) {
	return createDataSource(properties,
			org.apache.commons.dbcp2.BasicDataSource.class);
}
 
Example 25
Project: shoucang   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 26
Project: spring-cloud-gcp   File: GcpCloudSqlAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
public DataSourceProperties cloudSqlDataSourceProperties(DataSourceProperties properties,
		CloudSqlJdbcInfoProvider cloudSqlJdbcInfoProvider) {
	if (StringUtils.isEmpty(properties.getUsername())) {
		properties.setUsername("root");
		LOGGER.warn("spring.datasource.username is not specified. Setting default username.");
	}
	if (StringUtils.isEmpty(properties.getDriverClassName())) {
		properties.setDriverClassName(cloudSqlJdbcInfoProvider.getJdbcDriverClass());
	}
	else {
		LOGGER.warn(
				"spring.datasource.driver-class-name is specified. Not using generated Cloud SQL configuration");
	}
	if (StringUtils.isEmpty(properties.getUrl())) {
		properties.setUrl(cloudSqlJdbcInfoProvider.getJdbcUrl());
	}
	else {
		LOGGER.warn("spring.datasource.jdbc-url is specified. Not using generated Cloud SQL configuration");
	}
	return properties;
}
 
Example 27
Project: klask-io   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariDataSource hikariDataSource =  (HikariDataSource) DataSourceBuilder
            .create(dataSourceProperties.getClassLoader())
            .type(HikariDataSource.class)
            .driverClassName(dataSourceProperties.getDriverClassName())
            .url(dataSourceProperties.getUrl())
            .username(dataSourceProperties.getUsername())
            .password(dataSourceProperties.getPassword())
            .build();

    if (metricRegistry != null) {
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    return hikariDataSource;
}
 
Example 28
Project: blogAggr   File: HerokuDatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Heroku Datasource");

    String herokuUrl = System.getenv("JDBC_DATABASE_URL");
    if (herokuUrl != null) {
 HikariConfig config = new HikariConfig();
 
 //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
 if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
            config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
            config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
            config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
        }

        config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
        config.addDataSourceProperty("url", herokuUrl);
        return new HikariDataSource(config);
    } else {
        throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL");
    }
}
 
Example 29
Project: ugc-bot-redux   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, LeagueProperties leagueProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
        config.addDataSourceProperty("cachePrepStmts", leagueProperties.getDatasource().isCachePrepStmts());
        config.addDataSourceProperty("prepStmtCacheSize", leagueProperties.getDatasource().getPrepStmtCacheSize());
        config.addDataSourceProperty("prepStmtCacheSqlLimit", leagueProperties.getDatasource().getPrepStmtCacheSqlLimit());
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    if (healthCheckRegistry != null) {
        config.setHealthCheckRegistry(healthCheckRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 30
Project: jhipster-ribbon-hystrix   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariDataSource hikariDataSource =  (HikariDataSource) DataSourceBuilder
            .create(dataSourceProperties.getClassLoader())
            .type(HikariDataSource.class)
            .driverClassName(dataSourceProperties.getDriverClassName())
            .url(dataSourceProperties.getUrl())
            .username(dataSourceProperties.getUsername())
            .password(dataSourceProperties.getPassword())
            .build();

    if (metricRegistry != null) {
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    return hikariDataSource;
}
 
Example 31
Project: jhipster-ribbon-hystrix   File: _DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
    @ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource(DataSourceProperties dataSourceProperties<% if (hibernateCache == 'hazelcast') { %>, CacheManager cacheManager<% } %>) {
        log.debug("Configuring Datasource");
        if (dataSourceProperties.getUrl() == null) {
            log.error("Your database connection pool configuration is incorrect! The application" +
                    " cannot start. Please check your Spring profile, current profiles are: {}",
                Arrays.toString(env.getActiveProfiles()));

            throw new ApplicationContextException("Database connection pool is not configured correctly");
        }
        HikariDataSource hikariDataSource =  (HikariDataSource) DataSourceBuilder
                .create(dataSourceProperties.getClassLoader())
                .type(HikariDataSource.class)
                .driverClassName(dataSourceProperties.getDriverClassName())
                .url(dataSourceProperties.getUrl())
                .username(dataSourceProperties.getUsername())
                .password(dataSourceProperties.getPassword())
                .build();

        if (metricRegistry != null) {
            hikariDataSource.setMetricRegistry(metricRegistry);
        }
        return hikariDataSource;
    }
<%_ if (devDatabaseType == 'h2Disk' || devDatabaseType == 'h2Memory') { _%>
 
Example 32
Project: gameofcode   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
        config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
        config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
        config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 33
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: SampleActuatorApplicationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testConfigProps() throws Exception {
	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
			.getForEntity("http://localhost:" + this.port + "/configprops",
					Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
	@SuppressWarnings("unchecked")
	Map<String, Object> body = entity.getBody();
	assertThat(body)
			.containsKey("spring.datasource-" + DataSourceProperties.class.getName());
}
 
Example 34
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DevToolsDataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	String[] dataSourceBeanNames = context.getBeanFactory()
			.getBeanNamesForType(DataSource.class);
	if (dataSourceBeanNames.length != 1) {
		return ConditionOutcome
				.noMatch("A single DataSource bean was not found in the context");
	}
	if (context.getBeanFactory()
			.getBeanNamesForType(DataSourceProperties.class).length != 1) {
		return ConditionOutcome.noMatch(
				"A single DataSourceProperties bean was not found in the context");
	}
	BeanDefinition dataSourceDefinition = context.getRegistry()
			.getBeanDefinition(dataSourceBeanNames[0]);
	if (dataSourceDefinition instanceof AnnotatedBeanDefinition
			&& ((AnnotatedBeanDefinition) dataSourceDefinition)
					.getFactoryMethodMetadata() != null
			&& ((AnnotatedBeanDefinition) dataSourceDefinition)
					.getFactoryMethodMetadata().getDeclaringClassName()
					.startsWith(DataSourceAutoConfiguration.class.getPackage()
							.getName() + ".DataSourceConfiguration$")) {
		return ConditionOutcome.match("Found auto-configured DataSource");
	}
	return ConditionOutcome.noMatch("DataSource was not auto-configured");
}
 
Example 35
Project: shoucang   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 36
Project: oyd-pia   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 37
Project: eet.osslite.cz   File: PostgresDataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource getDataSource(DataSourceProperties props) {
	// TODO: change to any middleware
	PGPoolingDataSource source = new PGPoolingDataSource();

	source.setDataSourceName("eetds");
	source.setServerName("localhost");
	source.setDatabaseName(props.getName());
	source.setUser(props.getUsername());
	source.setPassword(props.getPassword());
	source.setMaxConnections(10);
	// source.setUrl("");

	return source;
}
 
Example 38
Project: spring-boot-concourse   File: DevToolsDataSourceAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	String[] dataSourceBeanNames = context.getBeanFactory()
			.getBeanNamesForType(DataSource.class);
	if (dataSourceBeanNames.length != 1) {
		return ConditionOutcome
				.noMatch("A single DataSource bean was not found in the context");
	}
	if (context.getBeanFactory()
			.getBeanNamesForType(DataSourceProperties.class).length != 1) {
		return ConditionOutcome.noMatch(
				"A single DataSourceProperties bean was not found in the context");
	}
	BeanDefinition dataSourceDefinition = context.getRegistry()
			.getBeanDefinition(dataSourceBeanNames[0]);
	if (dataSourceDefinition instanceof AnnotatedBeanDefinition
			&& ((AnnotatedBeanDefinition) dataSourceDefinition)
					.getFactoryMethodMetadata() != null
			&& ((AnnotatedBeanDefinition) dataSourceDefinition)
					.getFactoryMethodMetadata().getDeclaringClassName()
					.startsWith(DataSourceAutoConfiguration.class.getPackage()
							.getName() + ".DataSourceConfiguration$")) {
		return ConditionOutcome.match("Found auto-configured DataSource");
	}
	return ConditionOutcome.noMatch("DataSource was not auto-configured");
}
 
Example 39
Project: spring-boot-concourse   File: SampleActuatorApplicationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testConfigProps() throws Exception {
	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
			.getForEntity("http://localhost:" + this.port + "/configprops",
					Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
	@SuppressWarnings("unchecked")
	Map<String, Object> body = entity.getBody();
	assertThat(body)
			.containsKey("spring.datasource-" + DataSourceProperties.class.getName());
}
 
Example 40
Project: spring-cloud-dataflow   File: DefaultTaskService.java   Source Code and License 5 votes vote down vote up
/**
 * Initializes the {@link DefaultTaskService}.
 *
 * @param dataSourceProperties the data source properties.
 * @param taskDefinitionRepository the {@link TaskDefinitionRepository} this service will
 * use for task CRUD operations.
 * @param taskExecutionRepository the repository this service will use for deployment IDs.
 * @param taskExplorer the explorer this service will use to lookup task executions
 * @param registry URI registry this service will use to look up app URIs.
 * @param resourceLoader the {@link ResourceLoader} that will resolve URIs to
 * {@link Resource}s.
 * @param taskLauncher the launcher this service will use to launch task apps.
 * @param metaDataResolver the metadata resolver
 * @param taskConfigurationProperties the properties used to define the behavior of tasks
 * @param deploymentIdRepository the repository that maps deployment keys to IDs
 * @param dataflowServerUri the data flow server URI
 */
public DefaultTaskService(DataSourceProperties dataSourceProperties,
		TaskDefinitionRepository taskDefinitionRepository, TaskExplorer taskExplorer,
		TaskRepository taskExecutionRepository, AppRegistryCommon registry, ResourceLoader resourceLoader,
		TaskLauncher taskLauncher, ApplicationConfigurationMetadataResolver metaDataResolver,
		TaskConfigurationProperties taskConfigurationProperties, DeploymentIdRepository deploymentIdRepository,
		String dataflowServerUri) {
	Assert.notNull(dataSourceProperties, "DataSourceProperties must not be null");
	Assert.notNull(taskDefinitionRepository, "TaskDefinitionRepository must not be null");
	Assert.notNull(taskExecutionRepository, "TaskExecutionRepository must not be null");
	Assert.notNull(taskExplorer, "TaskExplorer must not be null");
	Assert.notNull(registry, "UriRegistry must not be null");
	Assert.notNull(resourceLoader, "ResourceLoader must not be null");
	Assert.notNull(taskLauncher, "TaskLauncher must not be null");
	Assert.notNull(metaDataResolver, "metaDataResolver must not be null");
	Assert.notNull(taskConfigurationProperties, "taskConfigurationProperties must not be null");
	Assert.notNull(deploymentIdRepository, "deploymentIdRepository must not be null");
	this.dataSourceProperties = dataSourceProperties;
	this.taskDefinitionRepository = taskDefinitionRepository;
	this.taskExecutionRepository = taskExecutionRepository;
	this.taskExplorer = taskExplorer;
	this.registry = registry;
	this.taskLauncher = taskLauncher;
	this.resourceLoader = resourceLoader;
	this.whitelistProperties = new WhitelistProperties(metaDataResolver);
	this.taskConfigurationProperties = taskConfigurationProperties;
	this.deploymentIdRepository = deploymentIdRepository;
	this.dataflowServerUri = dataflowServerUri;
}
 
Example 41
Project: spring-cloud-dataflow   File: TestDependencies.java   Source Code and License 5 votes vote down vote up
@Bean
public TaskService taskService(ApplicationConfigurationMetadataResolver metadataResolver,
		TaskRepository taskExecutionRepository, DeploymentIdRepository deploymentIdRepository,
		AppRegistryCommon appRegistry, DelegatingResourceLoader delegatingResourceLoader) {
	return new DefaultTaskService(new DataSourceProperties(), taskDefinitionRepository(), taskExplorer(),
			taskExecutionRepository, appRegistry, delegatingResourceLoader, taskLauncher(), metadataResolver,
			new TaskConfigurationProperties(), deploymentIdRepository, null);
}
 
Example 42
Project: spring-cloud-dataflow   File: JobDependencies.java   Source Code and License 5 votes vote down vote up
@Bean
public TaskService taskService(TaskDefinitionRepository repository, TaskExplorer explorer, AppRegistry registry,
		ResourceLoader resourceLoader, TaskLauncher taskLauncher,
		ApplicationConfigurationMetadataResolver metadataResolver, DeploymentIdRepository deploymentIdRepository) {
	return new DefaultTaskService(new DataSourceProperties(), repository, explorer, taskRepository(), registry,
			resourceLoader, taskLauncher, metadataResolver, new TaskConfigurationProperties(),
			deploymentIdRepository, null);
}
 
Example 43
Project: contestparser   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
public DataSource dataSource() {
	return DataSourceBuilder.create()
			.driverClassName("org.hsqldb.jdbc.JDBCDriver")
			.url("jdbc:hsqldb:mem:test").username("sa").build();
}
 
Example 44
Project: nosql-java   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 45
Project: nosql-java   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
        config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
        config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
        config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 46
Project: springboot-tourreservation   File: Config.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
DataSource realDataSource() {
    DataSource dataSource = DataSourceBuilder
            .create(this.dataSourceProperties.getClassLoader())
            .url(this.dataSourceProperties.getUrl())
            .username(this.dataSourceProperties.getUsername())
            .password(this.dataSourceProperties.getPassword())
            .build();
    return dataSource;
}
 
Example 47
Project: expper   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 48
Project: orchestrator   File: DatasourceConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@OrchestratorPersistenceUnit
@Primary
@ConfigurationProperties("datasource.orchestrator")
public DataSourceProperties orchestratorDataSourceProperties() {
  return new DataSourceProperties();
}
 
Example 49
Project: orchestrator   File: DatasourceConfig.java   Source Code and License 5 votes vote down vote up
private void bindXaProperties(XADataSource target, DataSourceProperties properties) {
  MutablePropertyValues values = new MutablePropertyValues()
      .add("user", properties.determineUsername())
      .add("password", properties.determinePassword())
      .add("url", properties.determineUrl());
  Optional
      .ofNullable(properties.getXa())
      .ifPresent(xa -> values.addPropertyValues(xa.getProperties()));
  new RelaxedDataBinder(target).withAlias("user", "username").bind(values);
}
 
Example 50
Project: druid-spring-boot   File: DruidDataSourceInitializer.java   Source Code and License 4 votes vote down vote up
public DruidDataSourceInitializer(DataSourceProperties properties,
                                  ApplicationContext applicationContext) {
    this.properties = properties;
    this.applicationContext = applicationContext;
}
 
Example 51
Project: druid-spring-boot   File: DruidDataSourceInitializerAutoConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean(value = DruidDataSourceInitializer.class, name = "dataSourceInitializer")
public DruidDataSourceInitializer dataSourceInitializer(DataSourceProperties properties,
                                                        ApplicationContext applicationContext) {
    return new DruidDataSourceInitializer(properties, applicationContext);
}
 
Example 52
Project: springboot-security-wechat   File: UserDsConfig.java   Source Code and License 4 votes vote down vote up
@Bean
@ConfigurationProperties("second.datasource")
public DataSourceProperties secondDataSourceProperties() {
    return new DataSourceProperties();
}
 
Example 53
Project: spring-boot-multidatasource   File: DataSourceInitializer.java   Source Code and License 4 votes vote down vote up
DataSourceInitializer(DataSourceProperties properties,
		ApplicationContext applicationContext, int index) {
	this.properties = properties;
	this.applicationContext = applicationContext;
	this.index = index;
}
 
Example 54
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T createDataSource(DataSourceProperties properties,
		Class<? extends DataSource> type) {
	return (T) properties.initializeDataSourceBuilder().type(type).build();
}
 
Example 55
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSourceProperties dataSourceProperties() {
	return new DataSourceProperties();
}
 
Example 56
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource1")
public DataSourceProperties dataSource1Properties() {
	return new DataSourceProperties();
}
 
Example 57
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource1.tomcat")
public org.apache.tomcat.jdbc.pool.DataSource dataSource1(@Qualifier("dataSource1Properties") DataSourceProperties properties) {
	return createTomcatDataSource(properties);
}
 
Example 58
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource2")
public DataSourceProperties dataSource2Properties() {
	return new DataSourceProperties();
}
 
Example 59
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource2.tomcat")
public org.apache.tomcat.jdbc.pool.DataSource dataSource2(@Qualifier("dataSource2Properties") DataSourceProperties properties) {
	return createTomcatDataSource(properties);
}
 
Example 60
Project: spring-boot-multidatasource   File: DataSourceConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource3")
public DataSourceProperties dataSource3Properties() {
	return new DataSourceProperties();
}