Example usage for org.apache.commons.dbcp BasicDataSource setPassword

List of usage examples for org.apache.commons.dbcp BasicDataSource setPassword

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setPassword.

Prototype

public synchronized void setPassword(String password) 

Source Link

Document

Sets the #password .

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:br.gov.frameworkdemoiselle.internal.proxy.BasicDataSourceProxy.java

private BasicDataSource getDelegate() {
    if (this.delegate == null) {
        BasicDataSource dataSource = new BasicDataSource();

        try {//from   w  w w. j  av  a  2  s .  co m
            String driver = config.getDriverClass().get(dataSourceName);
            String url = config.getUrl().get(dataSourceName);
            String username = config.getUsername().get(dataSourceName);
            String password = config.getPassword().get(dataSourceName);

            dataSource.setDriverClassName(driver);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);

        } catch (ClassCastException cause) {
            throw new DemoiselleException(bundle.getString("load-duplicated-configuration-failed"), cause);
        }

        delegate = dataSource;
    }

    return this.delegate;
}

From source file:edu.ucsf.vitro.opensocial.OpenSocialSmokeTests.java

/**
 * Check that we can connect to the database, and query one of the Shindig
 * tables.//from   ww  w  .  j  av a2s.  c  o  m
 */
private void checkDatabaseTables() {
    BasicDataSource dataSource = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(getProperty(PROPERTY_DB_DRIVER));
        dataSource.setUrl(getProperty(PROPERTY_DB_JDBC_URL));
        dataSource.setUsername(getProperty(PROPERTY_DB_USERNAME));
        dataSource.setPassword(getProperty(PROPERTY_DB_PASSWORD));

        conn = dataSource.getConnection();
        stmt = conn.createStatement();
        rset = stmt.executeQuery("select * from orng_apps");
    } catch (NoSuchPropertyException e) {
        warnings.add(new Warning(e.getMessage()));
    } catch (SQLException e) {
        if (e.getMessage().contains("doesn't exist")) {
            warnings.add(new Warning("The Shindig tables don't exist "
                    + "in the database. Was shindig_orng_tables.sql " + "run to set them up?", e));
        } else {
            warnings.add(new Warning("Can't access the Shindig database tables", e));
        }
    } finally {
        try {
            if (rset != null) {
                rset.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:ch.tatool.app.service.impl.UserAccountDAO.java

public void setAccountPassword(final UserAccountImpl account, final String password) {
    getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            // find the username
            BasicDataSource dataSource = (BasicDataSource) account.getBeanFactory()
                    .getBean("userAccountDataSource");
            String username = dataSource.getUsername();
            String newPassword = password != null ? password : "";
            //String driver = dataSource.getDriverClassName();

            // update the password using an alter user sql query (every db except mysql)
            try {
                StringBuilder sql = new StringBuilder();
                sql.append("ALTER USER '").append(username).append("' SET PASSWORD '").append(newPassword)
                        .append("'");

                SQLQuery query = session.createSQLQuery(sql.toString());
                query.executeUpdate();/*from  w w w.jav  a2s . c o m*/

                // update the current account object
                dataSource.setPassword(newPassword);
                account.setPassword(newPassword);
                account.setPasswordProtected(!newPassword.isEmpty());
            } catch (HibernateException hb) {
                //TODO: Add something
            }

            return null;
        }
    });
}

From source file:com.ibatis.common.jdbc.DbcpConfiguration.java

