Example usage for org.apache.commons.pool BaseKeyedPoolableObjectFactory BaseKeyedPoolableObjectFactory

List of usage examples for org.apache.commons.pool BaseKeyedPoolableObjectFactory BaseKeyedPoolableObjectFactory

Introduction

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

Prototype

BaseKeyedPoolableObjectFactory

Source Link

Usage

From source file:com.seajas.search.contender.scripting.ScriptCache.java

/**
 * Default constructor./*from w  w w.  j av  a2 s . c  om*/
 *
 * @param maximumEntries
 */
@Autowired
public ScriptCache(
        @Value("${contender.project.script.cache.maximum.entries.per.script}   ") final Integer maximumEntries) {
    pool = new GenericKeyedObjectPool<ModifierScript, ScriptCacheEntry>(
            new BaseKeyedPoolableObjectFactory<ModifierScript, ScriptCacheEntry>() {
                /**
                 * {@inheritDoc}
                 */
                @Override
                public ScriptCacheEntry makeObject(final ModifierScript script) throws Exception {
                    ScriptEngine engine = engineManager
                            .getEngineByName(script.getScriptLanguage().toLowerCase());

                    if (engine instanceof Compilable) {
                        CompiledScript compiledScript = ((Compilable) engine)
                                .compile(script.getScriptContent());

                        return new ScriptCacheEntry(script.getModificationDate(), compiledScript);
                    } else
                        throw new Exception(
                                String.format("The given script with ID %d of type %s cannot be compiled",
                                        script.getId(), script.getScriptLanguage()));
                }

                /**
                 * {@inheritDoc}
                 */
                @Override
                public boolean validateObject(final ModifierScript script, final ScriptCacheEntry entry) {
                    boolean result = entry.getModificationDate().equals(script.getModificationDate());

                    if (logger.isTraceEnabled())
                        logger.trace(String.format(
                                (result ? "I" : "Not i")
                                        + "nvalidating pool entry for ID %d - modification date has changed",
                                script.getId()));

                    return result;
                }
            }, maximumEntries);

    pool.setMaxIdle(maximumEntries);
    pool.setTestOnBorrow(true);
    pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK);
}

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

public void testClosedPoolBehavior() throws Exception {
    final KeyedObjectPool pool;
    try {/*from w  w  w .j av  a 2  s .  c o m*/
        pool = makeEmptyPool(new BaseKeyedPoolableObjectFactory() {
            public Object makeObject(final Object key) throws Exception {
                return new Object();
            }
        });
    } catch (UnsupportedOperationException uoe) {
        return; // test not supported
    }

    Object o1 = pool.borrowObject(KEY);
    Object o2 = pool.borrowObject(KEY);

    pool.close();

    try {
        pool.addObject(KEY);
        fail("A closed pool must throw an IllegalStateException when addObject is called.");
    } catch (IllegalStateException ise) {
        // expected
    }

    try {
        pool.borrowObject(KEY);
        fail("A closed pool must throw an IllegalStateException when borrowObject is called.");
    } catch (IllegalStateException ise) {
        // expected
    }

    // The following should not throw exceptions just because the pool is closed.
    assertEquals("A closed pool shouldn't have any idle objects.", 0, pool.getNumIdle(KEY));
    assertEquals("A closed pool shouldn't have any idle objects.", 0, pool.getNumIdle());
    pool.getNumActive();
    pool.getNumActive(KEY);
    pool.returnObject(KEY, o1);
    assertEquals("returnObject should not add items back into the idle object pool for a closed pool.", 0,
            pool.getNumIdle(KEY));
    assertEquals("returnObject should not add items back into the idle object pool for a closed pool.", 0,
            pool.getNumIdle());
    pool.invalidateObject(KEY, o2);
    pool.clear(KEY);
    pool.clear();
    pool.close();
}

From source file:eu.openanalytics.rsb.rservi.RmiRServiInstanceProvider.java

