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

The following are top voted examples for showing how to use org.springframework.jdbc.datasource.init.ResourceDatabasePopulator. 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   View source code 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   View source code 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: syncope   File: MigrateTest.java   View source code 7 votes vote down vote up
@Test
public void conf() throws Exception {
    // 1. migrate
    String[] args = new String[4];
    args[0] = "migrate";
    args[1] = "--conf";
    args[2] = BASE_PATH + File.separator + "content12.xml";
    args[3] = BASE_PATH + File.separator + "MasterContent.xml";

    new MigrateCommand().execute(new Input(args));

    // 2. initialize db as persistence-jpa does
    DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:syncopedb;DB_CLOSE_DELAY=-1", "sa", null);

    new ResourceDatabasePopulator(new ClassPathResource("/schema20.sql")).execute(dataSource);

    // 3. attempt to set initial content from the migrated MasterContent.xml
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try (InputStream in = new FileInputStream(args[3])) {

        SAXParser parser = factory.newSAXParser();
        parser.parse(in, new ContentLoaderHandler(dataSource, ROOT_ELEMENT, false));
    }
}
 
Example 4
Project: spring-boot-multidatasource   File: DataSourceInitializer.java   View source code 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   View source code 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   View source code 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: jdbc   File: PgcopySinkConfiguration.java   View source code 6 votes vote down vote up
@ConditionalOnProperty("pgcopy.initialize")
@Bean
public DataSourceInitializer nonBootDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
	DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
	dataSourceInitializer.setDataSource(dataSource);
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.setIgnoreFailedDrops(true);
	dataSourceInitializer.setDatabasePopulator(databasePopulator);
	if ("true".equals(properties.getInitialize())) {
		databasePopulator.addScript(new DefaultInitializationScriptResource(properties.getTableName(),
				properties.getColumns()));
	} else {
		databasePopulator.addScript(resourceLoader.getResource(properties.getInitialize()));
	}
	return dataSourceInitializer;
}
 
Example 8
Project: jdbc   File: JdbcSinkConfiguration.java   View source code 6 votes vote down vote up
@ConditionalOnProperty("jdbc.initialize")
@Bean
public DataSourceInitializer nonBootDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
	DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
	dataSourceInitializer.setDataSource(dataSource);
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.setIgnoreFailedDrops(true);
	dataSourceInitializer.setDatabasePopulator(databasePopulator);
	if ("true".equals(properties.getInitialize())) {
		databasePopulator.addScript(new DefaultInitializationScriptResource(properties.getTableName(),
				properties.getColumnsMap().keySet()));
	}
	else {
		databasePopulator.addScript(resourceLoader.getResource(properties.getInitialize()));
	}
	return dataSourceInitializer;
}
 
Example 9
Project: c2mon   File: RuleCachePopulationRule.java   View source code 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: ConfigurationCachePopulationRule.java   View source code 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: ClientCachePopulationRule.java   View source code 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: DaqCachePopulationRule.java   View source code 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 13
Project: c2mon   File: CachePopulationRule.java   View source code 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: HsqlDatabaseBuilder.java   View source code 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 15
Project: c2mon   File: CachePopulationRule.java   View source code 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 16
Project: c2mon   File: SupervisionCachePopulationRule.java   View source code 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 17
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceInitializer.java   View source code 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: https-github.com-g0t4-jenkins2-course-spring-boot   File: BatchDatabaseInitializer.java   View source code 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: spring-boot-concourse   File: DataSourceInitializer.java   View source code 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 20
Project: blog-java2   File: SpringTestBase.java   View source code 6 votes vote down vote up
protected void executeSql(String path) {
    logger.info("executeSql : " + path);

    Resource resource = new ClassPathResource(path, getClass());
    ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
    rdp.addScript(resource);
    rdp.setSqlScriptEncoding("UTF-8");
    rdp.setIgnoreFailedDrops(true);
    rdp.setContinueOnError(false);

    try (Connection conn = DataSourceUtils.getConnection(dataSource)) {
        rdp.populate(conn);
    }
    catch (Exception e) {
        throw new IllegalStateException("executeSql failed, path=" + path, e);
    }
}
 
Example 21
Project: contestparser   File: BatchDatabaseInitializer.java   View source code 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 22
Project: teamcity-highlighter   File: MySQLDBAdapter.java   View source code 6 votes vote down vote up
@Override
public void serverStartup()
{
    LOG.info("Initializing MySQL DB for highlighter");
    try (Connection connection = DriverManager.getConnection(url, user, password))
    {
        final ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.setContinueOnError(true);
        resourceDatabasePopulator.addScript(new FileSystemResource("../webapps/ROOT/plugins/highlighter-plugin/sql/mysql_init_db.sql"));
        resourceDatabasePopulator.addScript(new FileSystemResource("../webapps/ROOT/plugins/highlighter-plugin/sql/mysql_init_table.sql"));
        resourceDatabasePopulator.populate(connection);

        LOG.info("Initialization complete!");
    }
    catch (Exception e)
    {
        LOG.log(Level.SEVERE, "MySQL DB initialization failed for highlighter", e);
    }
}
 
Example 23
Project: booties   File: PostgreSqlRule.java   View source code 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 24
Project: syncope   File: H2StartStopListener.java   View source code 6 votes vote down vote up
@Override
public void contextInitialized(final ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);

    try {
        Server h2TestDb = new Server();
        h2TestDb.runTool("-tcp", "-tcpDaemon", "-web", "-webDaemon",
                "-webPort", ctx.getBean("testdb.webport", String.class));

        context.setAttribute(H2_TESTDB, h2TestDb);
    } catch (SQLException e) {
        LOG.error("Could not start H2 test db", e);
    }

    DataSource datasource = ctx.getBean(DataSource.class);

    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(ctx.getResource("classpath:/testdb.sql"));
    populator.setSqlScriptEncoding("UTF-8");
    DataSourceInitializer init = new DataSourceInitializer();
    init.setDataSource(datasource);
    init.setEnabled(true);
    init.setDatabasePopulator(populator);
    init.afterPropertiesSet();
    LOG.info("Database successfully initialized");
}
 
