Example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

Introduction

In this page you can find the example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool.

Prototype

public GenericObjectPool(PoolableObjectFactory factory) 

Source Link

Document

Create a new GenericObjectPool using the specified factory.

Usage

From source file:com.flexoodb.pool.ConnectionPool.java

public boolean reconnect() {
    boolean result = false;
    Connection conn = null;/*  ww  w.  j  a va  2s.  c o  m*/

    try {
        if (!_reconnecting) {
            if (_autoreturn) {

                _borrowed.clear();

            }
            _reconnecting = true;

            if (connections != null) {
                disconnect();
            }
            connections = new GenericObjectPool(new ConnectionPoolFactory(driverClassName.trim(), dbURL.trim(),
                    user.trim(), password.trim()));
            connections.setTestWhileIdle(true);
            connections.setTimeBetweenEvictionRunsMillis(600000); // 30 seconds before it checks for evictable objects.
            connections.setMinEvictableIdleTimeMillis(600000); // connection pool can be idle for 2 minutes
            connections.setMinIdle(this.initconnections);
            connections.setMaxActive(this.maxconnections);
            connections.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL);

            _connected = true;

            conn = (Connection) getConnection();

            _connected = (conn != null);
            _reconnecting = false;
        } else {
            //_log.warn("Database re-connection already on-going, re-connection ignored.");
        }
    } catch (Exception e) {
        result = false;
        _reconnecting = false;
        //_log.error(e);
        e.printStackTrace();
    } finally {
        if (_connected) {
            result = true;
            releaseConnection(conn);
        }
    }

    return result;

}

From source file:com.noelios.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Creates a connection pool for a given connection configuration.
 * /*  w  w w .j  a v a2s.c o m*/
 * @param uri
 *            The connection URI.
 * @param properties
 *            The connection properties.
 * @return The new connection pool.
 */
protected static ObjectPool createConnectionPool(String uri, Properties properties) {
    // Create an ObjectPool that will serve as the actual pool of
    // connections
    final ObjectPool result = new GenericObjectPool(null);

    // Create a ConnectionFactory that the pool will use to create
    // Connections
    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, properties);

    // Create the PoolableConnectionFactory, which wraps the "real"
    // Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            result, null, null, false, false);

    // To remove warnings
    poolableConnectionFactory.getPool();

    return result;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.router.DnsRoutePerformanceTest.java