private void initializeRServiClientPool(final Config config) {
    final KeyedPoolableObjectFactory<RServiPoolKey, PooledRServiWrapper> factory = new BaseKeyedPoolableObjectFactory<RServiPoolKey, PooledRServiWrapper>() {
        @Override//  w ww  .java2  s. c om
        public PooledRServiWrapper makeObject(final RServiPoolKey key) throws Exception {
            final RServi rServi = RServiUtil.getRServi(key.getAddress(), key.getClientId());
            return new PooledRServiWrapper(rServiPool, key, rServi);
        }

        @Override
        public void destroyObject(final RServiPoolKey key, final PooledRServiWrapper rServi) throws Exception {
            rServi.destroy();
        }

        @Override
        public boolean validateObject(final RServiPoolKey key, final PooledRServiWrapper rServi) {
            if (rServi.isClosed()) {
                return false;
            }

            if (rServi.hasError() || configuration
                    .getRServiClientPoolValidationStrategy() == RServiClientPoolValidationStrategy.FULL) {
                final boolean responding = Util.isRResponding(rServi);

                if (rServi.hasError() && LOGGER.isInfoEnabled()) {
                    LOGGER.info(String.format("RServi @ %s has been found %svalid after error",
                            key.getAddress(), responding ? "" : "in"));
                }

                if (responding) {
                    rServi.resetError();
                }

                return responding;
            } else {
                return true;
            }
        }
    };

    rServiPool = new GenericKeyedObjectPoolFactory<RServiPoolKey, PooledRServiWrapper>(factory, config)
            .createPool();
    LOGGER.info("RServi pool instantiated and configured with: " + ToStringBuilder.reflectionToString(config));
}

From source file:com.servoy.extensions.plugins.rest_ws.RestWSPlugin.java

synchronized KeyedObjectPool getClientPool() {
    if (clientPool == null) {
        byte exchaustedAction;
        int poolSize;
        if (ApplicationServerRegistry.get().isDeveloperStartup()) {
            // in developer multiple clients do not work well with debugger
            poolSize = 1;//from   w w w.  jav a2  s.  co  m
            exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else {
            try {
                poolSize = Integer.parseInt(application.getSettings()
                        .getProperty(CLIENT_POOL_SIZE_PROPERTY, "" + CLIENT_POOL_SIZE_DEFAULT).trim());
            } catch (NumberFormatException nfe) {
                poolSize = CLIENT_POOL_SIZE_DEFAULT;
            }
            String exchaustedActionCode = application.getSettings()
                    .getProperty(CLIENT_POOL_EXCHAUSTED_ACTION_PROPERTY);
            if (exchaustedActionCode != null)
                exchaustedActionCode = exchaustedActionCode.trim();
            if (ACTION_FAIL.equalsIgnoreCase(exchaustedActionCode)) {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_FAIL);
            } else if (ACTION_GROW.equalsIgnoreCase(exchaustedActionCode)) {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_GROW);
            } else {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_BLOCK);
            }
        }
        if (log.isDebugEnabled())
            log.debug("Creating client pool, maxSize=" + poolSize);
        clientPool = new GenericKeyedObjectPool(new BaseKeyedPoolableObjectFactory() {
            @Override
            public Object makeObject(Object key) throws Exception {
                if (log.isDebugEnabled())
                    log.debug("creating new session client for solution '" + key + '\'');
                String solutionName = (String) key;
                String[] solOpenArgs = SOLUTION_OPEN_METHOD_ARGS;

                String[] arr = solutionName.split(":");
                if (arr.length == 2) {
                    solutionName = arr[0];
                    solOpenArgs = Utils.arrayJoin(SOLUTION_OPEN_METHOD_ARGS, new String[] { "nodebug" });
                }
                return HeadlessClientFactory.createHeadlessClient(solutionName, solOpenArgs);
            }

            @Override
            public boolean validateObject(Object key, Object obj) {
                IHeadlessClient client = ((IHeadlessClient) obj);
                if (client.getPluginAccess().isInDeveloper()) {
                    String solutionName = (String) key;
                    if (solutionName.contains(":"))
                        solutionName = solutionName.split(":")[0];

                    if (!solutionName.equals(((IHeadlessClient) obj).getPluginAccess().getSolutionName())) {
                        try {
                            client.closeSolution(true);
                            client.loadSolution(solutionName);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                }
                boolean valid = client.isValid();
                if (log.isDebugEnabled())
                    log.debug("Validated session client for solution '" + key + "', valid = " + valid);
                return valid;
            }

            @Override
            public void destroyObject(Object key, Object obj) throws Exception {
                if (log.isDebugEnabled())
                    log.debug("Destroying session client for solution '" + key + "'");
                IHeadlessClient client = ((IHeadlessClient) obj);
                try {
                    client.shutDown(true);
                } catch (Exception e) {
                    Debug.error(e);
                }
            }
        }, poolSize);
        clientPool.setTestOnBorrow(true);
        clientPool.setWhenExhaustedAction(exchaustedAction);
        clientPool.setMaxIdle(poolSize); // destroy objects when pool has grown
    }
    return clientPool;
}