Example usage for org.springframework.jdbc.datasource.init ResourceDatabasePopulator ResourceDatabasePopulator

List of usage examples for org.springframework.jdbc.datasource.init ResourceDatabasePopulator ResourceDatabasePopulator

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource.init ResourceDatabasePopulator ResourceDatabasePopulator.

Prototype

public ResourceDatabasePopulator() 

Source Link

Document

Construct a new ResourceDatabasePopulator with default settings.

Usage

From source file:org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.java

private void runScripts(List<Resource> resources) {
    if (resources.isEmpty()) {
        return;//from w ww.  jav a2 s  .c  o  m
    }
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(this.properties.isContinueOnError());
    populator.setSeparator(this.properties.getSeparator());
    if (this.properties.getSqlScriptEncoding() != null) {
        populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
    }
    for (Resource resource : resources) {
        populator.addScript(resource);
    }
    DatabasePopulatorUtils.execute(populator, this.dataSource);
}

From source file:org.springframework.cloud.dataflow.server.repository.support.DataflowRdbmsInitializer.java

@Override
public void afterPropertiesSet() throws Exception {
    if (dataSource != null && definitionInitializationEnable) {
        String platform = getDatabaseType(dataSource);

        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));
        if (featuresProperties.isStreamsEnabled()) {
            String streamsSchemaLocation = schemaLocation;
            streamsSchemaLocation = streamsSchemaLocation.replace("@@suffix@@", STREAMS_SCHEMA_SUFFIX);
            logger.info(String.format("Adding dataflow schema %s for %s database", streamsSchemaLocation,
                    platform));/*from   ww w .j a  v  a2 s. c o m*/
            populator.addScript(resourceLoader.getResource(streamsSchemaLocation));
        }
        if (featuresProperties.isTasksEnabled()) {
            String tasksSchemaLocation = schemaLocation;
            tasksSchemaLocation = tasksSchemaLocation.replace("@@suffix@@", TASKS_SCHEMA_SUFFIX);
            logger.info(
                    String.format("Adding dataflow schema %s for %s database", tasksSchemaLocation, platform));
            populator.addScript(resourceLoader.getResource(tasksSchemaLocation));
        }
        if (featuresProperties.isStreamsEnabled() || featuresProperties.isTasksEnabled()) {
            String deploymentSchemaLocation = schemaLocation;
            deploymentSchemaLocation = deploymentSchemaLocation.replace("@@suffix@@", DEPLOYMENT_SCHEMA_SUFFIX);
            logger.info(String.format("Adding dataflow schema %s for %s database", deploymentSchemaLocation,
                    platform));
            populator.addScript(resourceLoader.getResource(deploymentSchemaLocation));
        }
        String jpaSchemaLocation = schemaLocation;
        jpaSchemaLocation = jpaSchemaLocation.replace("@@suffix@@", JPA_SCHEMA_SUFFIX);
        logger.info(String.format("Adding dataflow schema %s for %s database", jpaSchemaLocation, platform));
        populator.addScript(resourceLoader.getResource(jpaSchemaLocation));
        populator.setContinueOnError(true);
        logger.debug(String.format("Initializing dataflow schema for %s database", platform));
        DatabasePopulatorUtils.execute(populator, dataSource);
    }
}

From source file:org.springframework.cloud.deployer.admin.server.repository.support.DataflowRdbmsInitializer.java

@Override
public void afterPropertiesSet() throws Exception {
    if (dataSource != null && definitionInitializationEnable) {
        String platform = getDatabaseType(dataSource);
        if ("hsql".equals(platform)) {
            platform = "hsqldb";
        }/*from www.  ja  va 2  s  .c  o  m*/
        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);
    }
}

From source file:org.springframework.cloud.task.repository.support.TaskRepositoryInitializer.java

@Override
public void afterPropertiesSet() throws Exception {
    if (dataSource != null && taskInitializationEnable) {
        String platform = getDatabaseType(dataSource);
        if ("hsql".equals(platform)) {
            platform = "hsqldb";
        }//from w ww  . j  a  v a2s.c  o  m
        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(resourceLoader.getResource(schemaLocation));
        populator.setContinueOnError(true);
        logger.debug(String.format("Initializing task schema for %s database", platform));
        DatabasePopulatorUtils.execute(populator, dataSource);
    }
}

From source file:org.springframework.test.context.jdbc.DatabaseInitializerTestExecutionListener.java

