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

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

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DriverManagerDataSource 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:no.kantega.publishing.common.util.database.dbConnectionFactory.java

public static void loadConfiguration() {
    try {//from  www .jav  a  2s .c  o  m

        setConfiguration();

        verifyCompleteDatabaseConfiguration();

        DriverManagerDataSource rawDataSource = new DriverManagerDataSource();
        rawDataSource.setDriverClassName(dbDriver);
        rawDataSource.setUrl(dbUrl);

        if (!dbNTMLAuthentication) {
            rawDataSource.setUsername(dbUsername);
            rawDataSource.setPassword(dbPassword);
        }

        if (dbEnablePooling) {
            // Enable DBCP pooling
            BasicDataSource bds = new BasicDataSource();
            bds.setMaxTotal(dbMaxConnections);
            bds.setMaxIdle(dbMaxIdleConnections);
            bds.setMinIdle(dbMinIdleConnections);
            if (dbMaxWait != -1) {
                bds.setMaxWaitMillis(1000 * dbMaxWait);
            }

            if (dbDefaultQueryTimeout != -1) {
                bds.setDefaultQueryTimeout(dbDefaultQueryTimeout);
            }

            bds.setDriverClassName(dbDriver);
            if (!dbNTMLAuthentication) {
                bds.setUsername(dbUsername);
                bds.setPassword(dbPassword);
            }
            bds.setUrl(dbUrl);

            if (dbUseTransactions) {
                bds.setDefaultTransactionIsolation(dbTransactionIsolationLevel);
            }

            if (dbCheckConnections) {
                // Gjr at connections frigjres ved lukking fra database/brannmur
                bds.setValidationQuery("SELECT max(ContentId) from content");
                bds.setTimeBetweenEvictionRunsMillis(1000 * 60 * 2);
                bds.setMinEvictableIdleTimeMillis(1000 * 60 * 5);
                bds.setNumTestsPerEvictionRun(dbMaxConnections);
                if (dbRemoveAbandonedTimeout > 0) {
                    bds.setRemoveAbandonedTimeout(dbRemoveAbandonedTimeout);
                    bds.setLogAbandoned(true);
                }
            }

            ds = bds;
        } else {
            ds = rawDataSource;
        }

        // Use non-pooled datasource for table creation since validation query might fail
        ensureDatabaseExists(rawDataSource);
        if (shouldMigrateDatabase) {
            migrateDatabase(servletContext, rawDataSource);
        }

        if (dbUseTransactions) {
            log.info("Using transactions, database transaction isolation level set to "
                    + dbTransactionIsolationLevel);
        } else {
            log.info("Not using transactions");
        }

        if (debugConnections) {
            proxyDs = (DataSource) Proxy.newProxyInstance(DataSource.class.getClassLoader(),
                    new Class[] { DataSource.class }, new DataSourceWrapper(ds));
        }

    } catch (Exception e) {
        log.error("********* could not read aksess.conf **********", e);
    }

}

From source file:org.apache.kylin.rest.service.BasicService.java

public DataSource getOLAPDataSource(String project) {

    project = ProjectInstance.getNormalizedProjectName(project);

    DataSource ret = olapDataSources.get(project);
    if (ret == null) {
        logger.debug("Creating a new data source");
        logger.debug("OLAP data source pointing to " + getConfig());

        File modelJson = OLAPSchemaFactory.createTempOLAPJson(project, getConfig());

        try {/*from  ww w  . j  a  va 2 s  .  com*/
            List<String> text = Files.readLines(modelJson, Charset.defaultCharset());
            logger.debug("The new temp olap json is :");
            for (String line : text)
                logger.debug(line);
        } catch (IOException e) {
            e.printStackTrace(); // logging failure is not critical
        }

        DriverManagerDataSource ds = new DriverManagerDataSource();
        Properties props = new Properties();
        props.setProperty(OLAPQuery.PROP_SCAN_THRESHOLD,
                String.valueOf(KylinConfig.getInstanceFromEnv().getScanThreshold()));
        ds.setConnectionProperties(props);
        ds.setDriverClassName("net.hydromatic.optiq.jdbc.Driver");
        ds.setUrl("jdbc:calcite:model=" + modelJson.getAbsolutePath());

        ret = olapDataSources.putIfAbsent(project, ds);
        if (ret == null) {
            ret = ds;
        }
    }
    return ret;
}

From source file:org.encuestame.test.persistence.config.DBTestConfig.java

/**
 *
 * @return/*w  w w.j av a  2s .co m*/
 */
