org.springframework.jdbc.datasource.init.ResourceDatabasePopulator Java Examples

The following examples show how to use org.springframework.jdbc.datasource.init.ResourceDatabasePopulator. 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: HermesDataSourceInitializer.java    From hermes with Apache License 2.0 7 votes vote down vote up
/**
 * DriverName: 
 * 1:MySQL Connector Java; 
 * 2:Oracle JDBC driver; 
 * 3:H2 JDBC Driver
 * @throws SQLException
 */
@PostConstruct
public void initData() throws SQLException {
	String dbDriverName = getDBDriveName();
	Logger.info("当前数据库驱动名称:"+dbDriverName);
	Logger.info("检查是否需要初始化脚本");
	Query query = new Query("from User");
	Long userCount = commonRepository.count(query.getCount(), new HashMap<String, Object>());
	if (userCount == 0) {
		Logger.info("开始进行初始化脚本");
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.setSqlScriptEncoding("utf-8");
		populator.addScript(dataScript);
		populator.populate(dataSource.getConnection());
		Logger.info("初始化脚本已完成");
		return;
	}else{
		Logger.info("不需要初始化脚本");
	}
}
 
Example #3
Source File: TaskLauncherSinkTests.java    From spring-cloud-task with Apache License 2.0 7 votes vote down vote up
@Before
public void setup() {
	this.properties = new HashMap<>();
	this.properties.put("spring.datasource.url", DATASOURCE_URL);
	this.properties.put("spring.datasource.username", DATASOURCE_USER_NAME);
	this.properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD);
	this.properties.put("spring.datasource.driverClassName",
			DATASOURCE_DRIVER_CLASS_NAME);
	this.properties.put("spring.application.name", TASK_NAME);

	JdbcTemplate template = new JdbcTemplate(this.dataSource);
	template.execute("DROP ALL OBJECTS");

	DataSourceInitializer initializer = new DataSourceInitializer();

	initializer.setDataSource(this.dataSource);
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.addScript(
			new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql"));
	initializer.setDatabasePopulator(databasePopulator);

	initializer.afterPropertiesSet();
}
 
Example #4
Source File: DaoEnvTestSpringModuleConfig.java    From herd with Apache License 2.0 6 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 #5
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 #6
Source File: PostgreSqlRule.java    From booties with Apache License 2.0 6 votes vote down vote up
private void applyScripts(String url) throws SQLException, IOException {
    log.info("Apply Scripts ...");
    Connection connection = getConnection(url);
    DataSource ds = new SingleConnectionDataSource(connection, false);
    FileSystemScanner scanner = new FileSystemScanner();
    for (String location : builder.locations) {
        File directory = new File(location);
        if (directory.exists() && directory.isDirectory()) {
            Resource[] resources = scanner.scanForResources(location, "", ".sql");
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resources);
            populator.setSeparator(builder.separator);
            populator.execute(ds);
        } else {
            // log not existing directory
        }
    }
    log.info("Scripts applied!");
}
 
Example #7
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 #8
Source File: IndexController.java    From wetech-admin with MIT License 5 votes vote down vote up
@GetMapping("datasource/initialize")
public Result initializeDatasource() {
    DataSource dataSource = SpringUtils.getBean(DataSource.class);
    ResourceLoader loader = new DefaultResourceLoader();
    Resource schema = loader.getResource("classpath:schema.sql");
    Resource data = loader.getResource("classpath:data.sql");
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(schema, data);
    populator.execute(dataSource);
    return Result.success();
}
 
Example #9
Source File: TaskStartTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	this.properties = new HashMap<>();
	this.properties.put("spring.datasource.url", DATASOURCE_URL);
	this.properties.put("spring.datasource.username", DATASOURCE_USER_NAME);
	this.properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD);
	this.properties.put("spring.datasource.driverClassName",
			DATASOURCE_DRIVER_CLASS_NAME);
	this.properties.put("spring.application.name", TASK_NAME);
	this.properties.put("spring.cloud.task.initialize-enabled", "false");

	JdbcTemplate template = new JdbcTemplate(this.dataSource);
	template.execute("DROP TABLE IF EXISTS TASK_TASK_BATCH");
	template.execute("DROP TABLE IF EXISTS TASK_SEQ");
	template.execute("DROP TABLE IF EXISTS TASK_EXECUTION_PARAMS");
	template.execute("DROP TABLE IF EXISTS TASK_EXECUTION");
	template.execute("DROP TABLE IF EXISTS TASK_LOCK");
	template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION_SEQ");
	template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION_CONTEXT");
	template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_SEQ");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_SEQ");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_PARAMS");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_CONTEXT");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_INSTANCE");
	template.execute("DROP SEQUENCE IF EXISTS TASK_SEQ");

	DataSourceInitializer initializer = new DataSourceInitializer();

	initializer.setDataSource(this.dataSource);
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.addScript(
			new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql"));
	initializer.setDatabasePopulator(databasePopulator);
	initializer.afterPropertiesSet();
}
 
