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

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

Introduction

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

Prototype

public void setUsername(@Nullable String username) 

Source Link

Document

Set the JDBC username 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 {/*from  w  ww .ja  va 2s . c  o m*/
        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.security.util.ConfigurationHelper.java

private DataSource getDataSourceFromDocument(Document hibernateConfigDoc) throws CSConfigurationException {
    Element hbnConfigElement = hibernateConfigDoc.getRootElement();
    DataSource ds = null;/*w  ww  .j  a  v  a 2  s. c om*/
    org.jdom.Element urlProperty = null, usernameProperty = null, passwordProperty = null,
            driverProperty = null;
    try {
        org.jdom.Element dataSourceProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                "/hibernate-configuration//session-factory//property[@name='connection.datasource']");
        if (dataSourceProperty != null && dataSourceProperty.getTextTrim() != null) {
            try {
                InitialContext initialContext = new InitialContext();
                ds = (DataSource) initialContext.lookup(dataSourceProperty.getTextTrim());
            } catch (NamingException ex) {
                ex.printStackTrace();
                throw new CSConfigurationException();
            }
        } else {
            urlProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.url']");
            usernameProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.username']");
            passwordProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.password']");
            driverProperty = (org.jdom.Element) XPath.selectSingleNode(hibernateConfigDoc,
                    "/hibernate-configuration//session-factory//property[@name='connection.driver_class']");

            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(driverProperty.getTextTrim());
            dataSource.setUrl(urlProperty.getTextTrim());
            dataSource.setUsername(usernameProperty.getTextTrim());
            dataSource.setPassword(passwordProperty.getTextTrim());

            ds = dataSource;
        }
    } catch (JDOMException e) {
        e.printStackTrace();
        throw new CSConfigurationException();
    }
    return ds;
}

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

/**
 * Test the {@link QCLiveTestDataGenerator#setDccCommonDevJdbcTemplate(JdbcTemplate)} and 
 * {@link QCLiveTestDataGenerator#setDiseaseDevJdbcTemplate(JdbcTemplate)} methods with a {@link JdbcTemplate} instance
 * whose data source references a test account.
 * //  w w  w  .  j  av a2 s.  c o  m
 * <p>An {@link IllegalArgumentException} should be thrown indicating that test accounts are not allowed.
 */
@Test
public void testSetDevDataSourceWithTestAcct() {

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

    // Try setting the COMMON PRODUCTION JdbcTemplate for the QCLiveTestDataGenerator, should throw an IllegalArgumentException
    QCLiveTestDataGenerator qcLiveTestDataGenerator = new QCLiveTestDataGenerator();
    try {
        qcLiveTestDataGenerator.setDccCommonDevJdbcTemplate(jdbcTemplate);
    } catch (IllegalArgumentException iae) {
        assertEquals(
                "Test account 'test' is not permitted for database connection property 'dccCommonDevJdbcTemplate'",
                iae.getMessage());
    }

    // Try setting the DISEASE PRODUCTION JdbcTemplate for the QCLiveTestDataGenerator, should throw an IllegalArgumentException
    try {
        qcLiveTestDataGenerator.setDiseaseDevJdbcTemplate(jdbcTemplate);
    } catch (IllegalArgumentException iae) {
        assertEquals(
                "Test account 'test' is not permitted for database connection property 'diseaseDevJdbcTemplate'",
                iae.getMessage());
    }
}

From source file:com.unito.repository.JDBCConfig.java

@Bean
public DataSource dataSource() {
    DriverManagerDataSource driverManager = new DriverManagerDataSource();
    //driverManager.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    //driverManager.setDriverClassName(new org.apache.derby.jdbc.EmbeddedDriver());
    //driverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
    driverManager.setDriverClassName("com.mysql.jdbc.Driver");
    //create=true - start db derby server
    driverManager.setUrl("jdbc:mysql://podgoreanu.ddns.net:3306/mysql");
    driverManager.setUsername("root");
    driverManager.setPassword("645128");
    return driverManager;
}

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

/**
 * ?datasourceinfo ???// www  .  java 2s . com
 * 
 * @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: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  ww  w .  j a  v a2 s.co  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;//  w  w  w .  j av  a2  s  .  com

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

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 v  a2 s  . c  o m*/
    return namedParameterJdbcTemplate;
}

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;/*from   w  w  w. j  av  a  2 s. co  m*/

    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;
}