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

The following examples show how to use org.springframework.boot.autoconfigure.jdbc.DataSourceProperties. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 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 #2
Source File: DatabaseConfiguration.java    From galeb with Apache License 2.0 6 votes vote down vote up
@Bean
public HikariDataSource dataSource(DataSourceProperties properties) {
    HikariDataSource hikariDataSource = (HikariDataSource) properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    hikariDataSource.setConnectionTimeout(DB_CONN_TIMEOUT);
    hikariDataSource.setMaximumPoolSize(DB_MAX_POOL_SIZE);
    hikariDataSource.setMaxLifetime(DB_MAX_LIFE_TIME);
    hikariDataSource.setAutoCommit(DB_AUTOCOMMIT);
    hikariDataSource.setConnectionTestQuery("SELECT 1");
    hikariDataSource.addDataSourceProperty("cachePrepStmts", DB_CACHE_PREP_STMTS);
    hikariDataSource.addDataSourceProperty("prepStmtCacheSize", DB_PREP_STMT_CACHE_SIZE);
    hikariDataSource.addDataSourceProperty("prepStmtCacheSqlLimit", DB_PREP_STMT_CACHE_SQL_LIMIT);
    hikariDataSource.addDataSourceProperty("useServerPrepStmts", DB_USE_SERVER_PREP_STMTS);
    hikariDataSource.addDataSourceProperty("useLocalSessionState", DB_USE_LOCAL_SESSION_STATE);
    hikariDataSource.addDataSourceProperty("rewriteBatchedStatements", DB_REWRITE_BATCHED_STATEMENTS);
    hikariDataSource.addDataSourceProperty("cacheResultSetMetadata", DB_CACHE_RESULT_SET_METADATA);
    hikariDataSource.addDataSourceProperty("cacheServerConfiguration", DB_CACHE_SERVER_CONFIGURATION);
    hikariDataSource.addDataSourceProperty("elideSetAutoCommits", DB_ELIDE_SET_AUTO_COMMITS);
    hikariDataSource.addDataSourceProperty("maintainTimeStats", DB_MAINTAIN_TIME_STATS);

    return hikariDataSource;
}
 
Example #3
Source File: DataSourceConfig.java    From haven-platform with Apache License 2.0 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 #4
Source File: CacheDataSourceConfig.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
public DataSource cacheDataSource(@Autowired DataSourceProperties cacheDataSourceProperties) {
  String url = cacheDataSourceProperties.getUrl();

  // A simple inspection is done on the JDBC URL to deduce whether to create an in-memory
  // in-process database, start a file-based externally visible database or connect to
  // an external database.
  if (url.contains("hsql")) {
    String username =  cacheDataSourceProperties.getUsername();
    String password =  cacheDataSourceProperties.getPassword();
    return HsqlDatabaseBuilder.builder().url(url).username(username).password(password)
     .script(new ClassPathResource("sql/cache-schema-hsqldb.sql")).build().toDataSource();
  } else {
     return cacheDataSourceProperties.initializeDataSourceBuilder().build();
  }
}
 
Example #5
Source File: TaskServiceUtilsTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void testDatabasePropUpdate() {
	TaskDefinition taskDefinition = new TaskDefinition("testTask", "testApp");
	DataSourceProperties dataSourceProperties = new DataSourceProperties();
	dataSourceProperties.setUsername("myUser");
	dataSourceProperties.setDriverClassName("myDriver");
	dataSourceProperties.setPassword("myPassword");
	dataSourceProperties.setUrl("myUrl");
	TaskDefinition definition = TaskServiceUtils.updateTaskProperties(
			taskDefinition,
			dataSourceProperties);

	assertThat(definition.getProperties().size()).isEqualTo(5);
	assertThat(definition.getProperties().get("spring.datasource.url")).isEqualTo("myUrl");
	assertThat(definition.getProperties().get("spring.datasource.driverClassName")).isEqualTo("myDriver");
	assertThat(definition.getProperties().get("spring.datasource.username")).isEqualTo("myUser");
	assertThat(definition.getProperties().get("spring.datasource.password")).isEqualTo("myPassword");
}
 