@Before
public void before() throws Exception {
    CacheRegister cacheRegister = new CacheRegister();

    JSONTokener healthTokener = new JSONTokener(new FileReader("src/test/db/health.json"));
    JSONObject healthObject = new JSONObject(healthTokener);

    JSONTokener jsonTokener = new JSONTokener(new FileReader("src/test/db/cr-config.json"));
    JSONObject crConfigJson = new JSONObject(jsonTokener);
    JSONObject locationsJo = crConfigJson.getJSONObject("edgeLocations");
    final Set<CacheLocation> locations = new HashSet<CacheLocation>(locationsJo.length());
    for (final String loc : JSONObject.getNames(locationsJo)) {
        final JSONObject jo = locationsJo.getJSONObject(loc);
        locations.add(new CacheLocation(loc, jo.optString("zoneId"),
                new Geolocation(jo.getDouble("latitude"), jo.getDouble("longitude"))));
    }/*from   www. j a v  a2 s  . c om*/

    names = new DnsNameGenerator().getNames(crConfigJson.getJSONObject("deliveryServices"),
            crConfigJson.getJSONObject("config"));

    cacheRegister.setConfig(crConfigJson);
    CacheRegisterBuilder.parseDeliveryServiceConfig(crConfigJson.getJSONObject("deliveryServices"),
            cacheRegister);

    cacheRegister.setConfiguredLocations(locations);
    CacheRegisterBuilder.parseCacheConfig(crConfigJson.getJSONObject("contentServers"), cacheRegister);

    NetworkUpdater networkUpdater = new NetworkUpdater();
    networkUpdater.setDatabasesDirectory(Paths.get("src/test/db"));
    networkUpdater.setDatabaseName("czmap.json");
    networkUpdater.setExecutorService(Executors.newSingleThreadScheduledExecutor());
    networkUpdater.setTrafficRouterManager(mock(TrafficRouterManager.class));
    JSONObject configJson = crConfigJson.getJSONObject("config");
    networkUpdater.setDataBaseURL(configJson.getString("coveragezone.polling.url"),
            configJson.getLong("coveragezone.polling.interval"));

    File coverageZoneFile = new File("src/test/db/czmap.json");
    while (!coverageZoneFile.exists()) {
        Thread.sleep(500);
    }

    NetworkNode.generateTree(coverageZoneFile);

    ZoneManager zoneManager = mock(ZoneManager.class);

    MD5HashFunctionPoolableObjectFactory md5factory = new MD5HashFunctionPoolableObjectFactory();
    GenericObjectPool pool = new GenericObjectPool(md5factory);

    whenNew(ZoneManager.class)
            .withArguments(any(TrafficRouter.class), any(StatTracker.class), any(TrafficOpsUtils.class))
            .thenReturn(zoneManager);

    trafficRouter = new TrafficRouter(cacheRegister, mock(GeolocationService.class),
            mock(GeolocationService.class), pool, mock(StatTracker.class), mock(TrafficOpsUtils.class),
            mock(FederationRegistry.class));

    trafficRouter.setApplicationContext(mock(ApplicationContext.class));

    trafficRouter = spy(trafficRouter);

    doCallRealMethod().when(trafficRouter).getCoverageZoneCache(anyString(), any(DeliveryService.class));

    doCallRealMethod().when(trafficRouter).selectCache(any(Request.class), any(DeliveryService.class),
            any(Track.class));
    doCallRealMethod().when(trafficRouter, "selectCache", any(CacheLocation.class), any(DeliveryService.class));
    doCallRealMethod().when(trafficRouter, "getSupportingCaches", any(List.class), any(DeliveryService.class));
    doCallRealMethod().when(trafficRouter).setState(any(JSONObject.class));
    doCallRealMethod().when(trafficRouter).selectDeliveryService(any(Request.class), anyBoolean());
    doReturn(new Geolocation(39.739167, -104.984722)).when(trafficRouter).getLocation(anyString());

    trafficRouter.setState(healthObject);

    JSONObject coverageZoneMap = new JSONObject(new JSONTokener(new FileReader("src/test/db/czmap.json")));
    JSONObject coverageZones = coverageZoneMap.getJSONObject("coverageZones");

    Iterator iterator = coverageZones.keys();
    Map<String, Integer> seen = new HashMap<String, Integer>();

    while (iterator.hasNext()) {
        String coverageZoneName = (String) iterator.next();
        JSONObject coverageZoneJson = coverageZones.getJSONObject(coverageZoneName);
        JSONArray networks = coverageZoneJson.getJSONArray("network");
        Set<String> hosts = hostMap.get(coverageZoneName);

        if (hosts == null) {
            hosts = new HashSet<String>();
        }

        for (int i = 0; i < networks.length(); i++) {
            String network = networks.getString(i).split("/")[0];
            InetAddress ip = InetAddresses.forString(network);
            ip = InetAddresses.increment(ip);
            String ipstr = InetAddresses.toAddrString(ip);
            hosts.add(ipstr);

            if (seen.containsKey(ipstr)) {
                seen.put(ipstr, seen.get(ipstr) + 1);
            } else {
                seen.put(ipstr, 1);
            }
        }

        final CacheLocation location = cacheRegister.getCacheLocation(coverageZoneName);

        if (location != null || (location == null && coverageZoneJson.has("coordinates"))) {
            coverageZoneRouted.add(coverageZoneName);
        }

        hostMap.put(coverageZoneName, hosts);
    }

    // remove any dups that will cause a GEO result
    for (String ip : seen.keySet()) {
        if (seen.get(ip) > 1) {
            for (String coverageZoneName : hostMap.keySet()) {
                Set<String> ips = hostMap.get(coverageZoneName);
                ips.remove(ip);
            }
        }
    }
}