/**
 * Execute the SQL scripts configured via the supplied
 * {@link DatabaseInitializer @DatabaseInitializer} for the given
 * {@link ExecutionPhase} and {@link TestContext}.
 *
 * <p>Special care must be taken in order to properly support the
 * {@link DatabaseInitializer#requireNewTransaction requireNewTransaction}
 * flag.//from  w  ww. j  av a2  s. c  o m
 *
 * @param databaseInitializer the {@code @DatabaseInitializer} to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link DatabaseInitializer @DatabaseInitializer}
 * was declared at the class level
 */
@SuppressWarnings("serial")
private void executeDatabaseInitializer(DatabaseInitializer databaseInitializer, ExecutionPhase executionPhase,
        TestContext testContext, boolean classLevel) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                databaseInitializer, executionPhase, testContext));
    }

    if (executionPhase != databaseInitializer.executionPhase()) {
        return;
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(databaseInitializer.encoding());
    populator.setSeparator(databaseInitializer.separator());
    populator.setCommentPrefix(databaseInitializer.commentPrefix());
    populator.setBlockCommentStartDelimiter(databaseInitializer.blockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(databaseInitializer.blockCommentEndDelimiter());
    populator.setContinueOnError(databaseInitializer.continueOnError());
    populator.setIgnoreFailedDrops(databaseInitializer.ignoreFailedDrops());

    String[] scripts = getScripts(databaseInitializer, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    populator.setScripts(
            TestContextResourceUtils.convertToResources(testContext.getApplicationContext(), scripts));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scripts));
    }

    final DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext,
            databaseInitializer.dataSource());
    final PlatformTransactionManager transactionManager = TestContextTransactionUtils
            .retrieveTransactionManager(testContext, databaseInitializer.transactionManager());

    int propagation = databaseInitializer.requireNewTransaction()
            ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
            : TransactionDefinition.PROPAGATION_REQUIRED;

    TransactionAttribute transactionAttribute = TestContextTransactionUtils
            .createDelegatingTransactionAttribute(testContext, new DefaultTransactionAttribute(propagation));

    new TransactionTemplate(transactionManager, transactionAttribute)
            .execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    populator.execute(dataSource);
                };
            });
}

From source file:org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.java

/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.//from ww  w  .j av  a  2  s  . c  o m
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext,
        boolean classLevel) throws Exception {

    if (executionPhase != sql.executionPhase()) {
        return;
    }

    MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                mergedSqlConfig, executionPhase, testContext));
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
    populator.setSeparator(mergedSqlConfig.getSeparator());
    populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
    populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
    populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
    populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

    String[] scripts = getScripts(sql, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    List<Resource> scriptResources = TestContextResourceUtils
            .convertToResourceList(testContext.getApplicationContext(), scripts);
    for (String stmt : sql.statements()) {
        if (StringUtils.hasText(stmt)) {
            stmt = stmt.trim();
            scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
        }
    }
    populator.setScripts(scriptResources.toArray(new Resource[scriptResources.size()]));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
    }

    String dsName = mergedSqlConfig.getDataSource();
    String tmName = mergedSqlConfig.getTransactionManager();
    DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
    PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext,
            tmName);
    boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

    if (txMgr == null) {
        Assert.state(!newTxRequired,
                () -> String.format(
                        "Failed to execute SQL scripts for test context %s: "
                                + "cannot execute SQL scripts using Transaction Mode "
                                + "[%s] without a PlatformTransactionManager.",
                        testContext, TransactionMode.ISOLATED));
        Assert.state(dataSource != null,
                () -> String.format("Failed to execute SQL scripts for test context %s: "
                        + "supply at least a DataSource or PlatformTransactionManager.", testContext));
        // Execute scripts directly against the DataSource
        populator.execute(dataSource);
    } else {
        DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
        // Ensure user configured an appropriate DataSource/TransactionManager pair.
        if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
            throw new IllegalStateException(String.format(
                    "Failed to execute SQL scripts for test context %s: "
                            + "the configured DataSource [%s] (named '%s') is not the one associated with "
                            + "transaction manager [%s] (named '%s').",
                    testContext, dataSource.getClass().getName(), dsName, txMgr.getClass().getName(), tmName));
        }
        if (dataSource == null) {
            dataSource = dataSourceFromTxMgr;
            Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for "
                    + "test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
                    testContext, txMgr.getClass().getName(), tmName));
        }
        final DataSource finalDataSource = dataSource;
        int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                : TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
                testContext, new DefaultTransactionAttribute(propagation));
        new TransactionTemplate(txMgr, txAttr).execute(status -> {
            populator.execute(finalDataSource);
            return null;
        });
    }
}

From source file:org.teiid.spring.autoconfigure.MultiDataSourceInitializer.java

private void runScripts(List<Resource> resources, String username, String password) {
    if (resources.isEmpty()) {
        return;/*from  ww  w . j  ava2  s. c  o  m*/
    }
    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);
}