Example #10
Source File: DatabaseScriptLifecycleHandler.java    From vladmihalcea.wordpress.com with Apache License 2.0 5 votes vote down vote up
private void runInitScripts() {
    final ResourceDatabasePopulator resourceDatabasePopulator = createResourceDatabasePopulator();
    jdbcTemplate.execute(new ConnectionCallback<Void>() {
        @Override
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            resourceDatabasePopulator.setScripts(getInitScripts());
            resourceDatabasePopulator.populate(con);
            return null;
        }
    });
}
 
Example #11
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 #12
Source File: PluginInstanceService.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
private void initMysqlDatabaseTables(ResourceServer dbServer, PluginMysqlInstance mysqlInstance,
        PluginPackage pluginPackage) {

    String tmpFolderName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    String initSqlPath = SystemUtils.getTempFolderPath() + tmpFolderName + "/" + pluginProperties.getInitDbSql();

    String s3KeyName = pluginPackage.getName() + File.separator + pluginPackage.getVersion() + File.separator
            + pluginProperties.getInitDbSql();
    logger.info("Download init.sql from S3: {}", s3KeyName);

    s3Client.downFile(pluginProperties.getPluginPackageBucketName(), s3KeyName, initSqlPath);

    DriverManagerDataSource dataSource = new DriverManagerDataSource(
            "jdbc:mysql://" + dbServer.getHost() + ":" + dbServer.getPort() + "/" + mysqlInstance.getSchemaName()
                    + "?characterEncoding=utf8&serverTimezone=UTC",
            mysqlInstance.getUsername(), EncryptionUtils.decryptWithAes(mysqlInstance.getPassword(),
                    resourceProperties.getPasswordEncryptionSeed(), mysqlInstance.getSchemaName()));
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    File initSqlFile = new File(initSqlPath);
    List<Resource> scipts = newArrayList(new FileSystemResource(initSqlFile));
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(false);
    populator.setIgnoreFailedDrops(false);
    populator.setSeparator(";");
    scipts.forEach(populator::addScript);
    try {
        populator.execute(dataSource);
    } catch (Exception e) {
        String errorMessage = String.format("Failed to execute init.sql for schema[%s]",
                mysqlInstance.getSchemaName());
        logger.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
    logger.info(String.format("Init database[%s] tables has done..", mysqlInstance.getSchemaName()));
}
 
Example #13
Source File: EmbeddedDatabaseBuilder.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new embedded database builder with the given {@link ResourceLoader}.
 * @param resourceLoader the {@code ResourceLoader} to delegate to
 */
public EmbeddedDatabaseBuilder(ResourceLoader resourceLoader) {
	this.databaseFactory = new EmbeddedDatabaseFactory();
	this.databasePopulator = new ResourceDatabasePopulator();
	this.databaseFactory.setDatabasePopulator(this.databasePopulator);
	this.resourceLoader = resourceLoader;
}
 
Example #14
Source File: EmbeddedDatabaseBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new embedded database builder with the given {@link ResourceLoader}.
 * @param resourceLoader the {@code ResourceLoader} to delegate to
 */
public EmbeddedDatabaseBuilder(ResourceLoader resourceLoader) {
	this.databaseFactory = new EmbeddedDatabaseFactory();
	this.databasePopulator = new ResourceDatabasePopulator();
	this.databaseFactory.setDatabasePopulator(this.databasePopulator);
	this.resourceLoader = resourceLoader;
}
 
Example #15
Source File: SystemVariableServiceTest.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
private void executeSqlScripts(List<Resource> scipts) throws ScriptException {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(false);
    populator.setIgnoreFailedDrops(false);
    populator.setSeparator(";");
    scipts.forEach(populator::addScript);
    populator.execute(dataSource);
}
 
Example #16
Source File: EmbeddedDatabaseFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testFactoryBeanLifecycle() throws Exception {
	EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean();
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource("db-schema.sql"),
		resource("db-test-data.sql"));
	bean.setDatabasePopulator(populator);
	bean.afterPropertiesSet();
	DataSource ds = bean.getObject();
	JdbcTemplate template = new JdbcTemplate(ds);
	assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class));
	bean.destroy();
}
 