private BasicDataSource legacyDbcpConfiguration(Map map) {
    BasicDataSource basicDataSource = null;
    if (map.containsKey("JDBC.Driver")) {
        basicDataSource = new BasicDataSource();
        String driver = (String) map.get("JDBC.Driver");
        String url = (String) map.get("JDBC.ConnectionURL");
        String username = (String) map.get("JDBC.Username");
        String password = (String) map.get("JDBC.Password");
        String validationQuery = (String) map.get("Pool.ValidationQuery");
        String maxActive = (String) map.get("Pool.MaximumActiveConnections");
        String maxIdle = (String) map.get("Pool.MaximumIdleConnections");
        String maxWait = (String) map.get("Pool.MaximumWait");

        basicDataSource.setUrl(url);/* ww w .  ja  v  a2 s.  com*/
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUsername(username);
        basicDataSource.setPassword(password);

        if (notEmpty(validationQuery)) {
            basicDataSource.setValidationQuery(validationQuery);
        }

        if (notEmpty(maxActive)) {
            basicDataSource.setMaxActive(Integer.parseInt(maxActive));
        }

        if (notEmpty(maxIdle)) {
            basicDataSource.setMaxIdle(Integer.parseInt(maxIdle));
        }

        if (notEmpty(maxWait)) {
            basicDataSource.setMaxWait(Integer.parseInt(maxWait));
        }

        Iterator props = map.keySet().iterator();
        while (props.hasNext()) {
            String propertyName = (String) props.next();
            if (propertyName.startsWith(ADD_DRIVER_PROPS_PREFIX)) {
                String value = (String) map.get(propertyName);
                basicDataSource.addConnectionProperty(propertyName.substring(ADD_DRIVER_PROPS_PREFIX_LENGTH),
                        value);
            }
        }
    }
    return basicDataSource;
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * /*from   w w  w .  j  a v a  2s.c  o  m*/
 *
 * @param doPreparedStatement 
 * @return time taken
 * @throws PropertyVetoException 
 * @throws InterruptedException 
 * @throws SQLException 
 */
private DataSource multiThreadedDBCP(boolean doPreparedStatement)
        throws PropertyVetoException, InterruptedException, SQLException {
    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    if (doPreparedStatement) {
        cpds.setPoolPreparedStatements(true);
        cpds.setMaxOpenPreparedStatements(max_statement);
    }
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    return cpds;
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * /*  w w  w  .  j a  va 2s. com*/
 *
 * @return time taken
 * @throws SQLException
 */
private long singleDBCP() throws SQLException {
    // Start DBCP

    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    cpds.setMaxOpenPreparedStatements(max_statement);
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    cpds.getConnection(); // call to initialize possible lazy structures etc 

    long start = System.currentTimeMillis();
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        Connection conn = cpds.getConnection();
        conn.close();
    }
    long end = (System.currentTimeMillis() - start);
    //      System.out.println("DBCP Single thread benchmark: "+end);

    cpds.close();
    return end;

}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * Benchmarks PreparedStatement functionality (single thread) 
 * @return result//from w  w  w  .  j  a v  a2 s . c  o m
 * 
 * @throws PropertyVetoException
 * @throws SQLException
 */
private long testPreparedStatementSingleThreadDBCP() throws PropertyVetoException, SQLException {
    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    cpds.setPoolPreparedStatements(true);
    cpds.setMaxOpenPreparedStatements(30);
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    Connection conn = cpds.getConnection();

    long start = System.currentTimeMillis();
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        Statement st = conn.prepareStatement(TEST_QUERY);
        st.close();
    }
    conn.close();

    long end = (System.currentTimeMillis() - start);
    System.out.println("DBCP PreparedStatement Single thread benchmark: " + end);
    results.add("DBCP, " + end);
    // dispose of pool
    cpds.close();
    return end;
}

From source file:fi.ni.IFC_ClassModel.java