Example #6
Source File: HistoryDataSourceConfig.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
@ConfigurationProperties("c2mon.server.history.jdbc")
public DataSource historyDataSource(@Autowired DataSourceProperties historyDataSourceProperties) {
  String url = historyDataSourceProperties.getUrl();

  if (url.contains("hsql")) {
    String username = historyDataSourceProperties.getUsername();
    String password = historyDataSourceProperties.getPassword();
    return HsqlDatabaseBuilder.builder()
               .url(url)
               .username(username)
               .password(password)
               .script(new ClassPathResource("sql/history-schema-hsqldb.sql")).build()
               .toDataSource();
  } else {
    return historyDataSourceProperties.initializeDataSourceBuilder().build();
  }
}
 
Example #7
Source File: ConfigDataSourceConfig.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
 public DataSource configurationDataSource(@Autowired DataSourceProperties configDataSourceProperties) {

String url = configDataSourceProperties.getUrl();

   // A simple inspection is done on the JDBC URL to deduce whether to create an in-memory
   // in-process database, start a file-based externally visible database or connect to
   // an external database.
   if (url.contains("hsql")) {
     String username = configDataSourceProperties.getUsername();
     String password = configDataSourceProperties.getPassword();
       
     return HsqlDatabaseBuilder.builder()
                .url(url)
                .username(username)
                .password(password)
                .script(new ClassPathResource("sql/config-schema-hsqldb.sql"))
                .build().toDataSource();
   } else {
   	return configDataSourceProperties.initializeDataSourceBuilder().build();
   }
 }
 
Example #8
Source File: SpringLiquibaseUtilTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void createSpringLiquibaseFromLiquibaseProperties() {
    DataSource liquibaseDatasource = null;
    LiquibaseProperties liquibaseProperties = new LiquibaseProperties();
    liquibaseProperties.setUrl("jdbc:h2:mem:liquibase");
    liquibaseProperties.setUser("sa");
    DataSource normalDataSource = null;
    DataSourceProperties dataSourceProperties = new DataSourceProperties();
    dataSourceProperties.setPassword("password");

    SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDatasource, liquibaseProperties, normalDataSource, dataSourceProperties);
    assertThat(liquibase)
        .asInstanceOf(type(DataSourceClosingSpringLiquibase.class))
        .extracting(SpringLiquibase::getDataSource)
        .asInstanceOf(type(HikariDataSource.class))
        .hasFieldOrPropertyWithValue("jdbcUrl", "jdbc:h2:mem:liquibase")
        .hasFieldOrPropertyWithValue("username", "sa")
        .hasFieldOrPropertyWithValue("password", "password");
}
 
Example #9
Source File: _HerokuDatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 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 #10
Source File: DruidAndMybatisApplicationContextInitializer.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {
        ClassUtils.forName("com.alibaba.druid.pool.DruidDataSource",this.getClass().getClassLoader());
    } catch (ClassNotFoundException e) {
        return;
    }
    applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof DataSourceProperties) {
                DataSourceProperties dataSourceProperties = (DataSourceProperties)bean;
                DruidAndMybatisApplicationContextInitializer.this.rewirteDataSourceProperties(dataSourceProperties);
            } else if (bean instanceof MybatisProperties) {
                MybatisProperties mybatisProperties = (MybatisProperties)bean;
                DruidAndMybatisApplicationContextInitializer.this.rewriteMybatisProperties(mybatisProperties);
            }
            return bean;
        }
    });

}
 
Example #11
Source File: DatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 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 #12
Source File: SpringLiquibaseUtilTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void createAsyncSpringLiquibaseFromLiquibaseProperties() {
    DataSource liquibaseDatasource = null;
    LiquibaseProperties liquibaseProperties = new LiquibaseProperties();
    liquibaseProperties.setUrl("jdbc:h2:mem:liquibase");
    liquibaseProperties.setUser("sa");
    DataSource normalDataSource = null;
    DataSourceProperties dataSourceProperties = new DataSourceProperties();
    dataSourceProperties.setPassword("password");

    AsyncSpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(null, null, liquibaseDatasource, liquibaseProperties, normalDataSource, dataSourceProperties);
    assertThat(liquibase.getDataSource())
        .asInstanceOf(type(HikariDataSource.class))
        .hasFieldOrPropertyWithValue("jdbcUrl", "jdbc:h2:mem:liquibase")
        .hasFieldOrPropertyWithValue("username", "sa")
        .hasFieldOrPropertyWithValue("password", "password");
}
 