Example #17
Source File: DatabasePopulatorConfigUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static BeanDefinition createDatabasePopulator(Element element, List<Element> scripts, String execution) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CompositeDatabasePopulator.class);

	boolean ignoreFailedDrops = element.getAttribute("ignore-failures").equals("DROPS");
	boolean continueOnError = element.getAttribute("ignore-failures").equals("ALL");

	ManagedList<BeanMetadataElement> delegates = new ManagedList<>();
	for (Element scriptElement : scripts) {
		String executionAttr = scriptElement.getAttribute("execution");
		if (!StringUtils.hasText(executionAttr)) {
			executionAttr = "INIT";
		}
		if (!execution.equals(executionAttr)) {
			continue;
		}
		BeanDefinitionBuilder delegate = BeanDefinitionBuilder.genericBeanDefinition(ResourceDatabasePopulator.class);
		delegate.addPropertyValue("ignoreFailedDrops", ignoreFailedDrops);
		delegate.addPropertyValue("continueOnError", continueOnError);

		// Use a factory bean for the resources so they can be given an order if a pattern is used
		BeanDefinitionBuilder resourcesFactory = BeanDefinitionBuilder.genericBeanDefinition(SortedResourcesFactoryBean.class);
		resourcesFactory.addConstructorArgValue(new TypedStringValue(scriptElement.getAttribute("location")));
		delegate.addPropertyValue("scripts", resourcesFactory.getBeanDefinition());
		if (StringUtils.hasLength(scriptElement.getAttribute("encoding"))) {
			delegate.addPropertyValue("sqlScriptEncoding", new TypedStringValue(scriptElement.getAttribute("encoding")));
		}
		String separator = getSeparator(element, scriptElement);
		if (separator != null) {
			delegate.addPropertyValue("separator", new TypedStringValue(separator));
		}
		delegates.add(delegate.getBeanDefinition());
	}
	builder.addPropertyValue("populators", delegates);

	return builder.getBeanDefinition();
}
 
Example #18
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 #19
Source File: EmbeddedDatabaseBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new embedded database builder with the given {@link ResourceLoader}.
 * @param resourceLoader the {@code ResourceLoader} to delegate to
 */
public EmbeddedDatabaseBuilder(ResourceLoader resourceLoader) {
	this.databaseFactory = new EmbeddedDatabaseFactory();
	this.databasePopulator = new ResourceDatabasePopulator();
	this.databaseFactory.setDatabasePopulator(this.databasePopulator);
	this.resourceLoader = resourceLoader;
}
 