From source file:com.insprise.common.db.DefaultConnectionPool.java

/**
* Sets up the connection pool. Call this at most once only!
*
* @throws ClassNotFoundException//from   w w w . ja va2 s. c  om
*/
private void setupPool() throws ClassNotFoundException {
    if (sourceType != SourceType.DRIVER_MANAGER) {
        throw new RuntimeException();
    }

    connectionPool = new GenericObjectPool(null);
    setMaxActive(maxActive);
    setMaxIdle(maxIdle);
    setMaxWaittime(maxWaittime);

    // establish connection factory.
    ConnectionFactory connectionFactory = null;
    Class.forName(driverClass);
    connectionFactory = new DriverManagerConnectionFactory(url, properties);

    if (validationQuery == null) {
        log.warn("Validation SQL for database connection pool is null!");
    } else {
        // log.info("Validation SQL for database connection pool is: " + validationQuery);
    }

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, validationQuery, false, true);

    // force to execute validationQuery before borrowing connection from pool.
    connectionPool.setTestOnBorrow(true);
    dataSource = new PoolingDataSource(connectionPool);

    log.debug("Initialized " + toString());
}

From source file:com.jdon.aop.interceptor.PoolInterceptor.java

public CommonsPoolFactory create(TargetServiceFactory targetServiceFactory, String maxSize) {
    CommonsPoolFactory commonsPoolFactory = new CommonsPoolFactory(targetServiceFactory, maxSize);

    GenericObjectPool apachePool = new GenericObjectPool(commonsPoolFactory);
    CommonsPoolAdapter pool = new CommonsPoolAdapter(apachePool);
    if (maxSize == null) {
        Debug.logError("[JdonFramework] not set pool's max size", module);
    } else {//from  w  w  w.  ja  va  2  s  . c om
        int maxInt = Integer.parseInt(maxSize);
        pool.setMaxPoolSize(maxInt);
    }

    commonsPoolFactory.setPool(pool);
    return commonsPoolFactory;

}

From source file:esg.common.db.DatabaseResource.java

public DatabaseResource setupDataSource(Properties props) {
    log.trace("Setting up data source... ");
    if (props == null) {
        log.error("Property object is [" + props + "]: Cannot setup up data source");
        return this;
    }//from  w  w  w.j  av  a  2  s.c o  m
    //Ex: jdbc:postgresql://pcmdi3.llnl.gov:5432/esgcet
    String protocol = props.getProperty("db.protocol", "jdbc:postgresql:");
    String host = props.getProperty("db.host", "localhost");
    String port = props.getProperty("db.port", "5432");
    String database = props.getProperty("db.database", "esgcet");
    String user = props.getProperty("db.user", "dbsuper");
    String password = props.getProperty("db.password");

    //If the password is not directly available in the properties
    //object then try to read it via the code provided in the
    //ESGFProperties type...iff props is actually of the type
    //ESGFProperties.
    if (password == null) {
        try {
            password = ((esg.common.util.ESGFProperties) props).getDatabasePassword();
        } catch (Throwable t) {
            log.error(" ****** DATABASE PASSWORD IS NOT SET!!! ******");
            log.warn(
                    "Check that password is set in the passed in property file or that property object is an ESGFProperties object!!");
            t.printStackTrace();
        }
    }

    String connectURI = protocol + "//" + host + ":" + port + "/" + database;
    log.info("Connection URI = " + connectURI);
    connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, user, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);
    dataSource = new PoolingDataSource(connectionPool);
    return this;
}

From source file:com.l2jserver.service.database.sql.AbstractSQLDatabaseService.java

