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:org.venzia.mdbc.service.MDBCServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public void init() throws URISyntaxException {
    this.mdbcConnectors = new HashMap<String, Connector>();

    // loader by xml format
    try {//  w  w  w . j  a v a  2s  .com
        for (String connectorDeclare : connectorsDeclare) {

            InputStream connectorStream = getClass().getClassLoader().getResourceAsStream(connectorDeclare);

            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(connectorStream);

            List<Element> connector = doc.getRootElement().getChildren("connector");
            for (int i = 0; i < connector.size(); i++) {
                Element node = (Element) connector.get(i);
                // conexion a bbdd
                DriverManagerDataSource ds = new DriverManagerDataSource();
                ds.setDriverClassName(node.getChildText("driver-class-name"));
                ds.setUrl(node.getChildText("url"));
                ds.setUsername(node.getChildText("username"));
                ds.setPassword(node.getChildText("password"));

                GenericDAO dao = new GenericDAO(ds);
                List<Element> columnsNodes = node.getChild("columns").getChildren("column");
                StringBuilder build = new StringBuilder();

                Map<String, Column> columns = new HashMap<String, Column>();
                int totalColumns = 0;
                for (Element column : columnsNodes) {
                    totalColumns++;
                    Column c = new Column(column);
                    columns.put(c.getName(), c);
                    if (column.getAttributeValue("primary-key") != null) {
                        dao.setPrimaryKey(column.getAttributeValue("name"));
                    }
                    if (totalColumns == 1) {
                        build.append(c.getName());
                    } else {
                        build.append(" , " + c.getName());
                    }
                }

                dao.setQuery("SELECT " + build.toString() + " FROM " + node.getChildText("table"));

                dao.setWhere(" WHERE " + node.getChildText("where"));

                // creamos el Bus Entry
                Connector entryPoint = new ConnectorImpl(dao, node.getChildText("name"),
                        node.getChildText("aspect"));
                entryPoint.setTitle(node.getChildText("title"));
                entryPoint.setDescription(node.getChildText("description"));

                entryPoint.setColumns(columns);

                entryPoint.setColumnDetail(node.getChildText("column-detail"));

                this.mdbcConnectors.put(entryPoint.getName(), entryPoint);
            }

        }

    } catch (IOException e) {
        logger.error(e);
    } catch (JDOMException e) {
        logger.error(e);
    }

}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGeneratorSlowTest.java

/**
 * Test the {@link QCLiveTestDataGenerator#setDccCommonLocalJdbcTemplate(JdbcTemplate)} and 
 * {@link QCLiveTestDataGenerator#setDiseaseLocalJdbcTemplate(JdbcTemplate)} methods with a {@link JdbcTemplate} instance
 * whose data source defines a URL that contains a hostname that points to a non-test database instance.
 * /*ww w. ja  v a2 s  .  co  m*/
 * <p>An {@link IllegalArgumentException} should be thrown indicating that non-test hostnames in the database URL are
 * not allowed.
 */
