Example usage for org.springframework.jdbc.datasource SingleConnectionDataSource setUrl

List of usage examples for org.springframework.jdbc.datasource SingleConnectionDataSource setUrl

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource SingleConnectionDataSource setUrl.

Prototype

public void setUrl(@Nullable String url) 

Source Link

Document

Set the JDBC URL to use for connecting through the Driver.

Usage

From source file:eu.databata.engine.util.PropagatorRecreateDatabaseTool.java

public static void main(String[] args) {
    ClassLoader classLoader = PropagatorRecreateDatabaseTool.class.getClassLoader();
    InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties");
    Properties propagatorProperties = new Properties();
    try {// ww w. j  a  v  a 2s  . c  o m
        propagatorProperties.load(resourceAsStream);
    } catch (FileNotFoundException e) {
        LOG.error("Sepecified file 'databata.properties' not found");
    } catch (IOException e) {
        LOG.error("Sepecified file 'databata.properties' cannot be loaded");
    }

    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();
    dataSource.setDriverClassName(propagatorProperties.getProperty("db.propagation.driver"));
    dataSource.setUrl(propagatorProperties.getProperty("db.propagation.dba.connection-url"));
    dataSource.setUsername(propagatorProperties.getProperty("db.propagation.dba.user"));
    dataSource.setPassword(propagatorProperties.getProperty("db.propagation.dba.password"));
    dataSource.setSuppressClose(true);

    String databaseName = "undefined";
    try {
        databaseName = dataSource.getConnection().getMetaData().getDatabaseProductName();
    } catch (SQLException e) {
        LOG.error("Cannot get connection by specified url", e);
    }
    String databaseCode = PropagationUtils.getDatabaseCode(databaseName);
    LOG.info("Database with code '" + databaseCode + "' is identified.");

    String submitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.sql";
    String fileContent = "";
    try {
        fileContent = getFileContent(classLoader, submitFileName);
    } catch (IOException e) {
        LOG.info("File with name '" + submitFileName
                + "' cannot be read from classpath. Trying to load default submit file.");
    }
    if (fileContent == null || "".equals(fileContent)) {
        String defaultSubmitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.default.sql";
        try {
            fileContent = getFileContent(classLoader, defaultSubmitFileName);
        } catch (IOException e) {
            LOG.info("File with name '" + defaultSubmitFileName
                    + "' cannot be read from classpath. Trying to load default submit file.");
        }
    }

    if (fileContent == null) {
        LOG.info("File content is empty. Stopping process.");
        return;
    }

    fileContent = replacePlaceholders(fileContent, propagatorProperties);

    SqlFile sqlFile = null;
    try {
        sqlFile = new SqlFile(fileContent, null, submitFileName, new SqlExecutionCallback() {

            @Override
            public void handleExecuteSuccess(String sql, int arg1, double arg2) {
                LOG.info("Sql is sucessfully executed \n ======== \n" + sql + "\n ======== \n");
            }

            @Override
            public void handleException(SQLException arg0, String sql) throws SQLException {
                LOG.info("Sql returned error \n ======== \n" + sql + "\n ======== \n");
            }
        }, null);
    } catch (IOException e) {
        LOG.error("Error when initializing SqlTool", e);
    }
    try {
        sqlFile.setConnection(dataSource.getConnection());
    } catch (SQLException e) {
        LOG.error("Error is occured when setting connection", e);
    }

    try {
        sqlFile.execute();
    } catch (SqlToolError e) {
        LOG.error("Error when creating user", e);
    } catch (SQLException e) {
        LOG.error("Error when creating user", e);
    }
}

From source file:eu.databata.engine.util.PropagatorRecreateUserTool.java

