Example usage for org.apache.commons.pool2.impl GenericObjectPool borrowObject

List of usage examples for org.apache.commons.pool2.impl GenericObjectPool borrowObject

Introduction

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

Prototype

@Override
public T borrowObject() throws Exception 

Source Link

Document

Equivalent to #borrowObject(long) borrowObject ( #getMaxWaitMillis() ).

Usage

From source file:me.smoe.adar.pool.commonpool.CommonPool.java

public static void main(String[] args) throws NoSuchElementException, IllegalStateException, Exception {
    GenericObjectPool<Book> objectPool = new GenericObjectPool<Book>(new BookPoolFactory(),
            buildPoolConfig(5, 10, 2));//from ww  w. j  a  v a  2  s.c  om
    prestartCorePool(objectPool);

    List<Book> books = new LinkedList<Book>();
    for (int i = 0; i < 10; i++) {
        books.add(objectPool.borrowObject());
    }

    for (Book book : books) {
        objectPool.returnObject(book);
    }
}

From source file:com.heliosapm.streams.collector.ds.pool.TestMQPool.java

/**
 * @param args// w  w w . j a  v a 2 s . c  o  m
 */
public static void main(String[] args) {
    try {
        log("Pool Test");
        log(TEST_PROPS);
        JMXHelper.fireUpJMXMPServer(1077);
        final Properties p = Props.strToProps(TEST_PROPS);
        log("Props:" + p);
        final GenericObjectPool<Object> pool = null;//(GenericObjectPool<Object>)PoolConfig.deployPool(p);
        pool.preparePool();
        log("Pool Deployed:" + pool.getNumIdle());
        final List<Object> objects = new ArrayList<Object>();
        for (int i = 0; i < 4; i++) {
            try {
                final Object o = pool.borrowObject();
                log("Borrowed:" + o);
                objects.add(o);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log("Objects:" + objects.size());
        StdInCommandHandler.getInstance().registerCommand("close", new Runnable() {
            public void run() {
                for (Object o : objects) {
                    pool.returnObject(o);
                }
                objects.clear();
                try {
                    pool.close();
                } catch (Exception ex) {
                    ex.printStackTrace(System.err);
                }
            }
        }).run();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

}

From source file:gobblin.util.AutoReturnableObject.java

public AutoReturnableObject(GenericObjectPool<T> pool) throws IOException {
    try {//from   w  w w.j a  va2s.c o m
        this.pool = pool;
        this.object = pool.borrowObject();
        this.returned = false;
    } catch (Exception exc) {
        throw new IOException(exc);
    }
}

From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java

public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication,
        TransactionData transactionData) {

    LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod;
    UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication;

    boolean validation;

    String userId = userPwAuthentication.getUserId();
    String password = userPwAuthentication.getPassword();

    GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName());

    InitialLdapContext ctx = null;

    try {/* w  w w  .j a  v a 2 s  .  c o  m*/
        ctx = pool.borrowObject();

        // First we search the user
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID",
                SecurityUtils.escapeLDAPSearchFilter(userId));

        NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter,
                controls);

        SearchResult result;

        if (results.hasMoreElements()) {
            result = results.next();

            if (results.hasMoreElements()) {
                LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName());
                return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                        .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE);
            }
        } else {
            LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

        // Try to bind with the found user id
        validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(),
                result.getNameInNamespace(), password);

        pool.returnObject(ctx);

        if (validation) {
            LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId)
                    .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel());
        } else {
            LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

    } catch (Exception ex) {

        // Discard context
        try {
            if (ctx != null) {
                pool.invalidateObject(ctx);
            }
        } catch (Exception ex2) {
            LOG.error("An error occurend when authenticating user");
        }

        return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR);
    }

}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void genericPoolUsingWrappingShouldPropagateExceptionsCorrectly() throws Exception {

    GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig());

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    RedisCommands<String, String> sync = connection.sync();
    sync.set(key, value);/*w  w  w .  j  a  v a2 s . c om*/

    try {
        sync.hgetall(key);
        fail("Missing RedisCommandExecutionException");
    } catch (RedisCommandExecutionException e) {
        assertThat(e).hasMessageContaining("WRONGTYPE");
    }

    sync.close();
    pool.close();
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void wrappedConnectionShouldUseWrappers() throws Exception {

    GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig());

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    RedisCommands<String, String> sync = connection.sync();

    assertThat(connection).isInstanceOf(StatefulRedisConnection.class)
            .isNotInstanceOf(StatefulRedisClusterConnectionImpl.class);
    assertThat(Proxy.isProxyClass(connection.getClass())).isTrue();

    assertThat(sync).isInstanceOf(RedisCommands.class);
    assertThat(connection.async()).isInstanceOf(RedisAsyncCommands.class)
            .isNotInstanceOf(RedisAsyncCommandsImpl.class);
    assertThat(connection.reactive()).isInstanceOf(RedisReactiveCommands.class)
            .isNotInstanceOf(RedisReactiveCommandsImpl.class);
    assertThat(sync.getStatefulConnection()).isInstanceOf(StatefulRedisConnection.class)
            .isNotInstanceOf(StatefulRedisConnectionImpl.class).isSameAs(connection);

    sync.close();//w w  w .  j  av a  2 s.  c  om
    pool.close();
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void wrappedObjectClosedAfterReturn() throws Exception {

    GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig(), true);

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    RedisCommands<String, String> sync = connection.sync();
    sync.ping();//  ww  w .  ja  v a  2 s  .  com
    sync.close();

    try {
        connection.isMulti();
        fail("Missing RedisException");
    } catch (RedisException e) {
        assertThat(e).hasMessageContaining("deallocated");
    }

    pool.close();
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void plainConnectionShouldNotUseWrappers() throws Exception {

    GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig(), false);

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    RedisCommands<String, String> sync = connection.sync();

    assertThat(connection).isInstanceOf(StatefulRedisConnection.class)
            .isNotInstanceOf(StatefulRedisClusterConnectionImpl.class);
    assertThat(Proxy.isProxyClass(connection.getClass())).isFalse();

    assertThat(sync).isInstanceOf(RedisCommands.class);
    assertThat(connection.async()).isInstanceOf(RedisAsyncCommands.class)
            .isInstanceOf(RedisAsyncCommandsImpl.class);
    assertThat(connection.reactive()).isInstanceOf(RedisReactiveCommands.class)
            .isInstanceOf(RedisReactiveCommandsImpl.class);
    assertThat(sync.getStatefulConnection()).isInstanceOf(StatefulRedisConnection.class)
            .isInstanceOf(StatefulRedisConnectionImpl.class);

    pool.returnObject(connection);/*from  w  w w . j a va2 s . co m*/
    pool.close();
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void wrappedClusterConnectionShouldUseWrappers() throws Exception {

    RedisClusterClient redisClusterClient = RedisClusterClient.create(TestClientResources.create(),
            RedisURI.create(TestSettings.host(), 7379));

    GenericObjectPool<StatefulRedisClusterConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(redisClusterClient::connect, new GenericObjectPoolConfig());

    StatefulRedisClusterConnection<String, String> connection = pool.borrowObject();
    RedisAdvancedClusterCommands<String, String> sync = connection.sync();

    assertThat(connection).isInstanceOf(StatefulRedisClusterConnection.class)
            .isNotInstanceOf(StatefulRedisClusterConnectionImpl.class);
    assertThat(Proxy.isProxyClass(connection.getClass())).isTrue();

    assertThat(sync).isInstanceOf(RedisAdvancedClusterCommands.class);
    assertThat(connection.async()).isInstanceOf(RedisAdvancedClusterAsyncCommands.class)
            .isNotInstanceOf(RedisAdvancedClusterAsyncCommandsImpl.class);
    assertThat(connection.reactive()).isInstanceOf(RedisAdvancedClusterReactiveCommands.class)
            .isNotInstanceOf(RedisAdvancedClusterReactiveCommandsImpl.class);
    assertThat(sync.getStatefulConnection()).isInstanceOf(StatefulRedisClusterConnection.class)
            .isNotInstanceOf(StatefulRedisClusterConnectionImpl.class).isSameAs(connection);

    sync.close();/* w  w  w . j  a va2 s . com*/
    pool.close();

    FastShutdown.shutdown(redisClusterClient);
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void genericPoolShouldWorkWithPlainConnections() throws Exception {

    GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig(), false);

    borrowAndReturn(pool);//from w  w w.  ja v a2  s .c  o m

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    assertThat(Proxy.isProxyClass(connection.getClass())).isFalse();
    pool.returnObject(connection);

    pool.close();
}