@Override
protected void doStart() throws ServiceStartException {
    try {/*from w w w . j  a v  a  2s. c  o m*/
        engine = config.getDatabaseEngineClass().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new ServiceStartException("DatabaseEngine instance not found", e);
    }

    connectionPool = new GenericObjectPool<Connection>(null);
    connectionPool.setMaxActive(config.getMaxActiveConnections());
    connectionPool.setMinIdle(config.getMinIdleConnections());
    connectionPool.setMaxIdle(config.getMaxIdleConnections());

    // test if connections are active while idle
    connectionPool.setTestWhileIdle(true);

    // DriverManager.registerDriver(driver)

    connectionFactory = new DriverManagerConnectionFactory(config.getJdbcUrl(), config.getUsername(),
            config.getPassword());
    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null,
            "SELECT 1", false, true);
    dataSource = new PoolingDataSource(connectionPool);

    if (config.isAutomaticSchemaUpdateEnabled()) {
        updateSchemas();
    }

    for (final Type<?> type : sqlTypes) {
        engine.registerType(type);
    }

    // cache must be large enough for all world objects, to avoid
    // duplication... this would endanger non-persistent states
    objectCache = cacheService.createEternalCache("database-service", IDAllocator.ALLOCABLE_IDS);

    // start the auto save task
    autoSaveFuture = threadService.async(60, TimeUnit.SECONDS, 60, new Runnable() {
        @Override
        public void run() {
            try {
                log.debug("Auto save task started");
                int objects = 0;
                for (final Model<?> object : objectCache) {
                    @SuppressWarnings("unchecked")
                    final DataAccessObject<Model<?>, ?> dao = (DataAccessObject<Model<?>, ?>) daoResolver
                            .getDAO(object.getClass());
                    if (dao == null)
                        continue;
                    if (dao.save(object) > 0) {
                        objects++;
                    }
                }
                log.info("{} objects have been saved by the auto save task", objects);
            } catch (Exception e) {
                log.error("Error occured in save thread", e);
            }
        }
    });
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

/**
 * Tests addObject contention between ensureMinIdle triggered by the Evictor
 * with minIdle > 0 and borrowObject.
 *//*from  w w w .j  a  va  2s  . co  m*/
public void testEvictAddObjects() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    factory.setMakeLatency(300);
    factory.setMaxActive(2);
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setMaxActive(2);
    pool.setMinIdle(1);
    pool.borrowObject(); // numActive = 1, numIdle = 0
    // Create a test thread that will run once and try a borrow after
    // 150ms fixed delay
    TestThread borrower = new TestThread(pool, 1, 150, false);
    Thread borrowerThread = new Thread(borrower);
    // Set evictor to run in 100 ms - will create idle instance
    pool.setTimeBetweenEvictionRunsMillis(100);
    borrowerThread.start(); // Off to the races
    borrowerThread.join();
    assertTrue(!borrower.failed());
    pool.close();
}

From source file:com.nridge.core.ds.rdbms.SQLConnectionPool.java

private void create(Properties aProperties) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "create");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    String driverClassName = aProperties.getProperty("driverClassName");
    try {/*from   w  w  w . j  a  va 2 s. co m*/
        Class.forName(driverClassName).getConstructor().newInstance();
    } catch (Exception e) {
        throw new NSException(String.format("%s: %s", driverClassName, e.getMessage()), e);
    }

    String validationQuery = aProperties.getProperty("validationQuery");
    boolean isAutoCommit = StrUtl.stringToBoolean("defaultAutoCommit");

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(aProperties.getProperty("url"),
            aProperties);
    GenericObjectPool connectionPool = new GenericObjectPool(null);

    // When you pass an ObjectPool into the PoolableConnectionFactory, it will automatically
    // register itself as the PoolableObjectFactory for that pool.

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, validationQuery, false, isAutoCommit);
    mDataSource = new PoolingDataSource(connectionPool);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:esg.node.util.migrate.UserMigrationTool.java

public UserMigrationTool setupSourceResources(String protocol, String host, String port, String database,
        String user, String password) {

    System.out.println("Setting up source resources...");

    String connectURI = protocol + "//" + host + ":" + port + "/" + database; //zoiks
    log.debug("Source Connection URI  = " + connectURI);
    log.debug("Source Connection User = " + user);
    log.debug("Source Connection Password = " + (null == password ? password : "********"));
    this.connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, user, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);
    this.sourceDataSource = new PoolingDataSource(connectionPool);
    this.queryRunner = new QueryRunner(sourceDataSource);
    return this;
}