public static void main(String[] args) {
    if (args.length == 0) {
        printMessage();//from w  ww. java2s.  c  o  m
        return;
    }
    String scriptName = getScriptName(args[0]);
    if (scriptName == null) {
        printMessage();
        return;
    }
    ClassLoader classLoader = PropagatorRecreateUserTool.class.getClassLoader();
    InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties");
    Properties propagatorProperties = new Properties();
    try {
        propagatorProperties.load(resourceAsStream);
    } catch (FileNotFoundException e) {
        LOG.error("Sepecified file 'databata.properties' not found");
    } catch (IOException e) {
        LOG.error("Sepecified file 'databata.properties' cannot be loaded");
    }

    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();
    dataSource.setDriverClassName(propagatorProperties.getProperty("db.propagation.driver"));
    if ("-idb".equals(args[0])) {
        dataSource.setUrl(propagatorProperties.getProperty("db.propagation.dba.connection-url"));
        dataSource.setUsername(propagatorProperties.getProperty("db.propagation.dba.user"));
        dataSource.setPassword(propagatorProperties.getProperty("db.propagation.dba.password"));
    } else {
        dataSource.setUrl(propagatorProperties.getProperty("db.propagation.sa.connection-url"));
        dataSource.setUsername(propagatorProperties.getProperty("db.propagation.sa.user"));
        dataSource.setPassword(propagatorProperties.getProperty("db.propagation.sa.password"));
    }
    dataSource.setSuppressClose(true);

    String databaseName = "undefined";
    try {
        databaseName = dataSource.getConnection().getMetaData().getDatabaseProductName();
    } catch (SQLException e) {
        LOG.error("Cannot get connection by specified url", e);
        return;
    }
    String databaseCode = PropagationUtils.getDatabaseCode(databaseName);
    LOG.info("Database with code '" + databaseCode + "' is identified. for database '" + databaseName + "'");

    String submitFileName = "META-INF/databata/" + databaseCode + "_" + scriptName + ".sql";
    String fileContent = "";
    try {
        fileContent = getFileContent(classLoader, submitFileName);
    } catch (IOException e) {
        LOG.info("File with name '" + submitFileName
                + "' cannot be read from classpath. Trying to load default submit file.");
    }
    if (fileContent == null || "".equals(fileContent)) {
        String defaultSubmitFileName = "META-INF/databata/" + databaseCode + "_" + scriptName + ".default.sql";
        try {
            fileContent = getFileContent(classLoader, defaultSubmitFileName);
        } catch (IOException e) {
            LOG.info("File with name '" + defaultSubmitFileName
                    + "' cannot be read from classpath. Trying to load default submit file.");
        }
    }

    if (fileContent == null) {
        LOG.info("File content is empty. Stopping process.");
        return;
    }

    fileContent = replacePlaceholders(fileContent, propagatorProperties);

    SqlFile sqlFile = null;
    try {
        sqlFile = new SqlFile(fileContent, null, submitFileName, new SqlExecutionCallback() {

            @Override
            public void handleExecuteSuccess(String sql, int arg1, double arg2) {
                LOG.info("Sql is sucessfully executed \n ======== \n" + sql + "\n ======== \n");
            }

            @Override
            public void handleException(SQLException arg0, String sql) throws SQLException {
                LOG.info("Sql returned error \n ======== \n" + sql + "\n ======== \n");
            }
        }, null);
    } catch (IOException e) {
        LOG.error("Error when initializing SqlTool", e);
    }
    try {
        sqlFile.setConnection(dataSource.getConnection());
    } catch (SQLException e) {
        LOG.error("Error is occured when setting connection", e);
    }

    try {
        sqlFile.execute();
    } catch (SqlToolError e) {
        LOG.error("Error when creating user", e);
    } catch (SQLException e) {
        LOG.error("Error when creating user", e);
    }
}

From source file:io.github.benas.jql.Utils.java

public static SingleConnectionDataSource getDataSourceFrom(String databaseFile) {
    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();
    dataSource.setDriverClassName("org.sqlite.JDBC");
    dataSource.setUrl("jdbc:sqlite:" + databaseFile);
    return dataSource;
}

From source file:com.emc.ecs.sync.service.SqliteDbService.java

protected JdbcTemplate createJdbcTemplate() {
    SingleConnectionDataSource ds = new SingleConnectionDataSource();
    ds.setUrl(JDBC_URL_BASE + getDbFile());
    ds.setSuppressClose(true);/*from   w  w w .  j  av  a 2s.co m*/
    return new JdbcTemplate(ds);
}

From source file:nl.tranquilizedquality.itest.configuration.DatasourceConfiguration.java

@Bean(name = "dataSource")
public SingleConnectionDataSource singleConnectionDataSource() {

    final SingleConnectionDataSource singleConnectionDataSource = new SingleConnectionDataSource();
    singleConnectionDataSource.setDriverClassName(driverClassName);
    singleConnectionDataSource.setUrl(url);
    singleConnectionDataSource.setUsername(username);
    singleConnectionDataSource.setPassword(password);
    singleConnectionDataSource.setSuppressClose(true);
    return singleConnectionDataSource;
}

From source file:gr.abiss.calipso.config.DataSourceFactoryBean.java