Example #13
Source File: TaskServiceUtils.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the task definition with the datasource properties.
 * @param taskDefinition the {@link TaskDefinition} to be updated.
 * @param dataSourceProperties the dataSource properties used by SCDF.
 * @return the updated {@link TaskDefinition}
 */
public static TaskDefinition updateTaskProperties(TaskDefinition taskDefinition,
		DataSourceProperties dataSourceProperties) {
	Assert.notNull(taskDefinition, "taskDefinition must not be null");
	Assert.notNull(dataSourceProperties, "dataSourceProperties must not be null");
	TaskDefinition.TaskDefinitionBuilder builder = TaskDefinition.TaskDefinitionBuilder.from(taskDefinition);
	builder.setProperty("spring.datasource.url", dataSourceProperties.getUrl());
	builder.setProperty("spring.datasource.username", dataSourceProperties.getUsername());
	// password may be empty
	if (StringUtils.hasText(dataSourceProperties.getPassword())) {
		builder.setProperty("spring.datasource.password", dataSourceProperties.getPassword());
	}
	builder.setProperty("spring.datasource.driverClassName", dataSourceProperties.getDriverClassName());
	builder.setTaskName(taskDefinition.getTaskName());
	builder.setDslText(taskDefinition.getDslText());
	return builder.build();
}
 
Example #14
Source File: DefaultTaskExecutionInfoService.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the {@link DefaultTaskExecutionInfoService}.
 *
 * @param dataSourceProperties the data source properties.
 * @param appRegistryService URI registry this service will use to look up app URIs.
 * @param taskExplorer the explorer this service will use to lookup task executions
 * @param taskDefinitionRepository the {@link TaskDefinitionRepository} this service will
 *     use for task CRUD operations.
 * @param taskConfigurationProperties the properties used to define the behavior of tasks
 * @param launcherRepository the launcher repository
 * @param taskPlatforms the task platforms
 */
public DefaultTaskExecutionInfoService(DataSourceProperties dataSourceProperties,
		AppRegistryService appRegistryService,
		TaskExplorer taskExplorer,
		TaskDefinitionRepository taskDefinitionRepository,
		TaskConfigurationProperties taskConfigurationProperties,
		LauncherRepository launcherRepository,
		List<TaskPlatform> taskPlatforms) {
	Assert.notNull(dataSourceProperties, "DataSourceProperties must not be null");
	Assert.notNull(appRegistryService, "AppRegistryService must not be null");
	Assert.notNull(taskDefinitionRepository, "TaskDefinitionRepository must not be null");
	Assert.notNull(taskExplorer, "TaskExplorer must not be null");
	Assert.notNull(taskConfigurationProperties, "taskConfigurationProperties must not be null");
	Assert.notNull(launcherRepository, "launcherRepository must not be null");
	Assert.notEmpty(taskPlatforms, "taskPlatform must not be empty or null");

	this.dataSourceProperties = dataSourceProperties;
	this.appRegistryService = appRegistryService;
	this.taskExplorer = taskExplorer;
	this.taskDefinitionRepository = taskDefinitionRepository;
	this.taskConfigurationProperties = taskConfigurationProperties;
	this.launcherRepository = launcherRepository;
	this.taskPlatforms = taskPlatforms;
}
 
Example #15
Source File: DataSourceConfiguration.java    From event-sourcing-microservices-example with GNU General Public License v3.0 5 votes vote down vote up
@Bean
@ConfigurationProperties("spring.datasource")
@LiquibaseDataSource
public DataSource dataSource(DataSourceProperties properties) {
	return new SimpleDriverDataSource(new org.postgresql.Driver(), properties.getUrl(),
			properties.getDataUsername(), properties.getDataPassword());
}
 
Example #16
Source File: AuditDsConfig.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * 数据源配置对象
 * Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入
 * @return
 */
@Bean
@Primary
@ConfigurationProperties("first.datasource")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}
 
Example #17
Source File: TaskanaWildFlyApplication.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "datasource")
public DataSourceProperties dataSourceProperties() {
  DataSourceProperties props = new DataSourceProperties();
  props.setUrl(
      "jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS "
          + schemaName);
  return props;
}
 