@Test
public void testSetInvalidDevJDBCURLForLocalDB() {

    // Set up at data source and JDBC Connection template that uses a test account
    String url = "invalidTestDBHostName";
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl(url);
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    // Try setting the COMMON LOCAL JdbcTemplate for the QCLiveTestDataGenerator, should throw an IllegalArgumentException
    QCLiveTestDataGenerator qcLiveTestDataGenerator = new QCLiveTestDataGenerator();
    try {
        qcLiveTestDataGenerator.setDccCommonLocalJdbcTemplate(jdbcTemplate);
    } catch (IllegalArgumentException iae) {
        assertEquals("Connection URL '" + url
                + "' for datasource defined by 'dccCommonLocalJdbcTemplate' does not point to a "
                + "known test database host. Expected one of [" + qcLiveTestDataGenerator.getTestDBHostNames()
                + "]", iae.getMessage());
    }

    // Try setting the DISEASE LOCAL JdbcTemplate for the QCLiveTestDataGenerator, should throw an IllegalArgumentException
    try {
        qcLiveTestDataGenerator.setDiseaseLocalJdbcTemplate(jdbcTemplate);
    } catch (IllegalArgumentException iae) {
        assertEquals("Connection URL '" + url
                + "' for datasource defined by 'diseaseLocalJdbcTemplate' does not point to a "
                + "known test database host. Expected one of [" + qcLiveTestDataGenerator.getTestDBHostNames()
                + "]", iae.getMessage());
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.datasource.impl.SqlDataSourceManagerImpl.java

/**
 * ?datasourceinfo ???//from w ww .  j  av  a 2s. c  om
 * 
 * @param dataSourceInfo ???
 * @return ???
 */
private DynamicSqlDataSource createDynamicDataSource(SqlDataSourceInfo dataSourceInfo)
        throws DataSourceException {
    MetaDataService.checkDataSourceInfo(dataSourceInfo);
    Map<String, SqlDataSourceWrap> dataSources = new HashMap<String, SqlDataSourceWrap>();

    for (int i = 0; i < dataSourceInfo.getHosts().size(); i++) {

        String dataSourceKey = generateDataSourceKey(dataSourceInfo.getProductLine(),
                dataSourceInfo.getHosts().get(i), dataSourceInfo.getInstanceName(),
                dataSourceInfo.getUsername(), Md5Util.encode(dataSourceInfo.toString())).replace(":",
                        DATASOURCEKEY_SEPRATE);
        if (dataSourceInfo.isDBProxy()) {
            // dbproxy?
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(dataSourceInfo.getDataBase().getDriver());
            dataSource.setUrl(dataSourceInfo.getJdbcUrls().get(i));
            dataSource.setUsername(dataSourceInfo.getUsername());
            try {
                dataSource.setPassword(dataSourceInfo.getPassword());
            } catch (Exception e) {
                log.error("set dataSource password error," + dataSourceInfo, e);
                throw new DataSourceException("set dataSource password error," + dataSourceInfo, e);
            }
            dataSources.put(dataSourceKey, new SqlDataSourceWrap(dataSource));
        } else {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDataSourceName(dataSourceKey);
            try {
                dataSource.setDriverClass(dataSourceInfo.getDataBase().getDriver());
            } catch (PropertyVetoException e) {
                log.error("set dataSource driverclass error," + dataSourceInfo, e);
                // ??
                throw new DataSourceException(
                        "set c3p0 driverclass error when create datasource with:" + dataSourceInfo, e);
            }
            dataSource.setJdbcUrl(dataSourceInfo.getJdbcUrls().get(i));
            dataSource.setUser(dataSourceInfo.getUsername());
            try {
                dataSource.setPassword(dataSourceInfo.getPassword());
            } catch (Exception e) {
                log.error("set dataSource password error," + dataSourceInfo, e);
                throw new DataSourceException("set dataSource password error," + dataSourceInfo, e);
            }

            dataSource.setInitialPoolSize(Integer.valueOf(dataSourceInfo.getConnectionProperties(
                    DataSourceInfo.JDBC_INITIALPOOLSIZE_KEY, DataSourceInfo.JDBC_INITIALPOOLSIZE)));
            dataSource.setMaxPoolSize(Integer.valueOf(dataSourceInfo.getConnectionProperties(
                    DataSourceInfo.JDBC_MAXPOOLSIZE_KEY, DataSourceInfo.JDBC_MAXPOOLSIZE)));
            dataSource.setMinPoolSize(Integer.valueOf(dataSourceInfo.getConnectionProperties(
                    DataSourceInfo.JDBC_MINPOOLSIZE_KEY, DataSourceInfo.JDBC_MINPOOLSIZE)));

            dataSource.setIdleConnectionTestPeriod(Integer.valueOf(
                    dataSourceInfo.getConnectionProperties(DataSourceInfo.JDBC_IDLECONNECTIONTESTPERIOD_KEY,
                            DataSourceInfo.JDBC_IDLECONNECTIONTESTPERIOD)));
            dataSource.setMaxIdleTime(Integer.valueOf(dataSourceInfo.getConnectionProperties(
                    DataSourceInfo.JDBC_MAXIDLETIME_KEY, DataSourceInfo.JDBC_MAXIDLETIME)));
            dataSource.setCheckoutTimeout(Integer.valueOf(dataSourceInfo.getConnectionProperties(
                    DataSourceInfo.JDBC_CHECKTIMEOUT_KEY, DataSourceInfo.JDBC_CHECKTIMEOUT)));
            log.info("add datasource info into c3p0 pool success:" + dataSourceInfo);

            dataSources.put(dataSourceKey, new SqlDataSourceWrap(dataSource));
        }

    }
    return new DynamicSqlDataSource(dataSources);
}

From source file:com.kylinolap.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  w ww  . j a  va 2s  .  co  m*/
            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();
        }

        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:optiq:model=" + modelJson.getAbsolutePath());

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

From source file:in.sc.dao.ListGenerator.java

public NamedParameterJdbcTemplate getTemplate() {
    if (namedParameterJdbcTemplate == null) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setSchema("smart_compare");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setUrl("jdbc:mysql://localhost:3306/smart_compare");
        //            dataSource.setPassword("rose@123");
        //            dataSource.setURL("jdbc:mysql://52.42.111.208:3033/smart_compare");

        namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }/*ww w .  j  a  v  a  2 s .c  om*/
    return namedParameterJdbcTemplate;
}

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 {/* w  w w. ja  v  a 2  s  .c  o  m*/
            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:scott.barleydb.test.TestBase.java

private void initDb() throws Exception {
    if (!databaseInitialized) {
        DriverManagerDataSource dmDataSource = new DriverManagerDataSource();
        dmDataSource.setDriverClassName(db.getDriverClassName());
        dmDataSource.setUrl(db.getUrl());
        dmDataSource.setUsername(db.getUser());
        dmDataSource.setPassword(db.getPassword());
        dmDataSource.setConnectionProperties(db.getConnectionProperties());
        dataSource = dmDataSource;//from w  ww  . ja va  2  s.c om

        if (db instanceof HsqlDbTest) {
            executeScript("/drop.sql", true);
            executeScript("/" + db.getSchemaName(), false);
        }
        databaseInitialized = true;
    }
}

From source file:cz.dasnet.dasik.Dasik.java

public Dasik() throws ConfigException {
    log.info("");
    log.info("Creating new bot instance ...");
    this.config = new Config();

    log.info("Setting up datasource ...");
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName(config.getProperty("datasource.driver", "com.mysql.jdbc.Driver"));
    ds.setUrl(config.getProperty("datasource.connection", "jdbc:mysql://localhost:3306/dasik"));
    ds.setUsername(config.getProperty("datasource.username", "root"));
    ds.setPassword(config.getProperty("datasource.password", "root"));
    dataSource = ds;/*  w w  w .  j a va  2  s .  com*/

    log.info("Creating User DAO ...");
    userDao = new UserDaoImpl(dataSource);

    log.info("Creating Learn DAO ...");
    learnDao = new LearnDaoImpl(dataSource);

    log.info("Loading channel list ...");
    String channs = config.getProperty("irc.channel.autojoin");
    if (channs != null) {
        for (String chan : channs.split("\\s+")) {
            String pass = config.getProperty("irc.channel.pass." + chan, "");
            channels.put(chan, pass);
        }
    }

    log.info("Initializing logger ...");
    chanlog = new ChannelLogger(config.getProperty("log.basepath", "logs"));
    channelListeners.put("@log", chanlog);

    log.info("Creating plugin loader ...");
    pluginLoader = new PluginLoader(this);

    log.info("Loading plugins ...");
    String commands = config.getProperty("command.autoload");
    if (commands != null) {
        plugins.addAll(Arrays.asList(commands.split("\\s+")));
    }

    Map<String, Plugin> loadedPlugins = pluginLoader.loadPlugins(plugins);
    channelListeners.putAll(loadedPlugins);

    log.info("Loading channel configs ...");
    for (String plugin : plugins) {
        String ignore = config.getProperty("command.ignoreOn." + plugin);
        if (ignore != null) {
            String[] chans = ignore.split("\\s+");
            for (String chan : chans) {
                ChannelConfig c = channelConfigs.get(chan);
                if (c == null) {
                    c = new ChannelConfig(chan);
                    channelConfigs.put(chan, c);
                }
                c.ignorePlugin(plugin);
            }
        }
    }

    log.info("Bot created");
}

From source file:com.company.project.config.DataConfig.java

@Bean(name = "dataSource")
public DataSource dataSource() {
    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    //        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    //        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/test");
    //        driverManagerDataSource.setUsername("root");
    //        driverManagerDataSource.setPassword("root");

    // fails during unit tests
    //        driverManagerDataSource.setDriverClassName(driverClassName);
    //        driverManagerDataSource.setUrl(url);
    //        driverManagerDataSource.setUsername(username);
    //        driverManagerDataSource.setPassword(password);

    driverManagerDataSource.setDriverClassName(env.getProperty("jdbc.driver"));
    driverManagerDataSource.setUrl(env.getProperty("jdbc.url"));
    driverManagerDataSource.setUsername(env.getProperty("jdbc.username"));
    driverManagerDataSource.setPassword(env.getProperty("jdbc.password"));

    // create a table and populate some data
    //JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    //System.out.println("Creating tables");
    //jdbcTemplate.execute("drop table users if exists");
    //jdbcTemplate.execute("create table users(id serial, firstName varchar(255), lastName varchar(255), email varchar(255))");
    //jdbcTemplate.update("INSERT INTO users(firstName, lastName, email) values (?,?,?)", "Mike", "Lanyon", "lanyonm@gmail.com");

    return driverManagerDataSource;
}

From source file:in.sc.dao.ProductHelper.java

public NamedParameterJdbcTemplate getTemplate() {
    if (namedParameterJdbcTemplate == null) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setSchema("smart_compare");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        //            dataSource.setPassword("rose@123");
        dataSource.setUrl("jdbc:mysql://localhost:3306/smart_compare");
        //            dataSource.setURL("jdbc:mysql://52.42.111.208:3033/smart_compare");
        namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }/*from  w w  w  .  j a va  2s.c o m*/
    return namedParameterJdbcTemplate;
}