@Bean(name = "dataSource")
public DataSource restDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(EnMePlaceHolderConfigurer.getProperty("datasource.classname"));
    dataSource.setUrl(EnMePlaceHolderConfigurer.getProperty("datasource.urldb"));
    dataSource.setUsername(EnMePlaceHolderConfigurer.getProperty("datasource.userbd"));
    dataSource.setPassword(EnMePlaceHolderConfigurer.getProperty("datasource.pass"));
    return dataSource;
}

From source file:org.finra.dm.service.impl.JdbcServiceImpl.java

/**
 * Creates and returns a new data source from the given connection information.
 * Creates a new {@link DriverManagerDataSource}.
 * //w  w  w.  j a va2  s.  c  o  m
 * @param jdbcConnection The JDBC connection
 * @param variables Optional map of key-value for expression evaluation
 * @return a new {@link DataSource}
 */
private DataSource createDataSource(JdbcConnection jdbcConnection, Map<String, Object> variables) {
    String url = evaluate(jdbcConnection.getUrl(), variables, "jdbc connection url");
    String username = evaluate(jdbcConnection.getUsername(), variables, "jdbc connection username");
    String password = evaluate(jdbcConnection.getPassword(), variables, "jdbc connection password");

    validateUrl(url);

    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    driverManagerDataSource.setUrl(url);
    driverManagerDataSource.setUsername(username);
    driverManagerDataSource.setPassword(password);
    driverManagerDataSource.setDriverClassName(getDriverClassName(jdbcConnection.getDatabaseType()));
    return driverManagerDataSource;
}

From source file:org.finra.herd.service.impl.RelationalTableRegistrationHelperServiceImpl.java

/**
 * Retrieves a list of actual schema columns for the specified relational table. This method uses actual JDBC connection to retrieve a description of table
 * columns.//from w ww  .  j ava2 s  . c  o m
 *
 * @param relationalStorageAttributesDto the relational storage attributes DTO
 * @param relationalSchemaName the name of the relational database schema
 * @param relationalTableName the name of the relational table
 *
 * @return the list of schema columns for the specified relational table
 */
List<SchemaColumn> retrieveRelationalTableColumnsImpl(
        RelationalStorageAttributesDto relationalStorageAttributesDto, String relationalSchemaName,
        String relationalTableName) {
    // Get the JDBC password value.
    String password = getPassword(relationalStorageAttributesDto);

    // Create and initialize a driver manager data source (a simple implementation of the standard JDBC interface).
    // We only support PostgreSQL database type.
    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    driverManagerDataSource.setUrl(relationalStorageAttributesDto.getJdbcUrl());
    driverManagerDataSource.setUsername(relationalStorageAttributesDto.getJdbcUsername());
    driverManagerDataSource.setPassword(password);
    driverManagerDataSource.setDriverClassName(JdbcServiceImpl.DRIVER_POSTGRES);

    // Create an empty result list.
    List<SchemaColumn> schemaColumns = new ArrayList<>();

    // Connect to the database and retrieve the relational table columns.
    try (Connection connection = driverManagerDataSource.getConnection()) {
        DatabaseMetaData databaseMetaData = connection.getMetaData();

        // Check if the specified relational table exists in the database.
        try (ResultSet tables = databaseMetaData.getTables(null, relationalSchemaName, relationalTableName,
                null)) {
            Assert.isTrue(tables.next(), String.format(
                    "Relational table with \"%s\" name not found under \"%s\" schema at jdbc.url=\"%s\" for jdbc.username=\"%s\".",
                    relationalTableName, relationalSchemaName, driverManagerDataSource.getUrl(),
                    driverManagerDataSource.getUsername()));
        }

        // Retrieve the relational table columns.
        try (ResultSet columns = databaseMetaData.getColumns(null, relationalSchemaName, relationalTableName,
                null)) {
            while (columns.next()) {
                SchemaColumn schemaColumn = new SchemaColumn();
                schemaColumn.setName(columns.getString("COLUMN_NAME"));
                schemaColumn.setType(columns.getString("TYPE_NAME"));
                schemaColumn.setSize(columns.getString("COLUMN_SIZE"));
                schemaColumn.setRequired(columns.getInt("NULLABLE") == 0);
                schemaColumn.setDefaultValue(columns.getString("COLUMN_DEF"));
                schemaColumns.add(schemaColumn);
            }
        }
    } catch (SQLException e) {
        throw new IllegalArgumentException(String.format(
                "Failed to retrieve description of a relational table with \"%s\" name under \"%s\" schema "
                        + "at jdbc.url=\"%s\" using jdbc.username=\"%s\". Reason: %s",
                relationalTableName, relationalSchemaName, driverManagerDataSource.getUrl(),
                driverManagerDataSource.getUsername(), e.getMessage()), e);
    }

    return schemaColumns;
}