public void listRDF(OutputStream outputStream, String path, VirtConfig virt) throws IOException, SQLException {

    BufferedWriter out = null;//  w  ww .j  a  v  a2 s  . c o  m
    Connection c = null;
    String prefix_query = "PREFIX : <" + path + "> " + "PREFIX instances: <http://drum.cs.hut.fi/instances#> "
            + "PREFIX owl: <" + Namespace.OWL + "> " + "PREFIX ifc: <" + Namespace.IFC + "> " + "PREFIX xsd: <"
            + Namespace.XSD + "> " + "INSERT IN GRAPH <" + path + "> { ";

    try {
        //Setup file output
        out = new BufferedWriter(new OutputStreamWriter(outputStream));
        out.write("@prefix : <" + path + ">.\n");
        out.write("@prefix instances: <http://drum.cs.hut.fi/instances#>. \n");
        out.write("@prefix owl: <" + Namespace.OWL + "> .\n");
        out.write("@prefix ifc: <" + Namespace.IFC + "> .\n");
        out.write("@prefix xsd: <" + Namespace.XSD + "> .\n");
        out.write("\n");

        //If necessary, setup virtuoso connection
        if (virt != null) {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setUsername(virt.user);
            dataSource.setPassword(virt.password);
            dataSource.setUrl(virt.jdbc_uri);
            dataSource.setMaxActive(100);
            dataSource.setDriverClassName("virtuoso.jdbc4.Driver");
            c = dataSource.getConnection();
        }

        for (Map.Entry<Long, Thing> entry : object_buffer.entrySet()) {
            Thing gobject = entry.getValue();
            String triples = generateTriples(gobject);
            out.write(triples);

            if (virt != null) {
                Statement stmt = c.createStatement();
                StringBuilder queryString = new StringBuilder();
                queryString.append(prefix_query);
                queryString.append(triples);
                queryString.append("}");
                boolean more = stmt.execute("sparql " + queryString.toString());
                if (!more) {
                    System.err.println("INSERT failed.");
                }
                if (stmt != null)
                    stmt.close();
            }
        }

    } finally {
        if (out != null)
            out.close();
        if (c != null)
            c.close();
    }
}

From source file:net.firejack.platform.model.config.hibernate.HibernateFactoryBean.java

