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

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

Introduction

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

Prototype

public synchronized void setUsername(String username) 

Source Link

Document

Sets the #username .

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

Usage

From source file:com.plexobject.testplayer.dao.hibernate.GenericDaoHibernate.java

protected static DataSource _getDataSource() {
    BasicDataSource source = new BasicDataSource();
    source.setDriverClassName("org.hsqldb.jdbcDriver");
    source.setUrl("jdbc:hsqldb:file:testplayer.db");
    //source.setUrl("jdbc:hsqldb:hsql://localhost/testplayer");
    source.setUsername("sa");
    source.setPassword("");
    source.setMaxActive(15);//from  w  w  w.  j a v a2s .c  o  m
    source.setMaxIdle(4);
    return source;
}

From source file:com.aurel.track.dbase.DatabaseHandler.java

private static void checkForDatabase() {
    try {// ww  w .  j a  va2  s  . c om
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername(user);
        ds.setPassword(password);
        ds.setDriverClassName(getJdbcDriver());
        ds.setUrl(getJdbcUrl());
        testConnection();
        // createDatabaseInt(ds, fileNameSchema);
        System.out.println("Can access database");
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.cws.esolutions.core.listeners.CoreServiceInitializer.java

/**
 * Initializes the core service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar./*from w  w  w.  ja  v  a 2  s .c  om*/
 *
 * @param configFile - The service configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param loadSecurity - Flag to start security
 * @param startConnections - Flag to start connections
 * @throws CoreServiceException @{link com.cws.esolutions.core.exception.CoreServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean loadSecurity, final boolean startConnections) throws CoreServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfig secConfig = null;
    CoreConfigurationData configData = null;
    SecurityConfigurationData secConfigData = null;

    if (loadSecurity) {
        secConfigData = SecurityServiceBean.getInstance().getConfigData();
        secConfig = secConfigData.getSecurityConfig();
    }

    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("coreConfigFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("coreLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = CoreServiceInitializer.class.getClassLoader().getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(configFile).toURI().toURL();
        }

        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        CoreServiceInitializer.appBean.setConfigData(configData);

        if (startConnections) {
            Map<String, DataSource> dsMap = CoreServiceInitializer.appBean.getDataSources();

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            if (dsMap == null) {
                dsMap = new HashMap<String, DataSource>();
            }

            for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                if (!(dsMap.containsKey(mgr.getDsName()))) {
                    StringBuilder sBuilder = new StringBuilder()
                            .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                            .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                            .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                            .append("zeroDateTimeBehavior=convertToNull");

                    if (DEBUG) {
                        DEBUGGER.debug("StringBuilder: {}", sBuilder);
                    }

                    BasicDataSource dataSource = new BasicDataSource();
                    dataSource.setDriverClassName(mgr.getDriver());
                    dataSource.setUrl(mgr.getDataSource());
                    dataSource.setUsername(mgr.getDsUser());
                    dataSource.setConnectionProperties(sBuilder.toString());
                    dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getSalt(),
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            configData.getAppConfig().getEncoding()));
                    if (DEBUG) {
                        DEBUGGER.debug("BasicDataSource: {}", dataSource);
                    }

                    dsMap.put(mgr.getDsName(), dataSource);
                }
            }

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            CoreServiceInitializer.appBean.setDataSources(dsMap);
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new CoreServiceException(jx.getMessage(), jx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new CoreServiceException(mux.getMessage(), mux);
    }
}

From source file:com.util.conectividad.ConectorDB.java