From source file:org.jasig.portal.rdbm.TransientDatasource.java

public TransientDatasource() {

    final Properties dataSourceProperties = new Properties();
    final InputStream dataSourcePropertiesStream = this.getClass()
            .getResourceAsStream("/dataSource.properties");
    try {/*  w  ww .j a v a2 s.  c  o m*/
        dataSourceProperties.load(dataSourcePropertiesStream);
    } catch (IOException e) {
        throw new RuntimeException("Failed to load dataSource.properties", e);
    } finally {
        IOUtils.closeQuietly(dataSourcePropertiesStream);
    }

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(dataSourceProperties.getProperty("hibernate.connection.driver_class"));
    dataSource.setUrl(dataSourceProperties.getProperty("hibernate.connection.url"));
    dataSource.setUsername(dataSourceProperties.getProperty("hibernate.connection.username"));
    dataSource.setPassword(dataSourceProperties.getProperty("hibernate.connection.password"));

    this.delegate = dataSource;

}

From source file:org.mskcc.cbio.importer.io.internal.DataSourceFactoryBean.java

/**
 * Method used to create a Datasource./*from  w  ww  .jav  a 2  s. com*/
 *
 * @param databaseUser String
 * @param databasePassword String
 * @param databaseDriver String
 * @param databaseConnectionString String
 * @return DataSource
 */
private static DataSource getDataSource(String databaseUser, String databasePassword, String databaseDriver,
        String databaseConnectionString) {

    // create the datasource and set its properties
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(databaseDriver);
    dataSource.setUrl(databaseConnectionString + "?max_allowed_packet=256M");
    dataSource.setUsername(databaseUser);
    dataSource.setPassword(databasePassword);

    // outta here
    return dataSource;
}

From source file:org.pentaho.platform.engine.services.connection.datasource.dbcp.PooledDatasourceHelper.java

public static DataSource convert(IDatabaseConnection databaseConnection) throws DBDatasourceServiceException {
    DriverManagerDataSource basicDatasource = new DriverManagerDataSource(); // From Spring
    IDatabaseDialectService databaseDialectService = PentahoSystem.get(IDatabaseDialectService.class,
            PentahoSessionHolder.getSession());
    IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection);
    if (databaseConnection.getDatabaseType() == null && dialect == null) {
        // We do not have enough information to create a DataSource. Throwing exception
        throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                "PooledDatasourceHelper.ERROR_0001_DATASOURCE_CREATE_ERROR_NO_DIALECT",
                databaseConnection.getName()));
    }//  w  w w . j a  v  a2s. com

    if (databaseConnection.getDatabaseType().getShortName().equals("GENERIC")) { //$NON-NLS-1$
        String driverClassName = databaseConnection.getAttributes()
                .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS);
        if (!StringUtils.isEmpty(driverClassName)) {
            basicDatasource.setDriverClassName(driverClassName);
        } else {
            // We do not have enough information to create a DataSource. Throwing exception
            throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                    "PooledDatasourceHelper.ERROR_0002_DATASOURCE_CREATE_ERROR_NO_CLASSNAME",
                    databaseConnection.getName()));
        }

    } else {
        if (!StringUtils.isEmpty(dialect.getNativeDriver())) {
            basicDatasource.setDriverClassName(dialect.getNativeDriver());
        } else {
            // We do not have enough information to create a DataSource. Throwing exception
            throw new DBDatasourceServiceException(Messages.getInstance().getErrorString(
                    "PooledDatasourceHelper.ERROR_0003_DATASOURCE_CREATE_ERROR_NO_DRIVER",
                    databaseConnection.getName()));
        }

    }
    try {
        basicDatasource.setUrl(dialect.getURLWithExtraOptions(databaseConnection));
    } catch (DatabaseDialectException e) {
        basicDatasource.setUrl(null);
    }
    basicDatasource.setUsername(databaseConnection.getUsername());
    basicDatasource.setPassword(databaseConnection.getPassword());

    return basicDatasource;
}

From source file:ubic.gemma.core.externalDb.GoldenPath.java

void init() {
    assert databaseName != null;
    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    this.url = "jdbc:mysql://" + host + ":" + port + "/" + databaseName + "?relaxAutoCommit=true";
    GoldenPath.log.info("Connecting to " + databaseName);
    GoldenPath.log.debug("Connecting to Golden Path : " + url + " as " + user);

    dataSource.setDriverClassName(this.getDriver());
    dataSource.setUrl(url);
    dataSource.setUsername(user);/* w w  w. j a va2 s  . c  o m*/
    dataSource.setPassword(password);

    jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.setFetchSize(50);

}