org.springframework.jdbc.datasource.init.DatabasePopulatorUtils Java Examples
The following examples show how to use
org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.
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: DruidDataSourceInitializer.java From druid-spring-boot with Apache License 2.0 | 7 votes |
private void runScripts(DataSource dataSource, List<Resource> resources, String username, String password) { 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); } 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 #2
Source File: BankFactoryImpl.java From double-entry-bookkeeping-api with MIT License | 6 votes |
@Override public void configureDataSource(ConnectionOptions options) { try { DriverManagerDataSource dataSource = BankContextUtil.getBean("dataSource"); dataSource.setDriverClassName(options.driverClassName()); dataSource.setUrl(options.url()); dataSource.setUsername(options.username()); dataSource.setPassword(options.password()); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.setContinueOnError(true); databasePopulator.addScript(new ClassPathResource("db/" + options.schema())); DatabasePopulatorUtils.execute(databasePopulator, dataSource); } catch (Exception e) { throw new InfrastructureException(e); } }
Example #3
Source File: ScriptServiceImpl.java From multitenant with Apache License 2.0 | 6 votes |
private void runScripts(List<Resource> resources, DataSource dataSource, Map<String, Object> vars) { if (resources.isEmpty()) { return; } DynamicResourceDatabasePopulator populator = new DynamicResourceDatabasePopulator(); 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); } populator.setVars(vars); DatabasePopulatorUtils.execute(populator, dataSource); }
Example #4
Source File: EmbeddedDatabaseFactory.java From effectivejava with Apache License 2.0 | 6 votes |
/** * Hook to initialize the embedded database. Subclasses may call this method * to force initialization. * <p>After calling this method, {@link #getDataSource()} returns the * {@link DataSource} providing connectivity to the database. */ protected void initDatabase() { // Create the embedded database source first if (logger.isInfoEnabled()) { logger.info("Creating embedded database '" + this.databaseName + "'"); } if (this.databaseConfigurer == null) { this.databaseConfigurer = EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseType.HSQL); } this.databaseConfigurer.configureConnectionProperties( this.dataSourceFactory.getConnectionProperties(), this.databaseName); this.dataSource = this.dataSourceFactory.getDataSource(); // Now populate the database if (this.databasePopulator != null) { try { DatabasePopulatorUtils.execute(this.databasePopulator, this.dataSource); } catch (RuntimeException ex) { // failed to populate, so leave it as not initialized shutdownDatabase(); throw ex; } } }
Example #5
Source File: MultiDataSourceInitializer.java From teiid-spring-boot with Apache License 2.0 | 6 votes |
private void runScripts(List<Resource> resources, String username, String password) { if (resources.isEmpty()) { return; } boolean continueOnError = Boolean.parseBoolean(getProperty("continue-on-error")); ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.setContinueOnError(continueOnError); populator.setSeparator(getProperty("seperator")); if (getProperty("sql-script-encoding") != null) { populator.setSqlScriptEncoding(getProperty("sql-script-encoding")); } for (Resource resource : resources) { populator.addScript(resource); } DataSource dataSource = this.dataSource; if (StringUtils.hasText(username) && StringUtils.hasText(password)) { String driver = getProperty("driver-class-name"); String url = getProperty("url"); dataSource = DataSourceBuilder.create(this.getClass().getClassLoader()).driverClassName(driver).url(url) .username(username).password(password).build(); } DatabasePopulatorUtils.execute(populator, dataSource); }
Example #6
Source File: SchedulerDBInit.java From syncope with Apache License 2.0 | 6 votes |
@Override public void afterPropertiesSet() throws Exception { Assert.state(this.dataSource != null, "DataSource must be set"); Assert.state(this.databasePopulator != null, "DatabasePopulator must be set"); JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); boolean existingData; try { existingData = jdbcTemplate.queryForObject("SELECT COUNT(0) FROM QRTZ_SCHEDULER_STATE", Integer.class) > 0; } catch (BadSqlGrammarException e) { LOG.debug("Could not access to table QRTZ_SCHEDULER_STATE", e); existingData = false; } if (existingData) { LOG.info("Quartz tables found in the database, leaving untouched"); } else { LOG.info("No Quartz tables found, creating"); DatabasePopulatorUtils.execute(databasePopulator, this.dataSource); } }
Example #7
Source File: DaoEnvTestSpringModuleConfig.java From herd with Apache License 2.0 | 6 votes |
/** * Get a new herd data source based on an in-memory HSQLDB database. This data source is used for loading the configuration table as an environment property * source as well as for the JPA entity manager. It will therefore create/re-create the configuration table which is required for the former. It also * inserts required values for both scenarios. * * @return the test herd data source. */ @Bean public static DataSource herdDataSource() { // Create and return a data source that can connect directly to a JDBC URL. BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(org.h2.Driver.class.getName()); basicDataSource.setUsername(""); basicDataSource.setPassword(""); basicDataSource.setUrl("jdbc:h2:mem:herdTestDb"); // Create and populate the configuration table. // This is needed for all data source method calls since it is used to create the environment property source which happens before // JPA and other non-static beans are initialized. ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator(); resourceDatabasePopulator.addScript(new ClassPathResource("createConfigurationTableAndData.sql")); DatabasePopulatorUtils.execute(resourceDatabasePopulator, basicDataSource); // This is what the DataSourceInitializer does. return basicDataSource; }
Example #8
Source File: HsqlDatabaseBuilder.java From c2mon with GNU Lesser General Public License v3.0 | 6 votes |
public DataSource toDataSource() { DataSource dataSource; if (url == null || url.contains("hsqldb:mem")) { log.debug("Creating in memory HSQL database"); // Start an in-process, in-memory HSQL server dataSource = new EmbeddedDatabaseBuilder().setType(HSQL).setName("c2mondb").build(); } else { log.debug("Creating HSQL database at URL {}",url); dataSource = DataSourceBuilder.create().url(url).username(username).password(password).build(); } if (!scripts.isEmpty()) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(scripts.toArray(new Resource[scripts.size()])); populator.setContinueOnError(true); DatabasePopulatorUtils.execute(populator, dataSource); } return dataSource; }
Example #9
Source File: TeiidTestDataSources.java From monolith with Apache License 2.0 | 5 votes |
@Bean public DataSource ordersDS() { DataSource dataSource = DataSourceBuilder.create().driverClassName("org.h2.Driver").username("sa").password("").url("jdbc:h2:mem:ordersdb;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=FALSE;MODE=MYSQL").build(); Resource initSchema = new ClassPathResource("h2/scripts/ordersdb-schema.sql"); Resource initData = new ClassPathResource("h2/scripts/ordersdb-data.sql"); DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData); DatabasePopulatorUtils.execute(databasePopulator, dataSource); return dataSource; }
Example #10
Source File: TeiidTestDataSources.java From monolith with Apache License 2.0 | 5 votes |
@Bean public DataSource legacyDS() { DataSource dataSource = DataSourceBuilder.create().driverClassName("org.h2.Driver").username("sa").password("").url("jdbc:h2:mem:legacydb;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=FALSE;MODE=MYSQL").build(); Resource initSchema = new ClassPathResource("h2/scripts/legacydb-schema.sql"); Resource initData = new ClassPathResource("h2/scripts/legacydb-data.sql"); DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData); DatabasePopulatorUtils.execute(databasePopulator, dataSource); return dataSource; }
Example #11
Source File: EmbeddedDatabaseFactoryBean.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void destroy() { if (this.databaseCleaner != null) { DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource()); } shutdownDatabase(); }
Example #12
Source File: EmbeddedDatabaseFactory.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Hook to initialize the embedded database. * <p>If the {@code generateUniqueDatabaseName} flag has been set to {@code true}, * the current value of the {@linkplain #setDatabaseName database name} will * be overridden with an auto-generated name. * <p>Subclasses may call this method to force initialization; however, * this method should only be invoked once. * <p>After calling this method, {@link #getDataSource()} returns the * {@link DataSource} providing connectivity to the database. */ protected void initDatabase() { if (this.generateUniqueDatabaseName) { setDatabaseName(UUID.randomUUID().toString()); } // Create the embedded database first if (this.databaseConfigurer == null) { this.databaseConfigurer = EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseType.HSQL); } this.databaseConfigurer.configureConnectionProperties( this.dataSourceFactory.getConnectionProperties(), this.databaseName); this.dataSource = this.dataSourceFactory.getDataSource(); if (logger.isInfoEnabled()) { if (this.dataSource instanceof SimpleDriverDataSource) { SimpleDriverDataSource simpleDriverDataSource = (SimpleDriverDataSource) this.dataSource; logger.info(String.format("Starting embedded database: url='%s', username='%s'", simpleDriverDataSource.getUrl(), simpleDriverDataSource.getUsername())); } else { logger.info(String.format("Starting embedded database '%s'", this.databaseName)); } } // Now populate the database if (this.databasePopulator != null) { try { DatabasePopulatorUtils.execute(this.databasePopulator, this.dataSource); } catch (RuntimeException ex) { // failed to populate, so leave it as not initialized shutdownDatabase(); throw ex; } } }
Example #13
Source File: ConfigurationDatabasePopulationRule.java From c2mon with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void before() { ResourceDatabasePopulator populator = new ResourceDatabasePopulator( new ClassPathResource("sql/config-test-data.sql") ); DatabasePopulatorUtils.execute(populator, configurationDataSource); }
Example #14
Source File: DatabasePopulationRule.java From c2mon with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void before() throws SQLException { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(new ClassPathResource("sql/cache-data-remove.sql")); conn = cacheDataSource.getConnection(); if (conn.getMetaData().getURL().contains("mysql")) { populator.addScript(new ClassPathResource("sql/cache-data-update-sequence.sql")); } else { populator.addScript(new ClassPathResource("sql/cache-data-alter-sequence.sql")); } populator.addScript(new ClassPathResource("sql/cache-data-insert.sql")); DatabasePopulatorUtils.execute(populator, cacheDataSource); }
Example #15
Source File: TaskRepositoryInitializer.java From spring-cloud-task with Apache License 2.0 | 5 votes |
@Override public void afterPropertiesSet() throws Exception { boolean isInitializeEnabled = (this.taskProperties.isInitializeEnabled() != null) ? this.taskProperties.isInitializeEnabled() : this.taskInitializationEnabled; if (this.dataSource != null && isInitializeEnabled && this.taskProperties .getTablePrefix().equals(TaskProperties.DEFAULT_TABLE_PREFIX)) { String platform = getDatabaseType(this.dataSource); if ("hsql".equals(platform)) { platform = "hsqldb"; } if ("postgres".equals(platform)) { platform = "postgresql"; } if ("oracle".equals(platform)) { platform = "oracle10g"; } if ("mysql".equals(platform)) { platform = "mysql"; } if ("sqlserver".equals(platform)) { platform = "sqlserver"; } ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); String schemaLocation = schema; schemaLocation = schemaLocation.replace("@@platform@@", platform); populator.addScript(this.resourceLoader.getResource(schemaLocation)); populator.setContinueOnError(true); logger.debug( String.format("Initializing task schema for %s database", platform)); DatabasePopulatorUtils.execute(populator, this.dataSource); } }
Example #16
Source File: MemberDataSourceConfig.java From EasyReport with Apache License 2.0 | 5 votes |
@Primary @Bean(name = "memberDataSource") public DataSource dataSource() { DruidDataSource dsh = firstDataSourceProperties().initializeDataSourceBuilder().type (DruidDataSource.class).build(); dsh.setValidationQuery("select 1"); Resource initSchema = new ClassPathResource("schema.sql"); Resource initData = new ClassPathResource("data.sql"); DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData); DatabasePopulatorUtils.execute(databasePopulator, dsh); return dsh; }
Example #17
Source File: AbstractBatchIntegrationTest.java From batchers with Apache License 2.0 | 5 votes |
@After public void clearJobTables() throws SQLException { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.setScripts( new ClassPathResource("org/springframework/batch/core/schema-truncate-hsqldb.sql") ); DatabasePopulatorUtils.execute(databasePopulator, this.dataSource); }
Example #18
Source File: EmbeddedDatabaseFactoryBean.java From effectivejava with Apache License 2.0 | 5 votes |
@Override public void destroy() { if (this.databaseCleaner != null) { DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource()); } shutdownDatabase(); }
Example #19
Source File: DataSourceInitializer.java From camel-cookbook-examples with Apache License 2.0 | 5 votes |
public static DataSource initializeDataSource(DataSource dataSource, Resource script) { // here we use the same classes that Spring does under the covers to run the schema into the database ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(script); DatabasePopulatorUtils.execute(populator, dataSource); return dataSource; }
Example #20
Source File: JobConfig.java From spring4-sandbox with Apache License 2.0 | 5 votes |
@PostConstruct public void initialize(){ ResourceDatabasePopulator populator=new ResourceDatabasePopulator(); populator.setContinueOnError(true); populator.addScript(resourceLoader.getResource("classpath:/org/springframework/batch/core/schema-h2.sql")); DatabasePopulatorUtils.execute(populator, dataSource); }
Example #21
Source File: JobConfig.java From spring4-sandbox with Apache License 2.0 | 5 votes |
@PostConstruct public void initialize() { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.setContinueOnError(true); populator.addScript(resourceLoader.getResource("classpath:/org/springframework/batch/core/schema-h2.sql")); DatabasePopulatorUtils.execute(populator, dataSource); }
Example #22
Source File: DataflowRdbmsInitializer.java From spring-cloud-dashboard with Apache License 2.0 | 5 votes |
@Override public void afterPropertiesSet() throws Exception { if (dataSource != null && definitionInitializationEnable) { String platform = getDatabaseType(dataSource); if ("hsql".equals(platform)) { platform = "hsqldb"; } if ("postgres".equals(platform)) { platform = "postgresql"; } if ("oracle".equals(platform)) { platform = "oracle10g"; } ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); String schemaLocation = schema; schemaLocation = schemaLocation.replace("@@platform@@", platform); String commonSchemaLocation = schemaLocation; commonSchemaLocation = commonSchemaLocation.replace("@@suffix@@", COMMON_SCHEMA_SUFFIX); logger.info(String.format("Adding dataflow schema %s for %s database", commonSchemaLocation, platform)); populator.addScript(resourceLoader.getResource(commonSchemaLocation)); String applicationssSchemaLocation = schemaLocation; applicationssSchemaLocation = applicationssSchemaLocation.replace("@@suffix@@", APPLICATIONS_SCHEMA_SUFFIX); logger.info(String.format("Adding dataflow schema %s for %s database", applicationssSchemaLocation, platform)); populator.addScript(resourceLoader.getResource(applicationssSchemaLocation)); String deploymentSchemaLocation = schemaLocation; deploymentSchemaLocation = deploymentSchemaLocation.replace("@@suffix@@", DEPLOYMENT_SCHEMA_SUFFIX); logger.info(String.format("Adding dataflow schema %s for %s database", deploymentSchemaLocation, platform)); populator.addScript(resourceLoader.getResource(deploymentSchemaLocation)); populator.setContinueOnError(true); logger.debug(String.format("Initializing dataflow schema for %s database", platform)); DatabasePopulatorUtils.execute(populator, dataSource); } }
Example #23
Source File: EmbeddedDatabaseFactory.java From spring-analysis-note with MIT License | 5 votes |
/** * Hook to initialize the embedded database. * <p>If the {@code generateUniqueDatabaseName} flag has been set to {@code true}, * the current value of the {@linkplain #setDatabaseName database name} will * be overridden with an auto-generated name. * <p>Subclasses may call this method to force initialization; however, * this method should only be invoked once. * <p>After calling this method, {@link #getDataSource()} returns the * {@link DataSource} providing connectivity to the database. */ protected void initDatabase() { if (this.generateUniqueDatabaseName) { setDatabaseName(UUID.randomUUID().toString()); } // Create the embedded database first if (this.databaseConfigurer == null) { this.databaseConfigurer = EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseType.HSQL); } this.databaseConfigurer.configureConnectionProperties( this.dataSourceFactory.getConnectionProperties(), this.databaseName); this.dataSource = this.dataSourceFactory.getDataSource(); if (logger.isInfoEnabled()) { if (this.dataSource instanceof SimpleDriverDataSource) { SimpleDriverDataSource simpleDriverDataSource = (SimpleDriverDataSource) this.dataSource; logger.info(String.format("Starting embedded database: url='%s', username='%s'", simpleDriverDataSource.getUrl(), simpleDriverDataSource.getUsername())); } else { logger.info(String.format("Starting embedded database '%s'", this.databaseName)); } } // Now populate the database if (this.databasePopulator != null) { try { DatabasePopulatorUtils.execute(this.databasePopulator, this.dataSource); } catch (RuntimeException ex) { // failed to populate, so leave it as not initialized shutdownDatabase(); throw ex; } } }
Example #24
Source File: EmbeddedDatabaseFactoryBean.java From java-technology-stack with MIT License | 5 votes |
@Override public void destroy() { if (this.databaseCleaner != null && getDataSource() != null) { DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource()); } shutdownDatabase(); }
Example #25
Source File: EmbeddedDatabaseFactory.java From java-technology-stack with MIT License | 5 votes |
/** * Hook to initialize the embedded database. * <p>If the {@code generateUniqueDatabaseName} flag has been set to {@code true}, * the current value of the {@linkplain #setDatabaseName database name} will * be overridden with an auto-generated name. * <p>Subclasses may call this method to force initialization; however, * this method should only be invoked once. * <p>After calling this method, {@link #getDataSource()} returns the * {@link DataSource} providing connectivity to the database. */ protected void initDatabase() { if (this.generateUniqueDatabaseName) { setDatabaseName(UUID.randomUUID().toString()); } // Create the embedded database first if (this.databaseConfigurer == null) { this.databaseConfigurer = EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseType.HSQL); } this.databaseConfigurer.configureConnectionProperties( this.dataSourceFactory.getConnectionProperties(), this.databaseName); this.dataSource = this.dataSourceFactory.getDataSource(); if (logger.isInfoEnabled()) { if (this.dataSource instanceof SimpleDriverDataSource) { SimpleDriverDataSource simpleDriverDataSource = (SimpleDriverDataSource) this.dataSource; logger.info(String.format("Starting embedded database: url='%s', username='%s'", simpleDriverDataSource.getUrl(), simpleDriverDataSource.getUsername())); } else { logger.info(String.format("Starting embedded database '%s'", this.databaseName)); } } // Now populate the database if (this.databasePopulator != null) { try { DatabasePopulatorUtils.execute(this.databasePopulator, this.dataSource); } catch (RuntimeException ex) { // failed to populate, so leave it as not initialized shutdownDatabase(); throw ex; } } }
Example #26
Source File: BookPubApplicationTests.java From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License | 5 votes |
@Before public void loadDataFixtures() { if (loadDataFixtures) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql")); DatabasePopulatorUtils.execute(populator, ds); loadDataFixtures = false; } }
Example #27
Source File: BookPubApplicationTests.java From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License | 5 votes |
@Before public void loadDataFixtures() { if (loadDataFixtures) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql")); DatabasePopulatorUtils.execute(populator, ds); loadDataFixtures = false; } }
Example #28
Source File: BookPubApplicationTests.java From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License | 5 votes |
@Before public void loadDataFixtures() { if (loadDataFixtures) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql")); DatabasePopulatorUtils.execute(populator, ds); loadDataFixtures = false; } }
Example #29
Source File: BookPubApplicationTests.java From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License | 5 votes |
@Before public void loadDataFixtures() { if (loadDataFixtures) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql")); DatabasePopulatorUtils.execute(populator, ds); loadDataFixtures = false; } }
Example #30
Source File: BookPubApplicationTests.java From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License | 5 votes |
@Before public void loadDataFixtures() { if (loadDataFixtures) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql")); DatabasePopulatorUtils.execute(populator, ds); loadDataFixtures = false; } }