public static Connection obtenerConexionBasica() {
    Connection conexion = null;//from  www  . ja va 2s. c o m
    BasicDataSource basicDataSource = null;
    try {
        basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        //            basicDataSource.setUrl("jdbc:oracle:thin:@192.168.21.241:1521/pdb1");// local
        basicDataSource.setUrl("jdbc:oracle:thin:@172.28.80.32:1525/INTERAT1");// local
        //            basicDataSource.setUsername("interacttdp");// local
        basicDataSource.setUsername("USR_INTERACT_APP");
        //            basicDataSource.setPassword("interacttdp99");// local
        basicDataSource.setPassword("RT87TY");
        basicDataSource.setInitialSize(5);
        basicDataSource.setMaxActive(2);
        conexion = basicDataSource.getConnection();

        return conexion;
    } catch (Exception e) {
        return conexion;
    } finally {
        basicDataSource = null;
        conexion = null;
    }
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceInitializer.java

/**
 * Initializes the security service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar./*w  ww . j a  v  a2 s  . co  m*/
 *
 * @param configFile - The security configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param startConnections - Configure, load and start repository connections
 * @throws SecurityServiceException @{link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean startConnections) throws SecurityServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ClassLoader classLoader = SecurityServiceInitializer.class.getClassLoader();
    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("configFileFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("secLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = classLoader.getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(serviceConfig).toURI().toURL();
        }

        context = JAXBContext.newInstance(SecurityConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

        SecurityServiceInitializer.svcBean.setConfigData(configData);

        if (startConnections) {
            DAOInitializer.configureAndCreateAuthConnection(
                    new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                    false, SecurityServiceInitializer.svcBean);

            Map<String, DataSource> dsMap = SecurityServiceInitializer.svcBean.getDataSources();

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            if (configData.getResourceConfig() != null) {
                if (dsMap == null) {
                    dsMap = new HashMap<String, DataSource>();
                }

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    if (!(dsMap.containsKey(mgr.getDsName()))) {
                        StringBuilder sBuilder = new StringBuilder()
                                .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                                .append("zeroDateTimeBehavior=convertToNull");

                        if (DEBUG) {
                            DEBUGGER.debug("StringBuilder: {}", sBuilder);
                        }

                        BasicDataSource dataSource = new BasicDataSource();
                        dataSource.setDriverClassName(mgr.getDriver());
                        dataSource.setUrl(mgr.getDataSource());
                        dataSource.setUsername(mgr.getDsUser());
                        dataSource.setConnectionProperties(sBuilder.toString());
                        dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getDsSalt(),
                                configData.getSecurityConfig().getSecretAlgorithm(),
                                configData.getSecurityConfig().getIterations(),
                                configData.getSecurityConfig().getKeyBits(),
                                configData.getSecurityConfig().getEncryptionAlgorithm(),
                                configData.getSecurityConfig().getEncryptionInstance(),
                                configData.getSystemConfig().getEncoding()));

                        if (DEBUG) {
                            DEBUGGER.debug("BasicDataSource: {}", dataSource);
                        }

                        dsMap.put(mgr.getDsName(), dataSource);
                    }
                }

                if (DEBUG) {
                    DEBUGGER.debug("dsMap: {}", dsMap);
                }

                SecurityServiceInitializer.svcBean.setDataSources(dsMap);
            }
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new SecurityServiceException(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        fnfx.printStackTrace();
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new SecurityServiceException(mux.getMessage(), mux);
    } catch (SecurityException sx) {
        sx.printStackTrace();
        throw new SecurityServiceException(sx.getMessage(), sx);
    }
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLDataSources.java

private static DataSource createDataSource(String host, int port, String user, String passwd, int poolSize,
        int maxWaitMillis, int socketTimeoutMillis) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource//from w w  w  . ja  v a 2s  . c  om
            .setUrl(String.format(
                    "jdbc:mysql://%s:%d?" + "connectTimeout=5000&" + "socketTimeout=%d&"
                            + "enableQueryTimeouts=false&" + "cachePrepStmts=true&" + "characterEncoding=UTF-8",
                    host, port, socketTimeoutMillis));
    dataSource.setUsername(user);
    dataSource.setPassword(passwd);
    dataSource.setDefaultAutoCommit(true);
    dataSource.setInitialSize(poolSize);
    dataSource.setMaxActive(poolSize);
    dataSource.setMaxIdle(poolSize);
    // deal with idle connection eviction
    dataSource.setValidationQuery("SELECT 1 FROM DUAL");
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTestWhileIdle(true);
    dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000);
    dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000);
    dataSource.setNumTestsPerEvictionRun(poolSize);
    // max wait in milliseconds for a connection.
    dataSource.setMaxWait(maxWaitMillis);
    // force connection pool initialization.
    Connection conn = null;
    try {
        // Here not getting the connection from ThreadLocal no need to worry about that.
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        LOG.error(String.format(
                "Failed to get a mysql connection when creating DataSource, " + "host: %s, port: %d", host,
                port), e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }
    return dataSource;
}

From source file:com.wso2.raspberrypi.Util.java

