Java Code Examples for org.springframework.jdbc.datasource.init.DatabasePopulatorUtils

The following are top voted examples for showing how to use org.springframework.jdbc.datasource.init.DatabasePopulatorUtils. 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: spring-boot-concourse   File: BatchDatabaseInitializer.java   Source Code and License 7 votes vote down vote up
@PostConstruct
protected void initialize() {
	if (this.properties.getInitializer().isEnabled()) {
		String platform = getDatabaseType();
		if ("hsql".equals(platform)) {
			platform = "hsqldb";
		}
		if ("postgres".equals(platform)) {
			platform = "postgresql";
		}
		if ("oracle".equals(platform)) {
			platform = "oracle10g";
		}
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		String schemaLocation = this.properties.getSchema();
		schemaLocation = schemaLocation.replace("@@[email protected]@", platform);
		populator.addScript(this.resourceLoader.getResource(schemaLocation));
		populator.setContinueOnError(true);
		DatabasePopulatorUtils.execute(populator, this.dataSource);
	}
}
 
Example 2
Project: herd   File: DaoEnvTestSpringModuleConfig.java   Source Code and License 7 votes vote down vote up
/**
 * 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 3
Project: lams   File: EmbeddedDatabaseFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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 4
Project: spring-boot-multidatasource   File: DataSourceInitializer.java   Source Code and License 6 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
	if (resources.isEmpty()) {
		return;
	}
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setContinueOnError(this.properties.isContinueOnError());
	populator.setSeparator(this.properties.getSeparator());
	if (this.properties.getSqlScriptEncoding() != null) {
		populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
	}
	for (Resource resource : resources) {
		populator.addScript(resource);
	}
	DataSource dataSource = this.dataSource;
	if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
		dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
				.driverClassName(this.properties.determineDriverClassName())
				.url(this.properties.determineUrl()).username(username)
				.password(password).build();
	}
	DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 5
Project: holon-jdbc   File: DataContextDataSourceInitializer.java   Source Code and License 6 votes vote down vote up
private void runScripts(List<Resource> resources, DataSource dataSource) {
	if (resources.isEmpty()) {
		return;
	}
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setContinueOnError(configuration.isContinueOnError());
	populator.setSeparator(configuration.getConfigPropertyValue(SpringDataSourceConfigProperties.SEPARATOR, ";"));
	String encoding = configuration.getConfigPropertyValue(SpringDataSourceConfigProperties.SQL_SCRIPT_ENCODING,
			null);
	if (encoding != null) {
		populator.setSqlScriptEncoding(encoding);
	}
	for (Resource resource : resources) {
		populator.addScript(resource);
	}
	DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 6
Project: leopard   File: DomainWhiteListConfigImpl.java   Source Code and License 6 votes vote down vote up
protected void createTable() {
	StringBuilder sb = new StringBuilder();
	sb.append("CREATE TABLE  if not exists `leopard_domainwhitelist` (");
	sb.append("`domain` varchar(50) NOT NULL DEFAULT '',");
	sb.append("`username` varchar(50) NOT NULL DEFAULT '',");
	sb.append("`posttime` datetime NOT NULL DEFAULT '1970-01-01 00:00:00',");
	sb.append("`comment` varchar(255) NOT NULL DEFAULT '',");
	sb.append("PRIMARY KEY (`domain`)");
	sb.append(");");
	String sql = sb.toString();

	Resource scripts = new ByteArrayResource(sql.getBytes());
	DatabasePopulator populator = new ResourceDatabasePopulator(scripts);
	try {
		DatabasePopulatorUtils.execute(populator, jdbcTemplate.getDataSource());
	}
	catch (ScriptStatementFailedException e) {

	}
}
 
Example 7
Project: c2mon   File: RuleCachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 8
Project: c2mon   File: ConfigurationCachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 9
Project: c2mon   File: ClientCachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 10
Project: c2mon   File: DaqCachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 11
Project: c2mon   File: CachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 12
Project: c2mon   File: HsqlDatabaseBuilder.java   Source Code and License 6 votes vote down vote up
public DataSource build() {
  DataSource dataSource;

  if (url == null || url.contains("hsqldb:mem")) {
    // Start an in-process, in-memory HSQL server
    dataSource = new EmbeddedDatabaseBuilder().setType(HSQL).setName("c2mondb").build();
  } else if (url.contains("hsql://")) {
    // Start an externally visible, file-based HSQL server
    HsqlServer.start("file:///tmp/c2mondb", "c2mondb");
    url += ";sql.syntax_ora=true;hsqldb.default_table_type=cached;hsqldb.cache_rows=1000;hsqldb.result_max_memory_rows=2000;hsqldb.cache_size=100";
    dataSource = DataSourceBuilder.create().url(url).username(username).password(password).build();

  } else {
    throw new RuntimeException("The given URL was not a valid HSQL JDBC URL!");
  }

  if (!scripts.isEmpty()) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(scripts.toArray(new Resource[scripts.size()]));
    populator.setContinueOnError(true);
    DatabasePopulatorUtils.execute(populator, dataSource);
  }

  return dataSource;
}
 
Example 13
Project: c2mon   File: CachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 14
Project: c2mon   File: SupervisionCachePopulationRule.java   Source Code and License 6 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);

  CacheManager.getInstance().clearAll();
  controlTagCache.init();
  processCache.init();
  dataTagCache.init();
  equipmentCache.init();
  aliveTimerCache.init();
  commFaultTagCache.init();
  subEquipmentCache.init();
  alarmCache.init();
  ruleTagCache.init();
  commandTagCache.init();
  deviceClassCache.init();
  deviceCache.init();
}
 
Example 15
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceInitializer.java   Source Code and License 6 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
	if (resources.isEmpty()) {
		return;
	}
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setContinueOnError(this.properties.isContinueOnError());
	populator.setSeparator(this.properties.getSeparator());
	if (this.properties.getSqlScriptEncoding() != null) {
		populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
	}
	for (Resource resource : resources) {
		populator.addScript(resource);
	}
	DataSource dataSource = this.dataSource;
	if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
		dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
				.driverClassName(this.properties.determineDriverClassName())
				.url(this.properties.determineUrl()).username(username)
				.password(password).build();
	}
	DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 16
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: BatchDatabaseInitializer.java   Source Code and License 6 votes vote down vote up
@PostConstruct
protected void initialize() {
	if (this.properties.getInitializer().isEnabled()) {
		String platform = getDatabaseType();
		if ("hsql".equals(platform)) {
			platform = "hsqldb";
		}
		if ("postgres".equals(platform)) {
			platform = "postgresql";
		}
		if ("oracle".equals(platform)) {
			platform = "oracle10g";
		}
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		String schemaLocation = this.properties.getSchema();
		schemaLocation = schemaLocation.replace("@@[email protected]@", platform);
		populator.addScript(this.resourceLoader.getResource(schemaLocation));
		populator.setContinueOnError(true);
		DatabasePopulatorUtils.execute(populator, this.dataSource);
	}
}
 
Example 17
Project: spring-boot-concourse   File: DataSourceInitializer.java   Source Code and License 6 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
	if (resources.isEmpty()) {
		return;
	}
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setContinueOnError(this.properties.isContinueOnError());
	populator.setSeparator(this.properties.getSeparator());
	if (this.properties.getSqlScriptEncoding() != null) {
		populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
	}
	for (Resource resource : resources) {
		populator.addScript(resource);
	}
	DataSource dataSource = this.dataSource;
	if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
		dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
				.driverClassName(this.properties.determineDriverClassName())
				.url(this.properties.determineUrl()).username(username)
				.password(password).build();
	}
	DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 18
Project: contestparser   File: BatchDatabaseInitializer.java   Source Code and License 6 votes vote down vote up
@PostConstruct
protected void initialize() {
	if (this.properties.getInitializer().isEnabled()) {
		String platform = getDatabaseType();
		if ("hsql".equals(platform)) {
			platform = "hsqldb";
		}
		if ("postgres".equals(platform)) {
			platform = "postgresql";
		}
		if ("oracle".equals(platform)) {
			platform = "oracle10g";
		}
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		String schemaLocation = this.properties.getSchema();
		schemaLocation = schemaLocation.replace("@@[email protected]@", platform);
		populator.addScript(this.resourceLoader.getResource(schemaLocation));
		populator.setContinueOnError(true);
		DatabasePopulatorUtils.execute(populator, this.dataSource);
	}
}
 
Example 19
Project: class-guard   File: EmbeddedDatabaseFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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 20
Project: spring-batch-experiments   File: JtaConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean(initMethod = "init", destroyMethod = "close")
public PoolingDataSource batchMetaDataDataSource() {
	PoolingDataSource ds = new PoolingDataSource();

	ds.setClassName(org.hsqldb.jdbc.pool.JDBCXADataSource.class.getName());
	ds.setUniqueName("batchdb");
	ds.setMaxPoolSize(100);

	Properties props = new Properties();
	props.setProperty("databaseName", "spring-batch-metadata");
	// props.setProperty("createDatabase", "create");
	ds.setDriverProperties(props);

	ds.setAllowLocalTransactions(true);

	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.addScript(batchDropSchemaScript);
	populator.addScript(batchCreateSchemaScript);
	DatabasePopulatorUtils.execute(populator, ds);

	return ds;
}
 
Example 21
Project: spring-batch-experiments   File: JtaConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean(initMethod = "init", destroyMethod = "close")
public PoolingDataSource applicationDataSource() {
	PoolingDataSource ds = new PoolingDataSource();

	ds.setClassName(org.hsqldb.jdbc.pool.JDBCXADataSource.class.getName());
	ds.setUniqueName("appdb");
	ds.setMaxPoolSize(100);

	final Properties props = new Properties();
	props.setProperty("databaseName", "chapter09-application");
	// props.setProperty("createDatabase", "create");
	ds.setDriverProperties(props);

	ds.setAllowLocalTransactions(true);

	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.addScript(dropTablesScript);
	populator.addScript(createTableScript);
	DatabasePopulatorUtils.execute(populator, ds);

	return ds;
}
 
Example 22
Project: druid-spring-boot   File: DruidDataSourceInitializer.java   Source Code and License 5 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
    if (resources.isEmpty()) {
        return;
    }
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(this.properties.isContinueOnError());
    populator.setSeparator(this.properties.getSeparator());
    if (this.properties.getSqlScriptEncoding() != null) {
        populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
    }
    for (Resource resource : resources) {
        populator.addScript(resource);
    }
    DataSource dataSource = this.dataSource;
    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
                .driverClassName(this.properties.determineDriverClassName())
                .url(this.properties.determineUrl()).username(username)
                .password(password).build();
    }
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 23
Project: lams   File: EmbeddedDatabaseFactoryBean.java   Source Code and License 5 votes vote down vote up
@Override
public void destroy() {
	if (this.databaseCleaner != null) {
		DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource());
	}
	shutdownDatabase();
}
 
Example 24
Project: spring-cloud-dashboard   File: DataflowRdbmsInitializer.java   Source Code and License 5 votes vote down vote up
@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("@@[email protected]@", platform);
		String commonSchemaLocation = schemaLocation;
		commonSchemaLocation = commonSchemaLocation.replace("@@[email protected]@", 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("@@[email protected]@", 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("@@[email protected]@", 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 25
Project: spring4-understanding   File: EmbeddedDatabaseFactoryBean.java   Source Code and License 5 votes vote down vote up
@Override
public void destroy() {
	if (this.databaseCleaner != null) {
		DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource());
	}
	shutdownDatabase();
}
 
Example 26
Project: spring4-understanding   File: EmbeddedDatabaseFactory.java   Source Code and License 5 votes vote down vote up
/**
 * 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 27
Project: spring_boot   File: PersistenceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url + hostName + portNumber + databaseName + extraPram);
    dataSource.setUsername(userName);
    dataSource.setPassword(userPwd);
    DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
    return dataSource;
}
 
Example 28
Project: spring_boot   File: PersistenceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url + hostName + portNumber + databaseName + extraPram);
    dataSource.setUsername(userName);
    dataSource.setPassword(userPwd);
    DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
    return dataSource;
}
 
Example 29
Project: spring_boot   File: PersistenceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url + hostName + portNumber + databaseName + extraPram);
    dataSource.setUsername(userName);
    dataSource.setPassword(userPwd);
    DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
    return dataSource;
}
 
Example 30
Project: c2mon   File: ConfigurationDatabasePopulationRule.java   Source Code and License 5 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/config-test-data.sql")
  );
  DatabasePopulatorUtils.execute(populator, configurationDataSource);
}
 
Example 31
Project: c2mon   File: DatabasePopulationRule.java   Source Code and License 5 votes vote down vote up
@Override
protected void before() {
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
      new ClassPathResource("sql/cache-data-remove.sql"),
      new ClassPathResource("sql/cache-data-insert.sql")
  );
  DatabasePopulatorUtils.execute(populator, cacheDataSource);
}
 
Example 32
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: JdbcSessionDatabaseInitializer.java   Source Code and License 5 votes vote down vote up
@PostConstruct
protected void initialize() {
	if (this.properties.getJdbc().getInitializer().isEnabled()) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		String schemaLocation = this.properties.getJdbc().getSchema();
		schemaLocation = schemaLocation.replace("@@[email protected]@", getPlatform());
		populator.addScript(this.resourceLoader.getResource(schemaLocation));
		populator.setContinueOnError(true);
		DatabasePopulatorUtils.execute(populator, this.dataSource);
	}
}
 
Example 33
Project: music-for-all-application   File: UsersConnectionRepositoryTable.java   Source Code and License 5 votes vote down vote up
private static void create() {
    final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
    databasePopulator.addScript(new ClassPathResource("JdbcUsersConnectionRepository.sql",
            JdbcUsersConnectionRepository.class));
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);
    LOG.info("Table UserConnection successfully created");
}
 
Example 34
Project: spring-data-repositories   File: PersistenceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public InitializingBean dataPopulator(final DataSource dataSource) {
	return () -> {
		final DatabasePopulator populator = new ResourceDatabasePopulator(new ClassPathResource("data.sql"));
		DatabasePopulatorUtils.execute(populator, dataSource);
	};
}
 
Example 35
Project: contestparser   File: DataSourceInitializer.java   Source Code and License 5 votes vote down vote up
private void runScripts(List<Resource> resources) {
	if (resources.isEmpty()) {
		return;
	}
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setContinueOnError(this.properties.isContinueOnError());
	populator.setSeparator(this.properties.getSeparator());
	if (this.properties.getSqlScriptEncoding() != null) {
		populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
	}
	for (Resource resource : resources) {
		populator.addScript(resource);
	}
	DatabasePopulatorUtils.execute(populator, this.dataSource);
}
 
Example 36
Project: DependencyInjectionAgent   File: InitDataSourceConfig.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() {
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.addScript(new ClassPathResource(env.getProperty("jdbc.initLocation")));
	databasePopulator.addScript(new ClassPathResource(env.getProperty("jdbc.dataLocation")));
	DatabasePopulatorUtils.execute(databasePopulator, dataSource);
}
 
Example 37
Project: spring-cloud-task   File: TaskRepositoryInitializer.java   Source Code and License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if (dataSource != null &&
			taskInitializationEnable &&
			!StringUtils.hasText(this.tablePrefix)) {
		String platform = getDatabaseType(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("@@[email protected]@", platform);
		populator.addScript(resourceLoader.getResource(schemaLocation));
		populator.setContinueOnError(true);
		logger.debug(String.format("Initializing task schema for %s database",
				platform));
		DatabasePopulatorUtils.execute(populator, dataSource);
	}
}
 
Example 38
Project: spring-data-repositories   File: PersistenceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public InitializingBean dataPopulator(final DataSource dataSource) {
	return () -> {
		final DatabasePopulator populator = new ResourceDatabasePopulator(new ClassPathResource("data.sql"));
		DatabasePopulatorUtils.execute(populator, dataSource);
	};
}
 
Example 39
Project: spring-social-base   File: JdbcUsersConnectionRepositoryTableCreator.java   Source Code and License 5 votes vote down vote up
public void createTableIfNotExist() {
	JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	try {
		jdbcTemplate.queryForList("select count(*) from UserConnection");
	} catch (Exception e) {
		LOG.debug("Create table UserConnection");
		try {
			ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
			rdp.addScript(new ClassPathResource("/org/springframework/social/connect/jdbc/JdbcUsersConnectionRepository.sql"));
			DatabasePopulatorUtils.execute(rdp, dataSource);
		} catch (Exception e1) {
			LOG.error("Error create table UserConnection", e1);
		}
	}
}
 
Example 40
Project: batchers   File: AbstractBatchIntegrationTest.java   Source Code and License 5 votes vote down vote up
@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 41
Project: sqltemplate   File: TestConfig.java   Source Code and License 5 votes vote down vote up
DataSource dataSourceMySQL() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/test");
    dataSource.setUsername("test");
    dataSource.setPassword("test");

    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("schema.sql"));
    populator.addScript(new ClassPathResource("data.sql"));

    DatabasePopulatorUtils.execute(populator, dataSource);

    return dataSource;
}
 
Example 42
Project: camel-cookbook-examples   File: DataSourceInitializer.java   Source Code and License 5 votes vote down vote up
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 43
Project: spring4-sandbox   File: JobConfig.java   Source Code and License 5 votes vote down vote up
@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 44
Project: spring4-sandbox   File: JobConfig.java   Source Code and License 5 votes vote down vote up
@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 45
Project: whois   File: JdbcRpslObjectOperations.java   Source Code and License 5 votes vote down vote up
public static void loadScripts(final JdbcTemplate jdbcTemplate, final String... initSql) {
    sanityCheck(jdbcTemplate);

    final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
    final ResourceLoader resourceLoader = new DefaultResourceLoader();

    for (final String sql : initSql) {
        databasePopulator.addScript(resourceLoader.getResource(sql));
    }

    DatabasePopulatorUtils.execute(databasePopulator, jdbcTemplate.getDataSource());
}
 
Example 46
Project: spring-jdbc-oracle   File: DatabaseConfiguration.java   Source Code and License 5 votes vote down vote up
private void prepareDatabase() {
  final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
  populator.addScript(new ClassPathResource("prepare-database.sql"));
  populator.setIgnoreFailedDrops(true);

  TransactionTemplate trxTemplate = new TransactionTemplate(transactionManager());
  trxTemplate.execute(new TransactionCallback<Void>() {

    @Override
    public Void doInTransaction(TransactionStatus status) {
      DatabasePopulatorUtils.execute(populator, DatabaseConfiguration.this.dataSource);
      return null;
    }
  });
}
 
Example 47
Project: Spring-Security-Third-Edition   File: SocialDatabasePopulator.java   Source Code and License 4 votes vote down vote up
private void executeSql(final Resource resource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.addScript(resource);
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 48
Project: Spring-Security-Third-Edition   File: SocialDatabasePopulator.java   Source Code and License 4 votes vote down vote up
private void runScript(final Resource resource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.addScript(resource);
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 49
Project: Spring-Security-Third-Edition   File: SocialDatabasePopulator.java   Source Code and License 4 votes vote down vote up
private void runScript(final Resource resource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.addScript(resource);
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 50
Project: osoon   File: DbInitializer.java   Source Code and License 4 votes vote down vote up
private void runScript(Resource resource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.addScript(resource);
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 51
Project: dawn-marketplace-server   File: DatabaseConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean(name = "dataSource")
public DataSource getDataSource() {
	DataSource dataSource = createDataSource();
	DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
	return dataSource;
}
 
Example 52
Project: lemonaid   File: DatabaseInitializer.java   Source Code and License 4 votes vote down vote up
private void runScript(Resource resource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.addScript(resource);
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example 53
Project: spring-cloud-dataflow   File: DataflowRdbmsInitializer.java   Source Code and License 4 votes vote down vote up
@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("@@[email protected]@", platform);
		String commonSchemaLocation = schemaLocation;
		commonSchemaLocation = commonSchemaLocation.replace("@@[email protected]@", COMMON_SCHEMA_SUFFIX);
		logger.info(String.format("Adding dataflow schema %s for %s database", commonSchemaLocation, platform));
		populator.addScript(resourceLoader.getResource(commonSchemaLocation));
		if (featuresProperties.isStreamsEnabled()) {
			String streamsSchemaLocation = schemaLocation;
			streamsSchemaLocation = streamsSchemaLocation.replace("@@[email protected]@", STREAMS_SCHEMA_SUFFIX);
			logger.info(
					String.format("Adding dataflow schema %s for %s database", streamsSchemaLocation, platform));
			populator.addScript(resourceLoader.getResource(streamsSchemaLocation));
		}
		if (featuresProperties.isTasksEnabled()) {
			String tasksSchemaLocation = schemaLocation;
			tasksSchemaLocation = tasksSchemaLocation.replace("@@[email protected]@", TASKS_SCHEMA_SUFFIX);
			logger.info(String.format("Adding dataflow schema %s for %s database", tasksSchemaLocation, platform));
			populator.addScript(resourceLoader.getResource(tasksSchemaLocation));
		}
		if (featuresProperties.isStreamsEnabled() || featuresProperties.isTasksEnabled()) {
			String deploymentSchemaLocation = schemaLocation;
			deploymentSchemaLocation = deploymentSchemaLocation.replace("@@[email protected]@", 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 54
Project: class-guard   File: EmbeddedDatabaseFactoryBean.java   Source Code and License 4 votes vote down vote up
public void destroy() {
	if (this.databaseCleaner != null) {
		DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource());
	}
	shutdownDatabase();
}
 
Example 55
Project: maven-archetype-eventsourcing   File: DataSourceInitializer.java   Source Code and License 4 votes vote down vote up
@Bean(name = "dataSource")
public DataSource getDataSource() {
    DataSource dataSource = createDataSource();
    DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
    return dataSource;
}
 
Example 56
Project: maven-archetype-eventsourcing   File: DataSourceInitializer.java   Source Code and License 4 votes vote down vote up
@Bean(name = "dataSource")
public DataSource getDataSource() {
    DataSource dataSource = createDataSource();
    DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
    return dataSource;
}