public Object getObject() throws Exception {
    if (StringUtils.hasText(dataSourceJndiName)) {
        logger.info("JNDI datasource requested, looking up datasource from JNDI name: '" + dataSourceJndiName
                + "'");
        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
        factoryBean.setJndiName(dataSourceJndiName);
        // "java:comp/env/" will be prefixed if the JNDI name doesn't already have it
        factoryBean.setResourceRef(true);
        // this step actually does the JNDI lookup
        try {//from  w  ww.  j ava2  s .c o  m
            factoryBean.afterPropertiesSet();
        } catch (Exception e) {
            logger.error("datasource init from JNDI failed : " + e);
            logger.error("aborting application startup");
            throw new RuntimeException(e);
        }
        dataSource = (DataSource) factoryBean.getObject();
    } else if (url.startsWith("jdbc:hsqldb:file")) {
        logger.info("embedded HSQLDB mode detected, switching on spring single connection data source");
        SingleConnectionDataSource ds = new SingleConnectionDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setSuppressClose(true);
        dataSource = ds;
    } else {
        logger.info(
                "Not using embedded HSQLDB or JNDI datasource, switching on Apache DBCP data source connection pooling");
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setValidationQuery(validationQuery);
        ds.setTestOnBorrow(false);
        ds.setTestWhileIdle(true);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        dataSource = ds;
    }
    return dataSource;
}

From source file:info.jtrac.config.DataSourceFactoryBean.java

/**
 * This method returns the dataSource object used for the DB access.
 *
 * @throws Exception//  ww  w  .ja  v a  2 s .c o  m
 * @see org.springframework.beans.factory.FactoryBean#getObject()
 */
@Override
public DataSource getObject() throws Exception {
    if (StringUtils.hasText(dataSourceJndiName)) {
        logger.info("JNDI datasource requested, looking up datasource from JNDI name: '" + dataSourceJndiName
                + "'");
        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
        factoryBean.setJndiName(dataSourceJndiName);

        // "java:comp/env/" will be prefixed if the JNDI name doesn't already have it
        factoryBean.setResourceRef(true);

        // This step actually does the JNDI lookup
        try {
            factoryBean.afterPropertiesSet();
        } catch (Exception e) {
            logger.error("datasource init from JNDI failed : " + e);
            logger.error("aborting application startup");
            throw new RuntimeException(e);
        } // end try..catch

        dataSource = (DataSource) factoryBean.getObject();
    } else if (url.startsWith("jdbc:hsqldb:file")) {
        logger.info("embedded HSQLDB mode detected, switching on spring single connection data source");
        SingleConnectionDataSource ds = new SingleConnectionDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setSuppressClose(true);
        dataSource = ds;
    } else {
        logger.info(
                "Not using embedded HSQLDB or JNDI datasource, switching on Apache DBCP data source connection pooling");
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setValidationQuery(validationQuery);
        ds.setTestOnBorrow(false);
        ds.setTestWhileIdle(true);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        dataSource = ds;
    } // end if..else

    return dataSource;
}

From source file:org.osgp.adapter.protocol.dlms.application.config.DlmsPersistenceConfig.java

/**
 * Method for creating the Data Source.//from  w  ww  .j  av a2s.  c  o  m
 *
 * @return DataSource
 */
public DataSource dlmsDataSource() {
    final SingleConnectionDataSource singleConnectionDataSource = new SingleConnectionDataSource();
    singleConnectionDataSource.setAutoCommit(false);
    final Properties properties = new Properties();
    properties.setProperty("socketTimeout", "0");
    properties.setProperty("tcpKeepAlive", "true");
    singleConnectionDataSource
            .setDriverClassName(this.environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
    singleConnectionDataSource.setUrl(this.environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
    singleConnectionDataSource
            .setUsername(this.environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
    singleConnectionDataSource
            .setPassword(this.environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
    singleConnectionDataSource.setSuppressClose(true);
    return singleConnectionDataSource;
}

From source file:com.emc.ecs.sync.EndToEndTest.java

protected void verifyDb(TestObjectSource testSource, boolean truncateDb) {
    SingleConnectionDataSource ds = new SingleConnectionDataSource();
    ds.setUrl(SqliteDbService.JDBC_URL_BASE + dbFile.getPath());
    ds.setSuppressClose(true);/*from   w w w.  j a v  a2  s.  com*/
    JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

    long totalCount = verifyDbObjects(jdbcTemplate, testSource.getObjects());
    try {
        SqlRowSet rowSet = jdbcTemplate.queryForRowSet("SELECT count(source_id) FROM "
                + DbService.DEFAULT_OBJECTS_TABLE_NAME + " WHERE target_id != ''");
        Assert.assertTrue(rowSet.next());
        Assert.assertEquals(totalCount, rowSet.getLong(1));
        if (truncateDb)
            jdbcTemplate.update("DELETE FROM " + DbService.DEFAULT_OBJECTS_TABLE_NAME);
    } finally {
        try {
            ds.destroy();
        } catch (Throwable t) {
            log.warn("could not close datasource", t);
        }
    }
}