private static BasicDataSource getBasicDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://rss1.stratoslive.wso2.com/rpi_azeez_org");
    ds.setUsername("rpi_FHdBOhR3");
    ds.setPassword("wso2");
    ds.setValidationQuery("SELECT 1");
    return ds;/*from  w w  w  .  j  a  v a2 s.  c o  m*/
}

From source file:com.weibo.datasys.common.db.DBManager.java

/**
 * /*from w w w . j a  v  a2s .  co m*/
 * ?????
 * 
 * @param configData
 */
private static void initDataSource(CommonData configData) {
    String dsname = configData.getBaseField("dsname");

    BasicDataSource dataSource = new BasicDataSource();
    // ??
    dataSource.setDriverClassName(configData.getBaseField("driverClassName"));
    // ??
    dataSource.setUrl(configData.getBaseField("connectURL"));
    // ???
    dataSource.setUsername(configData.getBaseField("username"));
    dataSource.setPassword(configData.getBaseField("password"));
    // ?
    dataSource.setInitialSize(StringUtils.parseInt(configData.getBaseField("initialSize"), 1));
    // ?
    dataSource.setMinIdle(StringUtils.parseInt(configData.getBaseField("minIdle"), 1));
    // 
    dataSource.setMaxIdle(StringUtils.parseInt(configData.getBaseField("maxIdle"), 1));
    // 
    dataSource.setMaxActive(StringUtils.parseInt(configData.getBaseField("maxActive"), 1));
    // ?,?(ms)
    dataSource.setMaxWait(StringUtils.parseInt(configData.getBaseField("maxWait"), 1000));

    // ??
    dataSource.setTestWhileIdle(true);
    // ?sql?
    dataSource.setValidationQuery("select 'test'");
    // ?
    dataSource.setValidationQueryTimeout(5000);
    // 
    dataSource.setTimeBetweenEvictionRunsMillis(3600000);
    // ??
    dataSource.setMinEvictableIdleTimeMillis(3600000);

    dsMap.put(dsname, dataSource);

    logger.info("[InitDataSourceOK] - dsname={}", dsname);
}

From source file:com.alibaba.cobar.manager.qa.modle.CobarFactory.java

public static CobarAdapter getCobarAdapter(String cobarNodeName) throws IOException {
    CobarAdapter cAdapter = new CobarAdapter();
    Properties prop = new Properties();
    prop.load(CobarFactory.class.getClassLoader().getResourceAsStream("cobarNode.properties"));
    BasicDataSource ds = new BasicDataSource();
    String user = prop.getProperty(cobarNodeName + ".user").trim();
    String password = prop.getProperty(cobarNodeName + ".password").trim();
    String ip = prop.getProperty(cobarNodeName + ".ip").trim();
    int managerPort = Integer.parseInt(prop.getProperty(cobarNodeName + ".manager.port").trim());
    int maxActive = -1;
    int minIdle = 0;
    long timeBetweenEvictionRunsMillis = 10 * 60 * 1000;
    int numTestsPerEvictionRun = Integer.MAX_VALUE;
    long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
    ds.setUsername(user);
    ds.setPassword(password);/*from www  .ja va 2 s .c o m*/
    ds.setUrl(new StringBuilder().append("jdbc:mysql://").append(ip).append(":").append(managerPort).append("/")
            .toString());
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    ds.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    cAdapter.setDataSource(ds);
    return cAdapter;
}

From source file:net.sf.taverna.t2.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally.
 * The DataSource is named jdbc/taverna/*  w w  w.  ja v a  2  s.  c  o  m*/
 *
 * @param driverClassName - the classname for the driver to be used.
 * @param jdbcUrl - the jdbc connection url
 * @param username - the username, if required (otherwise null)
 * @param password - the password, if required (oteherwise null)
 * @param minIdle - if the driver supports multiple connections, then the minumum number of idle connections in the pool
 * @param maxIdle - if the driver supports multiple connections, then the maximum number of idle connections in the pool
 * @param maxActive - if the driver supports multiple connections, then the minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null) {
        ds.setUsername(username);
    }
    if (password != null) {
        ds.setPassword(password);
    }

    ds.setUrl(jdbcUrl);

    InitialContext context;
    try {
        context = new InitialContext();
        context.rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context: " + ex);
    }

}