Java Code Examples for org.springframework.jdbc.datasource.init.DatabasePopulatorUtils#execute()

The following examples show how to use org.springframework.jdbc.datasource.init.DatabasePopulatorUtils#execute() . 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 vote down vote up
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: ScriptServiceImpl.java    From multitenant with Apache License 2.0 6 votes vote down vote up
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 3
Source File: MultiDataSourceInitializer.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
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 4
Source File: SchedulerDBInit.java    From syncope with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: BookPubApplicationTests.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Before
public void loadDataFixtures() {
	if (loadDataFixtures) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql"));
		DatabasePopulatorUtils.execute(populator, ds);
		loadDataFixtures = false;
	}
}
 
Example 6
Source File: EmbeddedDatabaseFactory.java    From spring4-understanding with Apache License 2.0 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 7
Source File: TaskRepositoryInitializer.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: DatabasePopulationRule.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 9
Source File: EmbeddedDatabaseFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void destroy() {
	if (this.databaseCleaner != null && getDataSource() != null) {
		DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource());
	}
	shutdownDatabase();
}
 
Example 10
Source File: BookPubApplicationTests.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Before
public void loadDataFixtures() {
	if (loadDataFixtures) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql"));
		DatabasePopulatorUtils.execute(populator, ds);
		loadDataFixtures = false;
	}
}
 
Example 11
Source File: MemberDataSourceConfig.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: BookPubApplicationTests.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Before
public void loadDataFixtures() {
	if (loadDataFixtures) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/test-data.sql"));
		DatabasePopulatorUtils.execute(populator, ds);
		loadDataFixtures = false;
	}
}
 
Example 13
Source File: EmbeddedDatabaseFactoryBean.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() {
	if (this.databaseCleaner != null) {
		DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource());
	}
	shutdownDatabase();
}
 
Example 14
Source File: TeiidTestDataSources.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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 15
Source File: AbstractBatchIntegrationTest.java    From batchers with Apache License 2.0 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 16
Source File: RepositoryStepdefs.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
@Given("^([^\\\"]*) fixture is loaded$")
public void data_fixture_is_loaded(String fixtureName) throws Throwable {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/" + fixtureName + ".sql"));
    DatabasePopulatorUtils.execute(populator, ds);
}
 
Example 17
Source File: RepositoryStepdefs.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
@Given("^([^\\\"]*) fixture is loaded$")
public void data_fixture_is_loaded(String fixtureName) throws Throwable {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(context.getResource("classpath:/" + fixtureName + ".sql"));
    DatabasePopulatorUtils.execute(populator, ds);
}
 
Example 18
Source File: SocialDatabasePopulator.java    From Spring-Security-Third-Edition with MIT 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 19
Source File: DatabaseInitializer.java    From lemonaid with MIT 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 20
Source File: DynamicResourceDatabasePopulator.java    From multitenant with Apache License 2.0 2 votes vote down vote up
/**
 * Execute this {@code ResourceDatabasePopulator} against the given
 * {@link DataSource}.
 * <p>Delegates to {@link DatabasePopulatorUtils#execute}.
 * @param dataSource the {@code DataSource} to execute against (never {@code null})
 * @throws ScriptException if an error occurs
 * @since 4.1
 * @see #populate(Connection)
 */
public void execute(DataSource dataSource) throws ScriptException {
	DatabasePopulatorUtils.execute(this, dataSource);
}