Example #18
Source File: DefaultSchedulerServiceMultiplatformTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private SchedulerService getMockedKubernetesSchedulerService() {
	Launcher launcher = new Launcher(KUBERNETES_PLATFORM, "Kubernetes", Mockito.mock(TaskLauncher.class), scheduler);
	List<Launcher> launchers = new ArrayList<>();
	launchers.add(launcher);
	List<TaskPlatform> taskPlatform = Collections.singletonList(new TaskPlatform(KUBERNETES_PLATFORM, launchers));

	return  new DefaultSchedulerService(this.commonApplicationProperties,
			taskPlatform, this.taskDefinitionRepository,
			this.appRegistry, this.resourceLoader,
			this.taskConfigurationProperties, mock(DataSourceProperties.class), null,
			this.metaDataResolver, this.schedulerServiceProperties, this.auditRecordService);
}
 
Example #19
Source File: SchedulerConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public SchedulerService schedulerService(CommonApplicationProperties commonApplicationProperties,
		List<TaskPlatform> taskPlatforms, TaskDefinitionRepository taskDefinitionRepository,
		AppRegistryService registry, ResourceLoader resourceLoader,
		TaskConfigurationProperties taskConfigurationProperties,
		DataSourceProperties dataSourceProperties,
		ApplicationConfigurationMetadataResolver metaDataResolver,
		SchedulerServiceProperties schedulerServiceProperties,
		AuditRecordService auditRecordService) {
	return new DefaultSchedulerService(commonApplicationProperties,
			taskPlatforms, taskDefinitionRepository, registry, resourceLoader,
			taskConfigurationProperties, dataSourceProperties,
			this.dataflowServerUri, metaDataResolver, schedulerServiceProperties, auditRecordService);
}
 
Example #20
Source File: TestDependencies.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Bean
public TaskExecutionInfoService taskDefinitionRetriever(AppRegistryService registry,
		TaskExplorer taskExplorer, TaskDefinitionRepository taskDefinitionRepository,
		TaskConfigurationProperties taskConfigurationProperties, LauncherRepository launcherRepository,
		List<TaskPlatform> platforms) {
	return new DefaultTaskExecutionInfoService(new DataSourceProperties(),
			registry, taskExplorer, taskDefinitionRepository,
			taskConfigurationProperties, launcherRepository, platforms);
}
 
Example #21
Source File: RxJdbcConfig.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public Database database(DataSourceProperties dsProps) throws SQLException {
    NonBlockingConnectionPool pool =
            Pools.nonBlocking()
                    .maxPoolSize(Runtime.getRuntime().availableProcessors() * 2)
                    .connectionProvider(ConnectionProvider.from(dsProps.getUrl(), dsProps.getUsername(), dsProps.getPassword()))
                    .build();

    Database db = Database.from(pool);

    return db;
}
 
Example #22
Source File: JobDependencies.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Bean
public TaskExecutionInfoService taskDefinitionRetriever(AppRegistryService registry,
		TaskExplorer taskExplorer, TaskDefinitionRepository taskDefinitionRepository,
		TaskConfigurationProperties taskConfigurationProperties, LauncherRepository launcherRepository,
		List<TaskPlatform> taskPlatforms) {
	return new DefaultTaskExecutionInfoService(new DataSourceProperties(),
			registry, taskExplorer, taskDefinitionRepository,
			taskConfigurationProperties, launcherRepository, taskPlatforms);
}
 
Example #23
Source File: DataSourceConfiguration.java    From event-sourcing-microservices-example with GNU General Public License v3.0 5 votes vote down vote up
@Bean
@ConfigurationProperties("spring.datasource")
@LiquibaseDataSource
public DataSource dataSource(DataSourceProperties properties) {
	return new SimpleDriverDataSource(new org.postgresql.Driver(), properties.getUrl(),
			properties.getDataUsername(), properties.getDataPassword());
}
 
Example #24
Source File: UserDBConfig.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Primary
@Bean(name = "userDataSource")
@ConfigurationProperties("user.datasource.configuration")
public DataSource dataSource(@Qualifier("userDataSourceProperties") DataSourceProperties userDataSourceProperties) {
    return userDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class)
            .build();
}
 