Example 25
Project: SpringClips   File: PersistenceConfigurarion.java   View source code 6 votes vote down vote up
@Bean
@Lazy(false)
public ResourceDatabasePopulator populateDatabase() throws SQLException {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("data.sql"));

    Connection connection = null;

    try {
        connection = DataSourceUtils.getConnection(dataSource());
        populator.populate(connection);
    } finally {
        if (connection != null) {
            DataSourceUtils.releaseConnection(connection, dataSource());
        }
    }

    return populator;
}
 
Example 26
Project: mev   File: PresetsRestConfigurationTest.java   View source code 6 votes vote down vote up
@Inject @Bean
public DataSourceInitializer dataSourceInitializer( @Named("presets-datasource") DataSource dataSource) {
    DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);

    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    
    String scriptDropAll = environment.getProperty("mev.presets.db.schema.script.dropall");
    log.info ("***dataSourceInitializer-dropAllPresetsScript-TEST:"+scriptDropAll);
    //populator.addScript(new ClassPathResource(scriptDropAll));
    String scriptTestPresetValuesFlatTable = environment.getProperty("mev.presets.db.schema.script.TestPresetValuesFlatTable");
    populator.addScript(new ClassPathResource(scriptTestPresetValuesFlatTable));
          
    initializer.setDatabasePopulator(populator);
     return initializer;
}
 
Example 27
Project: mev   File: ProbeAnnotationsPersistanceConfigTest.java   View source code 6 votes vote down vote up
@Inject @Bean
public DataSourceInitializer dataSourceInitializer( @Named("probe-annotations-datasource") DataSource dataSource) {
    DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);

    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    
    String scriptDropAll = environment.getProperty(MEV_PROBE_ANNOTATIONS_PROPERTY_PREFIX+"db.schema.script.dropall");
    log.info ("***dataSourceInitializer-dropAllScript-TEST:"+scriptDropAll);
    populator.addScript(new ClassPathResource(scriptDropAll));
    
    String scriptCreate = environment.getProperty(MEV_PROBE_ANNOTATIONS_PROPERTY_PREFIX+"db.schema.script");
    log.info ("***dataSourceInitializer-createScript-TEST:"+scriptCreate);
    populator.addScript(new ClassPathResource(scriptCreate));
    
    
    initializer.setDatabasePopulator(populator);
    return initializer;
}
 
Example 28
Project: spring-batch-experiments   File: JtaConfiguration.java   View source code 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 29
Project: spring-batch-experiments   File: JtaConfiguration.java   View source code 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 30
Project: druid-spring-boot   File: DruidDataSourceInitializer.java   View source code 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 31
Project: nixmash-blog   File: H2Config.java   View source code 5 votes vote down vote up
@Bean
public DatabasePopulator databasePopulator(DataSource dataSource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.setIgnoreFailedDrops(true);
    populator.addScripts(new ClassPathResource("/db/h2schema.sql"),
            new ClassPathResource("/db/h2data.sql"));
    try {
        populator.populate(dataSource.getConnection());
    } catch (SQLException ignored) {
    }
    return populator;
}
 
Example 32
Project: Your-Microservice   File: YourMicroserviceEnvironmentConfiguration.java   View source code 5 votes vote down vote up
@Bean
@DependsOn("entityManagerFactory")
public ResourceDatabasePopulator initDatabase(DataSource dataSource) throws Exception {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("db/h2/insert-data.sql"));
    populator.populate(dataSource.getConnection());
    return populator;
}
 
Example 33
Project: lams   File: EmbeddedDatabaseBuilder.java   View source code 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 34
Project: lams   File: DatabasePopulatorConfigUtils.java   View source code 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 35
Project: spring-batch-admin   File: DataSourceConfig.java   View source code 5 votes vote down vote up
private DatabasePopulator databasePopulator() {
	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setIgnoreFailedDrops(true);
	populator.setContinueOnError(true);
	populator.addScript(dropScript);
	populator.addScript(schemaScript);
	return populator;
}
 
Example 36
Project: spring-cloud-dashboard   File: DataflowRdbmsInitializer.java   View source code 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 37
Project: holon-datastore-jdbc   File: AbstractDatastoreIntegrationTest.java   View source code 5 votes vote down vote up
protected static void initSQL(DataSource dataSource, String... scripts) {
	try {
		ResourceLoader rl = new DefaultResourceLoader();
		ResourceDatabasePopulator rbp = new ResourceDatabasePopulator();
		for (String script : scripts) {
			rbp.addScripts(rl.getResource(script));
		}
		try (Connection connection = dataSource.getConnection()) {
			rbp.populate(connection);
		}
	} catch (Exception e) {
		throw new RuntimeException("Failed to init SQL scripts", e);
	}
}
 
Example 38
Project: dawn-marketplace-server   File: DatabaseConfiguration.java   View source code 5 votes vote down vote up
private DatabasePopulator createDatabasePopulator() {
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.setContinueOnError(true);
	// populate the database with required tables
	databasePopulator.addScript(new ClassPathResource("schema.sql"));
	return databasePopulator;
}
 
Example 39
Project: spring4-understanding   File: EmbeddedDatabaseBuilder.java   View source code 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 40
Project: spring4-understanding   File: DatabasePopulatorConfigUtils.java   View source code 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();
}