Example #20
Source File: DataflowRdbmsInitializer.java    From spring-cloud-dashboard with Apache License 2.0 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("@@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 #21
Source File: TeiidTestDataSources.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: MasterDomain.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Bean(name = "MasterResourceDatabasePopulator")
@ConditionalOnMissingBean(name = "MasterResourceDatabasePopulator")
public ResourceDatabasePopulator masterResourceDatabasePopulator() {
    ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
    databasePopulator.setContinueOnError(true);
    databasePopulator.setIgnoreFailedDrops(true);
    databasePopulator.setSqlScriptEncoding("UTF-8");
    databasePopulator.addScript(auditSql);
    return databasePopulator;
}
 
Example #23
Source File: JdbcHdfsTaskIntegrationTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
DatabasePopulator databasePopulator(DataSource dataSource) throws SQLException, InterruptedException {
	DatabasePopulator dbp = new ResourceDatabasePopulator(false, false, "UTF-8",
			new ClassPathResource("jdbchdfs-schema.sql"),
			new ClassPathResource("jdbchdfs-data.sql"));
	dbp.populate(DataSourceUtils.getConnection(dataSource));
	return dbp;
}
 
Example #24
Source File: SqoopToolTaskApplicationTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
DatabasePopulator databasePopulator(DataSource dataSource) throws SQLException, InterruptedException {
	DatabasePopulator dbp = new ResourceDatabasePopulator(false, false, "UTF-8",
			new ClassPathResource("sqoop-test-schema-ddl.sql"),
			new ClassPathResource("sqoop-test-data.sql"));
	dbp.populate(DataSourceUtils.getConnection(dataSource));
	return dbp;
}
 
Example #25
Source File: SqoopToolJobApplicationTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
DatabasePopulator databasePopulator(DataSource dataSource) throws SQLException, InterruptedException {
	DatabasePopulator dbp = new ResourceDatabasePopulator(false, false, "UTF-8",
			new ClassPathResource("sqoop-schema-ddl.sql"),
			new ClassPathResource("sqoop-root-data.sql"),
			new ClassPathResource("sqoop-sessions-data.sql"),
			new ClassPathResource("sqoop-test-schema-ddl.sql"),
			new ClassPathResource("sqoop-test-data.sql"));
	dbp.populate(DataSourceUtils.getConnection(dataSource));
	return dbp;
}
 
Example #26
Source File: EmbeddedDatabaseBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new embedded database builder with the given {@link ResourceLoader}.
 * @param resourceLoader the {@code ResourceLoader} to delegate to
 */
public EmbeddedDatabaseBuilder(ResourceLoader resourceLoader) {
	this.databaseFactory = new EmbeddedDatabaseFactory();
	this.databasePopulator = new ResourceDatabasePopulator();
	this.databaseFactory.setDatabasePopulator(this.databasePopulator);
	this.resourceLoader = resourceLoader;
}
 
Example #27
Source File: DatabasePopulatorConfigUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
static private BeanDefinition createDatabasePopulator(Element element, List<Element> scripts, String execution) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CompositeDatabasePopulator.class);

	boolean ignoreFailedDrops = element.getAttribute("ignore-failures").equals("DROPS");
	boolean continueOnError = element.getAttribute("ignore-failures").equals("ALL");

	ManagedList<BeanMetadataElement> delegates = new ManagedList<BeanMetadataElement>();
	for (Element scriptElement : scripts) {
		String executionAttr = scriptElement.getAttribute("execution");
		if (!StringUtils.hasText(executionAttr)) {
			executionAttr = "INIT";
		}
		if (!execution.equals(executionAttr)) {
			continue;
		}
		BeanDefinitionBuilder delegate = BeanDefinitionBuilder.genericBeanDefinition(ResourceDatabasePopulator.class);
		delegate.addPropertyValue("ignoreFailedDrops", ignoreFailedDrops);
		delegate.addPropertyValue("continueOnError", continueOnError);

		// Use a factory bean for the resources so they can be given an order if a pattern is used
		BeanDefinitionBuilder resourcesFactory = BeanDefinitionBuilder.genericBeanDefinition(SortedResourcesFactoryBean.class);
		resourcesFactory.addConstructorArgValue(new TypedStringValue(scriptElement.getAttribute("location")));
		delegate.addPropertyValue("scripts", resourcesFactory.getBeanDefinition());
		if (StringUtils.hasLength(scriptElement.getAttribute("encoding"))) {
			delegate.addPropertyValue("sqlScriptEncoding", new TypedStringValue(scriptElement.getAttribute("encoding")));
		}
		if (StringUtils.hasLength(scriptElement.getAttribute("separator"))) {
			delegate.addPropertyValue("separator", new TypedStringValue(scriptElement.getAttribute("separator")));
		}
		delegates.add(delegate.getBeanDefinition());
	}
	builder.addPropertyValue("populators", delegates);

	return builder.getBeanDefinition();
}
 
Example #28
Source File: TempConfigToInitDB.java    From batchers with Apache License 2.0 5 votes vote down vote up
private DatabasePopulator dataSourcePopulator() {
    ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
    databasePopulator.setScripts(
            new ClassPathResource(dropScript),
            new ClassPathResource(schemaScript)
    );
    return databasePopulator;
}
 
Example #29
Source File: ConfigurationDatabasePopulationRule.java    From c2mon with GNU Lesser General Public License v3.0 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 #30
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);
	}
}