Example usage for com.google.common.util.concurrent SimpleTimeLimiter newProxy

List of usage examples for com.google.common.util.concurrent SimpleTimeLimiter newProxy

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SimpleTimeLimiter newProxy.

Prototype

@Override
    public <T> T newProxy(final T target, Class<T> interfaceType, final long timeoutDuration,
            final TimeUnit timeoutUnit) 

Source Link

Usage

From source file:org.graylog2.security.ldap.LdapConnector.java

public LdapNetworkConnection connect(LdapConnectionConfig config) throws LdapException {
    final LdapNetworkConnection connection = new LdapNetworkConnection(config);
    connection.setTimeOut(connectionTimeout);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Connecting to LDAP server {}:{}, binding with user {}", config.getLdapHost(),
                config.getLdapPort(), config.getName());
    }/*from  www.j  a va 2s.  c o m*/

    // this will perform an anonymous bind if there were no system credentials
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("ldap-connector-%d").build();
    final SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter(
            Executors.newSingleThreadExecutor(threadFactory));
    @SuppressWarnings("unchecked")
    final Callable<Boolean> timeLimitedConnection = timeLimiter.newProxy(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return connection.connect();
        }
    }, Callable.class, connectionTimeout, TimeUnit.MILLISECONDS);
    try {
        final Boolean connected = timeLimitedConnection.call();
        if (!connected) {
            return null;
        }
    } catch (UncheckedTimeoutException e) {
        LOG.error("Timed out connecting to LDAP server", e);
        throw new LdapException("Could not connect to LDAP server", e.getCause());
    } catch (LdapException e) {
        throw e;
    } catch (Exception e) {
        // unhandled different exception, should really not happen here.
        throw new LdapException("Unexpected error connecting to LDAP", e);
    }
    connection.bind();

    return connection;
}