List of usage examples for org.apache.commons.pool2.impl GenericObjectPoolConfig setTestOnBorrow
public void setTestOnBorrow(boolean testOnBorrow)
From source file:ddf.ldap.ldaplogin.LdapLoginConfig.java
private GenericObjectPoolConfig createGenericPoolConfig(String id) { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setJmxNameBase("org.apache.commons.pool2:type=LDAPConnectionPool,name="); config.setJmxNamePrefix(id);/*from w ww . j av a 2 s .c o m*/ config.setTimeBetweenEvictionRunsMillis(FIVE_MIN_MS); config.setTestWhileIdle(true); config.setTestOnBorrow(true); return config; }
From source file:com.zxy.commons.redis.RedisClusterFactory.java
private RedisClusterFactory() { GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxIdle(RedisPropUtils.getMaxIdle()); poolConfig.setMinIdle(RedisPropUtils.getMinIdle()); poolConfig.setMaxTotal(RedisPropUtils.getMaxTotal()); poolConfig.setMaxWaitMillis(RedisPropUtils.getMaxWaitMillis()); poolConfig.setTimeBetweenEvictionRunsMillis(RedisPropUtils.getTimeBetweenEvictionRunsMillis()); poolConfig.setMinEvictableIdleTimeMillis(RedisPropUtils.getMinEvictableIdleTimeMillis()); poolConfig.setTestWhileIdle(RedisPropUtils.getTestWhileIdle()); poolConfig.setTestOnBorrow(RedisPropUtils.getTestOnBorrow()); int timeout = RedisPropUtils.getTimeout(); Set<HostAndPort> haps = parseHostAndPort(); int maxRedirections = RedisPropUtils.getMaxRedirections(); if (maxRedirections <= 0) { maxRedirections = 5;//w w w .ja v a2 s.c om } jedisCluster = new JedisCluster(haps, timeout, maxRedirections, poolConfig); }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java
@Override public void init() throws ServletException { // Set the projects properties. // First look for a system property pointing to a project properties file. // This value can be either a file path, file protocol (e.g. - file:/path/to/file), // or a URL (http://some/server/file). // If this value either does not exist or is not valid, the default // file that comes with this application will be used for initialization. String environmentProjectPropsFile = System.getProperty(ENV_PROJECT_PROPS); logger.info("Value of environment property: [{}] for finding external properties file in location: {}", ENV_PROJECT_PROPS, environmentProjectPropsFile); if (environmentProjectPropsFile != null) { logger.info("Will look for properties file from environment in location: {}", environmentProjectPropsFile); try {/*from www. j a va2s. c om*/ File projectProperties = new File(environmentProjectPropsFile); if (projectProperties.exists() && projectProperties.isFile() && projectProperties.canRead()) { InputStream is = new FileInputStream(projectProperties); applicationProps = new Properties(); applicationProps.load(is); } } catch (IOException e) { // fall back to default file logger.error("Unable to load properties file: {} -- reason: {}", environmentProjectPropsFile, e.getMessage()); logger.error("Falling back to default project.properties file: {}", PROPERTIES_FILE_NAME); applicationProps = null; } } if (applicationProps == null) { // did not load from environment variable location try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream resourceStream = classLoader.getResourceAsStream(PROPERTIES_FILE_NAME); if (resourceStream != null) { applicationProps = new Properties(); applicationProps.load(resourceStream); logger.info("loaded default applicationProps"); } else { logger.warn("project.properties not found!!!"); } } catch (IOException e) { logger.error("Could not load properties file: {}", PROPERTIES_FILE_NAME, e); // couldn't load default properties so bail... throw new ServletException("Couldn't load an applications properties file.", e); } } int maxPoolSize = Integer .valueOf(applicationProps.getProperty("max.objects.in.pool", DEFAULT_MAX_OBJECTS_IN_POOL)); long maxFileUploadSizeMb = Long .valueOf(applicationProps.getProperty("max.upload.file.size.MB", DEFAULT_MAX_UPLOAD_SIZE)); long maxRequestSizeMb = Long .valueOf(applicationProps.getProperty("max.request.size.MB", DEFAULT_MAX_REQUEST_SIZE)); maxInMemoryFileSizeMb = Integer .valueOf(applicationProps.getProperty("max.in.memory.file.size.MB", DEFAULT_IN_MEMORY_FILE_SIZE)); logger.info( "Max objects in object pool: {} -- Max file upload size: {}MB -- Max request object size: {}MB -- Max in-memory file size: {}MB", maxPoolSize, maxFileUploadSizeMb, maxRequestSizeMb, maxInMemoryFileSizeMb); logger.debug("Initializing PdfaConverter pool"); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMinIdle(MIN_IDLE_OBJECTS_IN_POOL); poolConfig.setMaxTotal(maxPoolSize); poolConfig.setTestOnBorrow(true); poolConfig.setBlockWhenExhausted(true); pdfaConverterWrapperPool = new PdfaConverterWrapperPool(new PdfaConverterWrapperFactory(), poolConfig); // configures upload settings factory = new DiskFileItemFactory(); factory.setSizeThreshold((maxInMemoryFileSizeMb * (int) MB_MULTIPLIER)); File tempUploadDir = new File(System.getProperty(UPLOAD_DIRECTORY)); if (!tempUploadDir.exists()) { tempUploadDir.mkdir(); } factory.setRepository(tempUploadDir); upload = new ServletFileUpload(factory); upload.setFileSizeMax(maxFileUploadSizeMb * MB_MULTIPLIER); // convert from MB to bytes upload.setSizeMax(maxRequestSizeMb * MB_MULTIPLIER); // convert from MB to bytes logger.debug("PdfaConverter pool finished Initializing"); }
From source file:com.escframework.support.dubbo.RedisRegistry.java
public RedisRegistry(URL url) { super(url);/* www .j a v a 2 s . co m*/ if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); config.setTestOnReturn(url.getParameter("test.on.return", false)); config.setTestWhileIdle(url.getParameter("test.while.idle", false)); if (url.getParameter("max.idle", 0) > 0) config.setMaxIdle(url.getParameter("max.idle", 0)); if (url.getParameter("min.idle", 0) > 0) config.setMinIdle(url.getParameter("min.idle", 0)); if (url.getParameter("max.active", 0) > 0) config.setMaxTotal(url.getParameter("max.total", 0)); if (url.getParameter("max.wait", url.getParameter("timeout", 0)) > 0) config.setMaxWaitMillis(url.getParameter("max.wait", url.getParameter("timeout", 0))); if (url.getParameter("num.tests.per.eviction.run", 0) > 0) config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0)); if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0)); if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0)); String cluster = url.getParameter("cluster", "failover"); if (!"failover".equals(cluster) && !"replicate".equals(cluster)) { throw new IllegalArgumentException("Unsupported redis cluster: " + cluster + ". The redis cluster only supported failover or replicate."); } replicate = "replicate".equals(cluster); List<String> addresses = new ArrayList<String>(); addresses.add(url.getAddress()); String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]); if (backups != null && backups.length > 0) { addresses.addAll(Arrays.asList(backups)); } for (String address : addresses) { int i = address.indexOf(':'); String host; int port; if (i > 0) { host = address.substring(0, i); port = Integer.parseInt(address.substring(i + 1)); } else { host = address; port = DEFAULT_REDIS_PORT; } this.jedisPools.put(address, new JedisPool(config, host, port, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT))); } this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD); String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); if (!group.startsWith(Constants.PATH_SEPARATOR)) { group = Constants.PATH_SEPARATOR + group; } if (!group.endsWith(Constants.PATH_SEPARATOR)) { group = group + Constants.PATH_SEPARATOR; } this.root = group; this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT); this.expireFuture = expireExecutor.scheduleWithFixedDelay(new Runnable() { public void run() { try { deferExpired(); // } catch (Throwable t) { // logger.error("Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t); } } }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS); }
From source file:com.heliosapm.streams.collector.ds.AbstractDataSourceFactory.java
/** * Reads the generic object pool configuration from the passed JSONObject * @param jsonConfig The json configuration for the current data source * @return the pool config/* w w w . j av a 2 s .co m*/ */ protected GenericObjectPoolConfig getPoolConfig(final JsonNode jsonConfig) { if (jsonConfig == null) throw new IllegalArgumentException("The passed JSONObject was null"); final GenericObjectPoolConfig config = new GenericObjectPoolConfig(); if (jsonConfig.has("maxPoolSize")) config.setMaxTotal(jsonConfig.get("maxPoolSize").intValue()); if (jsonConfig.has("maxPoolIdle")) config.setMaxIdle(jsonConfig.get("maxPoolIdle").intValue()); if (jsonConfig.has("minPoolIdle")) config.setMinIdle(jsonConfig.get("minPoolIdle").intValue()); if (jsonConfig.has("registerMbeans")) config.setJmxEnabled(jsonConfig.get("registerMbeans").booleanValue()); if (jsonConfig.has("fair")) config.setFairness(jsonConfig.get("fair").booleanValue()); if (jsonConfig.has("lifo")) config.setLifo(jsonConfig.get("lifo").booleanValue()); if (jsonConfig.has("maxWait")) config.setMaxWaitMillis(jsonConfig.get("maxWait").longValue()); final boolean testWhileIdle; if (jsonConfig.has("testWhileIdle")) { testWhileIdle = jsonConfig.get("testWhileIdle").booleanValue(); } else { testWhileIdle = false; } if (testWhileIdle) { config.setTestWhileIdle(true); long testPeriod = 15000; if (jsonConfig.has("testPeriod")) { testPeriod = jsonConfig.get("testPeriod").longValue(); } config.setTimeBetweenEvictionRunsMillis(testPeriod); } else { config.setTestWhileIdle(false); } // ALWAYS test on borrow config.setTestOnBorrow(true); config.setTestOnCreate(true); config.setTestOnReturn(false); return config; }
From source file:com.yahoo.athenz.common.server.db.DataSourceFactory.java
public static GenericObjectPoolConfig setupPoolConfig() { // setup config vars for the object pool // ie. min and max idle instances, and max total instances of arbitrary objects GenericObjectPoolConfig config = new GenericObjectPoolConfig(); // The maximum number of active connections that can be allocated from // this pool at the same time, or negative for no limit. Default: 8 config.setMaxTotal(//from ww w. j a va 2 s . c om retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TOTAL, GenericObjectPoolConfig.DEFAULT_MAX_TOTAL)); if (config.getMaxTotal() == 0) { config.setMaxTotal(-1); // -1 means no limit } // The maximum number of connections that can remain idle in the pool, // without extra ones being released, or negative for no limit. Default 8 config.setMaxIdle( retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_IDLE, GenericObjectPoolConfig.DEFAULT_MAX_IDLE)); if (config.getMaxIdle() == 0) { config.setMaxIdle(-1); // -1 means no limit } // The minimum number of connections that can remain idle in the pool, // without extra ones being created, or zero to create none. Default 0 config.setMinIdle( retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MIN_IDLE, GenericObjectPoolConfig.DEFAULT_MIN_IDLE)); // The maximum number of milliseconds that the pool will wait (when // there are no available connections) for a connection to be returned // before throwing an exception, or -1 to wait indefinitely. Default -1 config.setMaxWaitMillis(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_WAIT, GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS)); // setup the configuration to cleanup idle connections // // Minimum time an object can be idle in the pool before being eligible // for eviction by the idle object evictor. // The default value is 30 minutes (1000 * 60 * 30). config.setMinEvictableIdleTimeMillis(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_EVICT_IDLE_TIMEOUT, BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS)); // Number of milliseconds to sleep between runs of idle object evictor thread. // Not using DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS since it is -1 // meaning it will not run the evictor thread and instead we're using // the default min value for evictable idle connections (Default 30 minutes) config.setTimeBetweenEvictionRunsMillis(retrieveConfigSetting(ATHENZ_PROP_DBPOOL_EVICT_IDLE_INTERVAL, BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS)); if (LOG.isDebugEnabled()) { LOG.debug("Config settings for idle object eviction: " + "time interval between eviction thread runs (" + config.getTimeBetweenEvictionRunsMillis() + " millis): minimum timeout for idle objects (" + config.getMinEvictableIdleTimeMillis() + " millis)"); } // Validate objects by the idle object evictor. If invalid, gets dropped // from the pool. config.setTestWhileIdle(true); // Validate object before borrowing from pool. If invalid, gets dropped // from the pool and an attempt to borrow another one will occur. config.setTestOnBorrow(true); return config; }
From source file:net.uiqui.oblivion.mercury.io.ConnectionPool.java
private static GenericObjectPoolConfig getDefaultConfig() { final GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMinIdle(1);/*from w w w. j av a 2 s . c o m*/ config.setTestOnBorrow(true); return config; }
From source file:net.ymate.platform.persistence.redis.impl.RedisModuleCfg.java
@SuppressWarnings("unchecked") protected RedisDataSourceCfgMeta __doParserDataSourceCfgMeta(String dsName, Map<String, String> _moduleCfgs) throws Exception { RedisDataSourceCfgMeta _meta = null; ////ww w.j a va2s . co m Map<String, String> _dataSourceCfgs = __doGetCfgs(_moduleCfgs, "ds." + dsName + "."); // // if (!_dataSourceCfgs.isEmpty()) { String _connectionType = StringUtils.defaultIfBlank(_dataSourceCfgs.get("connection_type"), "default"); String _masterServerName = StringUtils.defaultIfBlank(_dataSourceCfgs.get("master_server_name"), "default"); List<ServerMeta> _servers = new ArrayList<ServerMeta>(); String[] _serverNames = StringUtils .split(StringUtils.defaultIfBlank(_dataSourceCfgs.get("server_name_list"), "default"), "|"); Map<String, String> _tmpCfgs = null; if (_serverNames != null) { for (String _serverName : _serverNames) { _tmpCfgs = __doGetCfgs(_dataSourceCfgs, "server." + _serverName + "."); if (!_tmpCfgs.isEmpty()) { ServerMeta _servMeta = new ServerMeta(); _servMeta.setName(_serverName); _servMeta.setHost(StringUtils.defaultIfBlank(_tmpCfgs.get("host"), "localhost")); _servMeta.setPort( BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("port"), "6379")).toIntValue()); _servMeta.setTimeout(BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("timeout"), "2000")).toIntValue()); _servMeta.setWeight( BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("weight"), "1")).toIntValue()); _servMeta.setDatabase(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("database"), "0")) .toIntValue()); _servMeta.setClientName(StringUtils.trimToNull(_tmpCfgs.get("client_name"))); _servMeta.setPassword(StringUtils.trimToNull(_tmpCfgs.get("password"))); // boolean _pwdEncrypted = new BlurObject(_tmpCfgs.get("password_encrypted")).toBooleanValue(); // if (_pwdEncrypted && StringUtils.isNotBlank(_servMeta.getPassword()) && StringUtils.isNotBlank(_tmpCfgs.get("password_class"))) { IPasswordProcessor _proc = ClassUtils.impl(_dataSourceCfgs.get("password_class"), IPasswordProcessor.class, this.getClass()); if (_proc != null) { _servMeta.setPassword(_proc.decrypt(_servMeta.getPassword())); } } // _servers.add(_servMeta); } } } // GenericObjectPoolConfig _poolConfig = new GenericObjectPoolConfig(); _tmpCfgs = __doGetCfgs(_dataSourceCfgs, "pool."); if (!_tmpCfgs.isEmpty()) { _poolConfig.setMinIdle(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("min_idle"), GenericObjectPoolConfig.DEFAULT_MIN_IDLE + "")).toIntValue()); _poolConfig.setMaxIdle(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_idle"), GenericObjectPoolConfig.DEFAULT_MAX_IDLE + "")).toIntValue()); _poolConfig.setMaxTotal(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_total"), GenericObjectPoolConfig.DEFAULT_MAX_TOTAL + "")).toIntValue()); _poolConfig .setBlockWhenExhausted( BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("block_when_exhausted"), GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED + "")) .toBooleanValue()); _poolConfig.setFairness(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("fairness"), GenericObjectPoolConfig.DEFAULT_FAIRNESS + "")).toBooleanValue()); _poolConfig.setJmxEnabled(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_enabled"), GenericObjectPoolConfig.DEFAULT_JMX_ENABLE + "")).toBooleanValue()); _poolConfig.setJmxNameBase(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_name_base"), GenericObjectPoolConfig.DEFAULT_JMX_NAME_BASE)); _poolConfig.setJmxNamePrefix(StringUtils.defaultIfBlank(_tmpCfgs.get("jmx_name_prefix"), GenericObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX)); _poolConfig.setEvictionPolicyClassName( StringUtils.defaultIfBlank(_tmpCfgs.get("eviction_policy_class_name"), GenericObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME)); _poolConfig.setLifo(BlurObject.bind( StringUtils.defaultIfBlank(_tmpCfgs.get("lifo"), GenericObjectPoolConfig.DEFAULT_LIFO + "")) .toBooleanValue()); _poolConfig.setMaxWaitMillis(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("max_wait_millis"), GenericObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS + "")).toLongValue()); _poolConfig .setMinEvictableIdleTimeMillis(BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("min_evictable_idle_time_millis"), GenericObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS + "")) .toLongValue()); _poolConfig.setSoftMinEvictableIdleTimeMillis(BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("soft_min_evictable_idle_time_millis"), GenericObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS + "")) .toLongValue()); _poolConfig.setTestOnBorrow(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_borrow"), GenericObjectPoolConfig.DEFAULT_TEST_ON_BORROW + "")).toBooleanValue()); _poolConfig.setTestOnReturn(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_return"), GenericObjectPoolConfig.DEFAULT_TEST_ON_RETURN + "")).toBooleanValue()); _poolConfig.setTestOnCreate(BlurObject.bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_on_create"), GenericObjectPoolConfig.DEFAULT_TEST_ON_CREATE + "")).toBooleanValue()); _poolConfig .setTestWhileIdle( BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("test_while_idle"), GenericObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE + "")) .toBooleanValue()); _poolConfig .setNumTestsPerEvictionRun( BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("num_tests_per_eviction_run"), GenericObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN + "")) .toIntValue()); _poolConfig .setTimeBetweenEvictionRunsMillis(BlurObject .bind(StringUtils.defaultIfBlank(_tmpCfgs.get("time_between_eviction_runs_millis"), GenericObjectPoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS + "")) .toLongValue()); } _meta = new RedisDataSourceCfgMeta(dsName, _connectionType, _masterServerName, _servers, _poolConfig); // } return _meta; }
From source file:org.apache.directory.ldap.client.template.LdapConnectionTemplateTest.java
@Test public void testDIRAPI_202() throws Exception { // test requested by https://issues.apache.org/jira/browse/DIRAPI-202 LdapConnectionConfig config = new LdapConnectionConfig(); config.setLdapHost(Network.LOOPBACK_HOSTNAME); config.setLdapPort(createLdapConnectionPoolRule.getLdapServer().getPort()); config.setName("uid=admin,ou=system"); config.setCredentials("secret"); DefaultLdapConnectionFactory factory = new DefaultLdapConnectionFactory(config); factory.setTimeOut(30000);// ww w .j a va 2 s.c o m // optional, values below are defaults GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setLifo(true); poolConfig.setMaxTotal(8); poolConfig.setMaxIdle(8); poolConfig.setMaxWaitMillis(-1L); poolConfig.setMinEvictableIdleTimeMillis(1000L * 60L * 30L); poolConfig.setMinIdle(0); poolConfig.setNumTestsPerEvictionRun(3); poolConfig.setSoftMinEvictableIdleTimeMillis(-1L); poolConfig.setTestOnBorrow(false); poolConfig.setTestOnReturn(false); poolConfig.setTestWhileIdle(false); poolConfig.setTimeBetweenEvictionRunsMillis(-1L); poolConfig.setBlockWhenExhausted(GenericObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED); LdapConnectionTemplate ldapConnectionTemplate = new LdapConnectionTemplate( new LdapConnectionPool(new ValidatingPoolableLdapConnectionFactory(factory), poolConfig)); assertNotNull(ldapConnectionTemplate); List<Muppet> muppets = ldapConnectionTemplate.search("ou=people,dc=example,dc=com", "(objectClass=inetOrgPerson)", SearchScope.ONELEVEL, Muppet.getEntryMapper()); assertNotNull(muppets); assertEquals(6, muppets.size()); muppets = ldapConnectionTemplate.search("ou=people,dc=example,dc=com", equal("objectClass", "inetOrgPerson"), SearchScope.ONELEVEL, Muppet.getEntryMapper()); assertNotNull(muppets); assertEquals(6, muppets.size()); }
From source file:org.apache.directory.server.core.integ.CreateLdapConnectionPoolRule.java
private LdapConnectionPool createLdapConnectionPool(LdapServer ldapServer, Class<? extends PooledObjectFactory<LdapConnection>> factoryClass, Class<? extends LdapConnectionFactory> connectionFactoryClass, Class<? extends LdapConnectionValidator> validatorClass) { LdapConnectionConfig config = new LdapConnectionConfig(); config.setLdapHost(Network.LOOPBACK_HOSTNAME); config.setLdapPort(ldapServer.getPort()); config.setName("uid=admin,ou=system"); config.setCredentials("secret"); if ((createLdapConnectionPool.additionalBinaryAttributes() != null) && (createLdapConnectionPool.additionalBinaryAttributes().length > 0)) { DefaultConfigurableBinaryAttributeDetector binaryAttributeDetector = new DefaultConfigurableBinaryAttributeDetector(); binaryAttributeDetector.addBinaryAttribute(createLdapConnectionPool.additionalBinaryAttributes()); config.setBinaryAttributeDetector(binaryAttributeDetector); }//www . j a va 2s . c om GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setLifo(createLdapConnectionPool.lifo()); poolConfig.setMaxTotal(createLdapConnectionPool.maxActive()); poolConfig.setMaxIdle(createLdapConnectionPool.maxIdle()); poolConfig.setMaxWaitMillis(createLdapConnectionPool.maxWait()); poolConfig.setMinEvictableIdleTimeMillis(createLdapConnectionPool.minEvictableIdleTimeMillis()); poolConfig.setMinIdle(createLdapConnectionPool.minIdle()); poolConfig.setNumTestsPerEvictionRun(createLdapConnectionPool.numTestsPerEvictionRun()); poolConfig.setSoftMinEvictableIdleTimeMillis(createLdapConnectionPool.softMinEvictableIdleTimeMillis()); poolConfig.setTestOnBorrow(createLdapConnectionPool.testOnBorrow()); poolConfig.setTestOnReturn(createLdapConnectionPool.testOnReturn()); poolConfig.setTestWhileIdle(createLdapConnectionPool.testWhileIdle()); poolConfig.setTimeBetweenEvictionRunsMillis(createLdapConnectionPool.timeBetweenEvictionRunsMillis()); poolConfig.setBlockWhenExhausted(createLdapConnectionPool.whenExhaustedAction() == 1); try { Constructor<? extends LdapConnectionFactory> constructor = connectionFactoryClass .getConstructor(LdapConnectionConfig.class); ldapConnectionFactory = constructor.newInstance(config); } catch (Exception e) { throw new IllegalArgumentException( "invalid connectionFactoryClass " + connectionFactoryClass.getName() + ": " + e.getMessage(), e); } try { Method timeoutSetter = connectionFactoryClass.getMethod("setTimeOut", Long.TYPE); if (timeoutSetter != null) { timeoutSetter.invoke(ldapConnectionFactory, createLdapConnectionPool.timeout()); } } catch (Exception e) { throw new IllegalArgumentException("invalid connectionFactoryClass " + connectionFactoryClass.getName() + ", missing setTimeOut(long): " + e.getMessage(), e); } try { Constructor<? extends PooledObjectFactory<LdapConnection>> constructor = factoryClass .getConstructor(LdapConnectionFactory.class); poolableLdapConnectionFactory = constructor.newInstance(ldapConnectionFactory); } catch (Exception e) { throw new IllegalArgumentException( "invalid factoryClass " + factoryClass.getName() + ": " + e.getMessage(), e); } try { Method setValidator = factoryClass.getMethod("setValidator", LdapConnectionValidator.class); if (setValidator != null) { setValidator.invoke(poolableLdapConnectionFactory, validatorClass.newInstance()); } } catch (Exception e) { throw new IllegalArgumentException("invalid connectionFactoryClass " + connectionFactoryClass.getName() + ", missing setTimeOut(long): " + e.getMessage(), e); } return new LdapConnectionPool(poolableLdapConnectionFactory, poolConfig); }