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); }
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); }
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) { } }
@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; }
@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; }
@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(); }
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; }
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); } }
/** * 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; }
@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); } }
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!"); }
@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"); }
@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)); } }
@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; }
@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; }
@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; }
@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; }
@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; }
@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; }
@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; }
/** * 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; }
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(); }
private DatabasePopulator databasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.setIgnoreFailedDrops(true); populator.setContinueOnError(true); populator.addScript(dropScript); populator.addScript(schemaScript); return populator; }
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); } }
private DatabasePopulator createDatabasePopulator() { ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.setContinueOnError(true); // populate the database with required tables databasePopulator.addScript(new ClassPathResource("schema.sql")); return databasePopulator; }