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

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

Introduction

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

Prototype

public SingleConnectionDataSource() 

Source Link

Document

Constructor for bean-style configuration.

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 {//from ww  w . ja va2  s.  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 w  w.  ja  v a 2 s .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: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: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 a2  s  . co  m*/
    return new JdbcTemplate(ds);
}

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

/**
 * Method for creating the Data Source.//from  w  w  w.  j a  va 2 s  .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:org.unbunt.ella.lang.sql.DBUtils.java

protected static DriverManagerDataSource createDataSourceInternal(Properties props, String url, String user,
        String pass, String classOrType) throws DBConnectionFailedException {
    DriverManagerDataSource ds = new SingleConnectionDataSource();

    String[] driverClasses = null;
    if (classOrType != null) {
        try {//from  www.j  a v  a2 s  . c  om
            Drivers drivers = Drivers.valueOf(classOrType);
            driverClasses = drivers.getDriverClasses();
        } catch (IllegalArgumentException ignored) {
            driverClasses = new String[] { classOrType };
        }
    }

    if (driverClasses == null) {
        String driverClass = props.getProperty("driverClassName");
        if (driverClass != null) {
            driverClasses = new String[] { driverClass };
        } else {
            throw new DBConnectionFailedException("No driver specified");
        }
    }

    String actualDriverClass = null;
    for (String driverClass : driverClasses) {
        try {
            Class.forName(driverClass);
            actualDriverClass = driverClass;
            break;
        } catch (ClassNotFoundException e) {
            continue;
        }
    }

    if (actualDriverClass == null) {
        throw new DBConnectionFailedException("Failed to load JDBC driver: Unknown type or class not found");
    }

    ds.setDriverClassName(actualDriverClass);
    props.setProperty("driverClassName", actualDriverClass);

    if (url == null) {
        throw new DBConnectionFailedException("Missing URL");
    }
    ds.setUrl(url);

    if (user != null) {
        ds.setUsername(user);
    }
    if (pass != null) {
        ds.setPassword(pass);
    }

    ds.setConnectionProperties(props);

    return ds;
}

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 {/* w ww  . j  a v a 2s  .  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//from  www. j av  a2 s  .co  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;
}