Example #25
Source File: GcpCloudSqlAutoConfigurationMockTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoJdbc() {
	this.contextRunner.withPropertyValues(
			"spring.cloud.gcp.sql.instanceConnectionName=tubular-bells:singapore:test-instance")
			.withClassLoader(
					new FilteredClassLoader(EmbeddedDatabaseType.class, DataSource.class))
			.run((context) -> {
				assertThat(context.getBeanNamesForType(DataSource.class)).isEmpty();
				assertThat(context.getBeanNamesForType(DataSourceProperties.class)).isEmpty();
				assertThat(context.getBeanNamesForType(GcpCloudSqlProperties.class)).isEmpty();
				assertThat(context.getBeanNamesForType(CloudSqlJdbcInfoProvider.class)).isEmpty();
			});
}
 
Example #26
Source File: JdbcConfig.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public DataSource datasource(DataSourceProperties dataSourceProperties) {
    HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    dataSource.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2);

    return dataSource;
}
 
Example #27
Source File: DefaultSchedulerServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private SchedulerService getMockedKubernetesSchedulerService() {
	Launcher launcher = new Launcher("default", "Kubernetes", Mockito.mock(TaskLauncher.class), scheduler);
	List<Launcher> launchers = new ArrayList<>();
	launchers.add(launcher);
	List<TaskPlatform> taskPlatform = Collections.singletonList(new TaskPlatform("testTaskPlatform", launchers));

	return  new DefaultSchedulerService(this.commonApplicationProperties,
			taskPlatform, this.taskDefinitionRepository,
			this.appRegistry, this.resourceLoader,
			this.taskConfigurationProperties, mock(DataSourceProperties.class), null,
			this.metaDataResolver, this.schedulerServiceProperties, this.auditRecordService);
}
 
Example #28
Source File: _DatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 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 #29
Source File: App.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
@Profile({"jdbc", "jpa"})
public DataSource datasource(DataSourceProperties dataSourceProperties) {
    HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    dataSource.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2);

    return dataSource;
}
 
Example #30
Source File: DefaultSchedulerServiceTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private List<String> getCommandLineArguments(List<String> commandLineArguments) {
	Scheduler mockScheduler = mock(SimpleTestScheduler.class);
	TaskDefinitionRepository mockTaskDefinitionRepository = mock(TaskDefinitionRepository.class);
	AppRegistryService mockAppRegistryService = mock(AppRegistryService.class);

	Launcher launcher = new Launcher("default", "defaultType", null, mockScheduler);
	List<Launcher> launchers = new ArrayList<>();
	launchers.add(launcher);
	List<TaskPlatform> taskPlatform = Collections.singletonList(new TaskPlatform("testTaskPlatform", launchers));
	SchedulerService mockSchedulerService = new DefaultSchedulerService(mock(CommonApplicationProperties.class),
			taskPlatform, mockTaskDefinitionRepository, mockAppRegistryService, mock(ResourceLoader.class),
			this.taskConfigurationProperties, mock(DataSourceProperties.class), "uri",
			mock(ApplicationConfigurationMetadataResolver.class), mock(SchedulerServiceProperties.class),
			mock(AuditRecordService.class));

	TaskDefinition taskDefinition = new TaskDefinition(BASE_DEFINITION_NAME, "timestamp");

	when(mockTaskDefinitionRepository.findById(BASE_DEFINITION_NAME)).thenReturn(Optional.of(taskDefinition));
	when(mockAppRegistryService.getAppResource(any())).thenReturn(new DockerResource("springcloudtask/timestamp-task:latest"));
	when(mockAppRegistryService.find(taskDefinition.getRegisteredAppName(), ApplicationType.task))
			.thenReturn(new AppRegistration());
	mockSchedulerService.schedule(BASE_SCHEDULE_NAME, BASE_DEFINITION_NAME, this.testProperties,
			commandLineArguments, null);

	ArgumentCaptor<ScheduleRequest> scheduleRequestArgumentCaptor = ArgumentCaptor.forClass(ScheduleRequest.class);
	verify(mockScheduler).schedule(scheduleRequestArgumentCaptor.capture());

	return scheduleRequestArgumentCaptor.getValue().getCommandlineArguments();
}