private void buildHibernateTransactionManager() {
    for (Map.Entry<String, Database> entry : databases.entrySet()) {
        String name = entry.getKey();
        Database database = entry.getValue();

        BasicDataSource dataSource = null;
        try {//  w w  w  . ja va2s  . co  m
            dataSource = context.getBean(name + HIBERNATE_DATA_SOURCE_SUFFIX, BasicDataSource.class);
        } catch (BeansException e) {
            logger.info("Manual Hibernate DataSource: " + name + HIBERNATE_DATA_SOURCE_SUFFIX
                    + " not found use default");
        }

        if (dataSource == null) {
            dataSource = defaultHibernate.getBean(HIBERNATE_DEFAULT_PREFIX + HIBERNATE_DATA_SOURCE_SUFFIX,
                    BasicDataSource.class);
            dataSource.setDriverClassName(database.type.getDriver());
            dataSource.setUrl(database.getUrl());
            dataSource.setUsername(database.getUsername());
            dataSource.setPassword(database.getPassword());
            dataSource.setValidationQuery(database.getType().getValidate());

            context.getBeanFactory().registerSingleton(name + HIBERNATE_DATA_SOURCE_SUFFIX, dataSource);
        }

        Properties properties = null;
        try {
            properties = context.getBean(name + HIBERNATE_PROPERTIES_SUFFIX, Properties.class);
        } catch (BeansException e) {
            logger.info("Manual Hibernate properties: " + name + HIBERNATE_PROPERTIES_SUFFIX
                    + " not found use default");
        }

        if (properties == null) {
            properties = defaultHibernate.getBean(HIBERNATE_DEFAULT_PREFIX + HIBERNATE_PROPERTIES_SUFFIX,
                    Properties.class);
            properties.put(Environment.DIALECT, database.getType().getDialect());

            context.getBeanFactory().registerSingleton(name + HIBERNATE_PROPERTIES_SUFFIX, properties);
        }

        SessionFactory sessionFactory = null;
        try {
            sessionFactory = context.getBean(name + HIBERNATE_SESSION_FACTORY_SUFFIX, SessionFactory.class);
        } catch (BeansException e) {
            logger.info("Manual Hibernate Session Factory: " + name + HIBERNATE_SESSION_FACTORY_SUFFIX
                    + " not found use default");
        }

        if (sessionFactory == null) {
            try {
                AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
                annotationSessionFactoryBean.setAnnotatedClasses(new Class[] { BaseEntityModel.class });
                annotationSessionFactoryBean.setDataSource(dataSource);
                annotationSessionFactoryBean.setHibernateProperties(properties);
                annotationSessionFactoryBean.setPackagesToScan(database.getScanPackages());
                annotationSessionFactoryBean.setNamingStrategy(new OpenFlameNamingStrategy(database.getType()));

                if (database.getType() == DatabaseName.MySQL || database.getType() == DatabaseName.MSSQL) {
                    annotationSessionFactoryBean.setLobHandler(new DefaultLobHandler());
                } else if (database.getType() == DatabaseName.Oracle) {
                    annotationSessionFactoryBean.setLobHandler(new OracleLobHandler());
                }

                disposableBeans.add(annotationSessionFactoryBean);
                annotationSessionFactoryBean.afterPropertiesSet();
                sessionFactory = annotationSessionFactoryBean.getObject();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }

        HibernateTemplate template = new HibernateTemplate();
        template.setSessionFactory(sessionFactory);

        context.getBeanFactory().registerSingleton(name + HIBERNATE_TEMPLATE_PREFIX, template);
        database.setHibernateSupport(template);
        logger.info("Initialize Hibernate support for stories: " + database);

        String beanName = name + HIBERNATE_TRANSACTION_MANAGER_SUFFIX;

        ConstructorArgumentValues values = new ConstructorArgumentValues();
        values.addGenericArgumentValue(sessionFactory);

        RootBeanDefinition definition = new RootBeanDefinition(HibernateTransactionManager.class);
        definition.setConstructorArgumentValues(values);
        registers.put(beanName, definition);

        Collection<HibernateSupport> stores = database.getStores();
        for (HibernateSupport store : stores) {
            targets.put(((Advised) store).getTargetClass(), beanName);
        }
    }
}

From source file:com.googlecode.wmbutil.jdbc.DataSourceLocator.java

/**
 * Looks up a named data source//from w  ww.  j  a v  a 2  s  .  c  o m
 * 
 * @param dataSourceName
 *            The name of the data source to look for
 * @return The data source
 * @throws RuntimeException
 *             If the configuration can not be loaded or the data source
 *             definition is missing
 */
public synchronized DataSource lookup(String dataSourceName) {
    BasicDataSource ds;
    if (dataSources.containsKey(dataSourceName)) {
        ds = (BasicDataSource) dataSources.get(dataSourceName);

        if (ds == null) {
            // we failed to create it earlier
            throw new RuntimeException("Failed to create data source");
        }
    } else {
        ds = new BasicDataSource();

        try {
            String driver = config.getProperty("jdbc." + dataSourceName + ".class");
            if (driver == null || driver.trim().length() == 0) {
                throw new RuntimeException("Lookup connections configuration file must contain a jdbc."
                        + dataSourceName + ".class value");
            } else {
                ds.setDriverClassName(driver);
            }

            String url = config.getProperty("jdbc." + dataSourceName + ".url");
            if (url == null || url.trim().length() == 0) {
                throw new RuntimeException("Lookup connections configuration file must contain a jdbc."
                        + dataSourceName + ".url value");
            } else {
                ds.setUrl(url);
            }

            String username = config.getProperty("jdbc." + dataSourceName + ".username");
            if (username == null || username.trim().length() == 0) {
                throw new RuntimeException("Lookup connections configuration file must contain a jdbc."
                        + dataSourceName + ".username value");
            } else {
                ds.setUsername(username);
            }

            ds.setPassword(config.getProperty("jdbc." + dataSourceName + ".password"));
            ds.setDefaultReadOnly(true);

            dataSources.put(dataSourceName, ds);
        } catch (RuntimeException e) {
            // mark failed to create
            dataSources.put(dataSourceName, null);
            throw e;
        }
    }

    return ds;

}