List of usage examples for org.apache.commons.dbcp BasicDataSource setInitialSize
public synchronized void setInitialSize(int initialSize)
Sets the initial size of the connection pool.
Note: this method currently has no effect once the pool has been initialized.
From source file:cn.com.sims.crawler.util.JDBCHelper.java
public static JdbcTemplate createMysqlTemplate(String templateName, String url, String username, String password, int initialSize, int maxActive) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl(url);//from w ww . j a va 2s . com dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setInitialSize(initialSize); dataSource.setMaxActive(maxActive); JdbcTemplate template = new JdbcTemplate(dataSource); templateMap.put(templateName, template); return template; }
From source file:com.devwebsphere.jdbc.loader.JDBCTxCallback.java
public synchronized static DataSource setupDataSource(String connectURI, String user, String password) { String key = connectURI + ":" + user + ":" + password; DataSource rc = dataSourceList.get(key); if (rc == null) { ////from w w w .j a v a 2 s. c o m // First, we'll need a ObjectPool that serves as the // actual pool of connections. // // We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. // BasicDataSource bds = new BasicDataSource(); bds.setInitialSize(5); bds.setUrl(connectURI); bds.setUsername(user); bds.setPassword(password); bds.setPoolPreparedStatements(true); rc = bds; dataSourceList.put(key, bds); } return rc; }
From source file:com.weibo.datasys.parser.sql.DBConnectionFactory.java
public static void init() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(ConfigFactory.getString("jdbc.driverClassName")); dataSource.setUrl(ConfigFactory.getString("jdbc.url")); dataSource.setUsername(ConfigFactory.getString("jdbc.username")); dataSource.setPassword(ConfigFactory.getString("jdbc.password")); dataSource.setInitialSize(ConfigFactory.getInt("jdbc.initialSize", 1)); dataSource.setMinIdle(ConfigFactory.getInt("jdbc.minIdle", 2)); dataSource.setMaxIdle(ConfigFactory.getInt("jdbc.maxIdle", 10)); dataSource.setMaxWait(ConfigFactory.getInt("jdbc.maxWait", 1000)); dataSource.setMaxActive(ConfigFactory.getInt("jdbc.maxActive", 2)); dataSource.addConnectionProperty("autoReconnect", "true"); // ??//from ww w . ja va2 s.co m dataSource.setTestWhileIdle(true); // ?sql? dataSource.setValidationQuery("select 'test'"); // ? dataSource.setValidationQueryTimeout(5000); // dataSource.setTimeBetweenEvictionRunsMillis(3600000); // ?? dataSource.setMinEvictableIdleTimeMillis(3600000); ds = dataSource; }
From source file:com.gs.obevo.db.impl.core.jdbc.JdbcDataSourceFactory.java
private static DataSource createFromJdbcUrl(Class<? extends Driver> driverClass, String url, Credential credential, int numThreads, ImmutableList<String> initSqls, Properties extraConnectionProperties) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverClass.getName()); dataSource.setUrl(url);/*w w w . j a va 2 s.c o m*/ dataSource.setUsername(credential.getUsername()); dataSource.setPassword(credential.getPassword()); // connection pool settings dataSource.setInitialSize(numThreads); dataSource.setMaxActive(numThreads); // keep the connections open if possible; only close them via the removeAbandonedTimeout feature dataSource.setMaxIdle(numThreads); dataSource.setMinIdle(0); dataSource.setRemoveAbandonedTimeout(300); dataSource.setConnectionInitSqls(initSqls.castToList()); if (extraConnectionProperties != null) { for (String key : extraConnectionProperties.stringPropertyNames()) { dataSource.addConnectionProperty(key, extraConnectionProperties.getProperty(key)); } } return dataSource; }
From source file:net.certifi.audittablegen.HsqldbDMR.java
/** * Generate a Hsqldb DataSource from Properties * * @param props/*w w w . j a va 2s .com*/ * @return BasicDataSource as DataSource */ static DataSource getRunTimeDataSource(Properties props) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUsername(props.getProperty("username")); dataSource.setPassword(props.getProperty("password")); dataSource.setUrl(props.getProperty("url")); dataSource.setMaxActive(10); dataSource.setMaxIdle(5); dataSource.setInitialSize(5); dataSource.setAccessToUnderlyingConnectionAllowed(true); dataSource.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS"); return dataSource; }
From source file:com.pinterest.deployservice.db.DatabaseUtil.java
/** * Create a MySQL datasource.//from w w w .ja va 2 s.c o m * * @param url the url of the DB. * @param user the user name to connect to MySQL as. * @param passwd the password for the corresponding MySQL user. * @param poolSize the connection pool size string, in the format of * initialSize:maxActive:maxIdle:minIdle. * @param maxWaitInMillis the max wait time in milliseconds to get a connection from the pool. * @return a BasicDataSource for the target MySQL instance. */ public static BasicDataSource createDataSource(String driverClassName, String url, String user, String passwd, String poolSize, int maxWaitInMillis) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(user); dataSource.setPassword(passwd); dataSource.setDefaultAutoCommit(true); dataSource.setDefaultReadOnly(false); // poolSize parsing, the poolsize string passed in the following format // initialSize:maxActive:maxIdle:minIdle String[] sizeStrs = poolSize.split(":"); dataSource.setInitialSize(Integer.parseInt(sizeStrs[0])); dataSource.setMaxActive(Integer.parseInt(sizeStrs[1])); dataSource.setMaxIdle(Integer.parseInt(sizeStrs[2])); dataSource.setMinIdle(Integer.parseInt(sizeStrs[3])); dataSource.setValidationQuery("SELECT 1"); dataSource.setTestOnBorrow(true); dataSource.setTestOnReturn(false); dataSource.setTestWhileIdle(true); dataSource.setMinEvictableIdleTimeMillis(5 * 60 * 1000); dataSource.setTimeBetweenEvictionRunsMillis(3 * 60 * 1000); // dataSource.setNumTestsPerEvictionRun(3); // max wait in milliseconds for a connection. dataSource.setMaxWait(maxWaitInMillis); // 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 db connection when creating DataSource, url = %s", url), e); } finally { DbUtils.closeQuietly(conn); } return dataSource; }
From source file:com.cws.esolutions.security.utils.DAOInitializer.java
/** * @param properties - The <code>AuthRepo</code> object containing connection information * @param isContainer - A <code>boolean</code> flag indicating if this is in a container * @param bean - The {@link com.cws.esolutions.security.SecurityServiceBean} <code>SecurityServiceBean</code> that holds the connection * @throws SecurityServiceException {@link com.cws.esolutions.security.exception.SecurityServiceException} * if an exception occurs opening the connection */// w w w . j a v a 2s . c om public synchronized static void configureAndCreateAuthConnection(final InputStream properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException { String methodName = DAOInitializer.CNAME + "#configureAndCreateAuthConnection(final String properties, final boolean isContainer, final SecurityServiceBean bean) throws SecurityServiceException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("InputStream: {}", properties); DEBUGGER.debug("isContainer: {}", isContainer); DEBUGGER.debug("SecurityServiceBean: {}", bean); } try { Properties connProps = new Properties(); connProps.load(properties); if (DEBUG) { DEBUGGER.debug("Properties: {}", connProps); } AuthRepositoryType repoType = AuthRepositoryType .valueOf(connProps.getProperty(DAOInitializer.REPO_TYPE)); RepositoryConnectionType connType = RepositoryConnectionType .valueOf(connProps.getProperty(DAOInitializer.CONN_TYPE)); if (DEBUG) { DEBUGGER.debug("AuthRepositoryType: {}", repoType); DEBUGGER.debug("RepositoryConnectionType: {}", connType); } switch (repoType) { case LDAP: SSLUtil sslUtil = null; LDAPConnection ldapConn = null; LDAPConnectionPool connPool = null; LDAPConnectionOptions connOpts = new LDAPConnectionOptions(); connOpts.setAutoReconnect(true); connOpts.setAbandonOnTimeout(true); connOpts.setBindWithDNRequiresPassword(true); connOpts.setConnectTimeoutMillis( Integer.parseInt(connProps.getProperty(DAOInitializer.CONN_TIMEOUT))); connOpts.setResponseTimeoutMillis( Integer.parseInt(connProps.getProperty(DAOInitializer.READ_TIMEOUT))); if (DEBUG) { DEBUGGER.debug("LDAPConnectionOptions: {}", connOpts); } switch (connType) { case CONNECTION_TYPE_INSECURE: ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST), Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT))); if (DEBUG) { DEBUGGER.debug("LDAPConnection: {}", ldapConn); } if (!(ldapConn.isConnected())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } connPool = new LDAPConnectionPool(ldapConn, Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)), Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS))); break; case CONNECTION_TYPE_SSL: sslUtil = new SSLUtil(new TrustStoreTrustManager( connProps.getProperty(DAOInitializer.TRUST_FILE), PasswordUtils .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS), connProps.getProperty(DAOInitializer.TRUST_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()) .toCharArray(), connProps.getProperty(DAOInitializer.TRUST_TYPE), true)); if (DEBUG) { DEBUGGER.debug("SSLUtil: {}", sslUtil); } SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory(); if (DEBUG) { DEBUGGER.debug("SSLSocketFactory: {}", sslSocketFactory); } ldapConn = new LDAPConnection(sslSocketFactory, connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST), Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT))); if (DEBUG) { DEBUGGER.debug("LDAPConnection: {}", ldapConn); } if (!(ldapConn.isConnected())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } connPool = new LDAPConnectionPool(ldapConn, Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)), Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS))); break; case CONNECTION_TYPE_TLS: ldapConn = new LDAPConnection(connOpts, connProps.getProperty(DAOInitializer.REPOSITORY_HOST), Integer.parseInt(connProps.getProperty(DAOInitializer.REPOSITORY_PORT))); if (DEBUG) { DEBUGGER.debug("LDAPConnection: {}", ldapConn); } if (!(ldapConn.isConnected())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } sslUtil = new SSLUtil(new TrustStoreTrustManager( connProps.getProperty(DAOInitializer.TRUST_FILE), PasswordUtils .decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS), connProps.getProperty(DAOInitializer.TRUST_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()) .toCharArray(), connProps.getProperty(DAOInitializer.TRUST_TYPE), true)); if (DEBUG) { DEBUGGER.debug("SSLUtil: {}", sslUtil); } SSLContext sslContext = sslUtil.createSSLContext(); if (DEBUG) { DEBUGGER.debug("SSLContext: {}", sslContext); } StartTLSExtendedRequest startTLS = new StartTLSExtendedRequest(sslContext); if (DEBUG) { DEBUGGER.debug("StartTLSExtendedRequest: {}", startTLS); } ExtendedResult extendedResult = ldapConn.processExtendedOperation(startTLS); if (DEBUG) { DEBUGGER.debug("ExtendedResult: {}", extendedResult); } BindRequest bindRequest = new SimpleBindRequest( connProps.getProperty(DAOInitializer.REPOSITORY_USER), PasswordUtils.decryptText(connProps.getProperty(DAOInitializer.TRUST_PASS), connProps.getProperty(DAOInitializer.TRUST_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding())); if (DEBUG) { DEBUGGER.debug("BindRequest: {}", bindRequest); } BindResult bindResult = ldapConn.bind(bindRequest); if (DEBUG) { DEBUGGER.debug("BindResult: {}", bindResult); } StartTLSPostConnectProcessor tlsProcessor = new StartTLSPostConnectProcessor(sslContext); if (DEBUG) { DEBUGGER.debug("StartTLSPostConnectProcessor: {}", tlsProcessor); } connPool = new LDAPConnectionPool(ldapConn, Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS)), Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS)), tlsProcessor); break; } if (DEBUG) { DEBUGGER.debug("LDAPConnectionPool: {}", connPool); } if ((connPool == null) || (connPool.isClosed())) { throw new LDAPException(ResultCode.CONNECT_ERROR, "Failed to establish an LDAP connection"); } bean.setAuthDataSource(connPool); break; case SQL: // the isContainer only matters here if (isContainer) { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup(DAOInitializer.DS_CONTEXT); bean.setAuthDataSource(envContext.lookup(DAOInitializer.REPOSITORY_HOST)); } else { BasicDataSource dataSource = new BasicDataSource(); dataSource.setInitialSize( Integer.parseInt(connProps.getProperty(DAOInitializer.MIN_CONNECTIONS))); dataSource .setMaxActive(Integer.parseInt(connProps.getProperty(DAOInitializer.MAX_CONNECTIONS))); dataSource.setDriverClassName(connProps.getProperty(DAOInitializer.CONN_DRIVER)); dataSource.setUrl(connProps.getProperty(DAOInitializer.REPOSITORY_HOST)); dataSource.setUsername(connProps.getProperty(DAOInitializer.REPOSITORY_USER)); dataSource.setPassword(PasswordUtils.decryptText( connProps.getProperty(DAOInitializer.REPOSITORY_PASS), connProps.getProperty(DAOInitializer.REPOSITORY_SALT), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding())); bean.setAuthDataSource(dataSource); } break; case NONE: return; default: throw new SecurityServiceException("Unhandled ResourceType"); } } catch (LDAPException lx) { throw new SecurityServiceException(lx.getMessage(), lx); } catch (GeneralSecurityException gsx) { throw new SecurityServiceException(gsx.getMessage(), gsx); } catch (NamingException nx) { throw new SecurityServiceException(nx.getMessage(), nx); } catch (FileNotFoundException fnfx) { throw new SecurityServiceException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new SecurityServiceException(iox.getMessage(), iox); } }
From source file:com.util.conectividad.ConectorDB.java
public static Connection obtenerConexionBasica() { Connection conexion = null;/* w w w . j a v a 2s . com*/ 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.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/* w ww . j a v a 2 s . c o m*/ .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.weibo.datasys.common.db.DBManager.java
/** * // w w w . jav a 2s. c om * ????? * * @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); }