Example usage for com.google.common.util.concurrent SettableFuture get

List of usage examples for com.google.common.util.concurrent SettableFuture get

Introduction

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

Prototype

@Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 

Source Link

Usage

From source file:org.loadui.testfx.utils.FXTestUtils.java

/**
 * Runs the given Callable in the JavaFX thread, waiting for it to complete before returning.
 * Also attempts to wait for any other JavaFX events that may have been queued in the Callable
 * to complete. If any Exception is thrown during execution of the Callable, that exception
 * will be re-thrown from invokeAndWait.
 *
 * @param task//from   ww  w. j  a  va2 s  .co m
 * @param timeoutInSeconds
 * @throws Exception
 */
public static void invokeAndWait(final Callable<?> task, int timeoutInSeconds) throws Exception {
    final SettableFuture<Void> future = SettableFuture.create();

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            try {
                task.call();
                future.set(null);
            } catch (Throwable e) {
                future.setException(e);
            }
        }
    });

    try {
        future.get(timeoutInSeconds, TimeUnit.SECONDS);
        awaitEvents();
    } catch (ExecutionException exception) {
        if (exception.getCause() instanceof Exception) {
            throw (Exception) exception.getCause();
        } else {
            throw exception;
        }
    }
}

From source file:com.eviware.loadui.ui.fx.util.test.FXTestUtils.java

/**
 * Runs the given Callable in the JavaFX thread, waiting for it to complete
 * before returning. Also attempts to wait for any other JavaFX events that
 * may have been queued in the Callable to complete. If any Exception is
 * thrown during execution of the Callable, that exception will be re-thrown
 * from invokeAndWait./*  ww w .  j a va2 s . co  m*/
 * 
 * @param task
 * @param timeoutInSeconds
 * @throws Throwable
 */
public static void invokeAndWait(final Callable<?> task, int timeoutInSeconds) throws Exception {
    final SettableFuture<Void> future = SettableFuture.create();

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            try {
                task.call();
                future.set(null);
            } catch (Throwable e) {
                future.setException(e);
            }
        }
    });

    try {
        future.get(timeoutInSeconds, TimeUnit.SECONDS);
        awaitEvents();
    } catch (ExecutionException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        } else {
            throw e;
        }
    }
}

From source file:com.google.cloud.testing.BaseEmulatorHelper.java

private static int waitForProcess(final Process process, Duration timeout)
        throws InterruptedException, TimeoutException {
    if (process == null) {
        return 0;
    }/*from  w w w  .  j a v a 2  s.  co m*/

    final SettableFuture<Integer> exitValue = SettableFuture.create();

    Thread waiter = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                exitValue.set(process.waitFor());
            } catch (InterruptedException e) {
                exitValue.setException(e);
            }
        }
    });
    waiter.start();

    try {
        return exitValue.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof InterruptedException) {
            throw (InterruptedException) e.getCause();
        }
        throw new UncheckedExecutionException(e);
    } finally {
        waiter.interrupt();
    }
}

From source file:com.microsoft.alm.plugin.authentication.AuthHelper.java

/**
 * This method wraps the normal Async call to authenticate and waits on the result.
 *//* w  w w . ja v  a 2  s.c o m*/
public static AuthenticationInfo getAuthenticationInfoSynchronously(final AuthenticationProvider provider,
        final String gitRemoteUrl) {
    final SettableFuture<AuthenticationInfo> future = SettableFuture.create();

    provider.authenticateAsync(gitRemoteUrl, new AuthenticationListener() {
        @Override
        public void authenticating() {
            // do nothing
        }

        @Override
        public void authenticated(final AuthenticationInfo authenticationInfo, final Throwable throwable) {
            if (throwable != null) {
                future.setException(throwable);
            } else {
                future.set(authenticationInfo);
            }
        }
    });

    // Wait for the authentication info object to be ready
    // Don't wait any longer than 15 minutes for the user to authenticate
    Throwable t = null;
    try {
        return future.get(15, TimeUnit.MINUTES);
    } catch (InterruptedException ie) {
        t = ie;
    } catch (ExecutionException ee) {
        t = ee;
    } catch (TimeoutException te) {
        t = te;
    } finally {
        if (t != null) {
            logger.error("getAuthenticationInfoSynchronously: failed to get authentication info from user");
            logger.warn("getAuthenticationInfoSynchronously", t);
        }
    }
    return null;
}

From source file:org.pentaho.caching.impl.PentahoCacheManagerFactory.java

public synchronized void unregisterProvider(String providerId, PentahoCacheProvidingService provider) {
    Set<ListenableFuture<PentahoCacheProvidingService>> invalidFutures = Sets.newHashSet();
    for (Iterator<SettableFuture<PentahoCacheProvidingService>> iterator = providerMap.get(providerId)
            .iterator(); iterator.hasNext();) {
        SettableFuture<PentahoCacheProvidingService> future = iterator.next();
        try {//from  w  w  w .  ja va2 s . c  o m
            if (future.isDone() && future.get(10, TimeUnit.SECONDS).equals(provider)) {
                iterator.remove();
                invalidFutures.add(future);
            }
        } catch (Throwable t) {
            Logger.getLogger(providerId).log(Level.WARNING, "Unexpected exception", t);
        }
    }

    Set<String> pidSet = Sets.newHashSet();
    Iterator<RegistrationHandler> registrations = registrationHandlerMap.values().iterator();
    while (!invalidFutures.isEmpty() && registrations.hasNext()) {
        RegistrationHandler registrationHandler = registrations.next();
        if (invalidFutures.contains(registrationHandler.serviceFuture)) {
            pidSet.add(registrationHandler.pid);
        }
    }

    for (String pid : pidSet) {
        restartService(pid, providerId);
    }
}

From source file:org.apache.spark.network.client.TransportClient.java

/**
 * Synchronously sends an opaque message to the RpcHandler on the server-side, waiting for up to
 * a specified timeout for a response.//from www  . ja v a2s.  c  om
 */
public byte[] sendRpcSync(byte[] message, long timeoutMs) {
    final SettableFuture<byte[]> result = SettableFuture.create();

    sendRpc(message, new RpcResponseCallback() {
        @Override
        public void onSuccess(byte[] response) {
            result.set(response);
        }

        @Override
        public void onFailure(Throwable e) {
            result.setException(e);
        }
    });

    try {
        return result.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:c5db.C5DB.java

@Override
public ImmutableMap<ModuleType, C5Module> getModules()
        throws ExecutionException, InterruptedException, TimeoutException {
    final SettableFuture<ImmutableMap<ModuleType, C5Module>> future = SettableFuture.create();
    serverFiber.execute(() -> future.set(ImmutableMap.copyOf(allModules)));
    return future.get(1, TimeUnit.SECONDS);
}

From source file:co.cask.cdap.common.discovery.AbstractEndpointStrategy.java

@Override
public Discoverable pick(long timeout, TimeUnit timeoutUnit) {
    Discoverable discoverable = pick();//from   w  w  w.ja  v a 2s  . c o  m
    if (discoverable != null) {
        return discoverable;
    }
    final SettableFuture<Discoverable> future = SettableFuture.create();
    Cancellable cancellable = serviceDiscovered.watchChanges(new ServiceDiscovered.ChangeListener() {
        @Override
        public void onChange(ServiceDiscovered serviceDiscovered) {
            // The serviceDiscovered provided is the same as the one in the field, hence ok to just call pick().
            Discoverable discoverable = pick();
            if (discoverable != null) {
                future.set(discoverable);
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
    try {
        return future.get(timeout, timeoutUnit);
    } catch (Exception e) {
        return null;
    } finally {
        cancellable.cancel();
    }
}

From source file:com.github.sparkfy.network.client.TransportClient.java

/**
 * Synchronously sends an opaque message to the RpcHandler on the server-side, waiting for up to
 * a specified timeout for a response.// w ww.j  a v a  2  s. c  om
 */
public ByteBuffer sendRpcSync(ByteBuffer message, long timeoutMs) {
    final SettableFuture<ByteBuffer> result = SettableFuture.create();

    sendRpc(message, new RpcResponseCallback() {
        @Override
        public void onSuccess(ByteBuffer response) {
            ByteBuffer copy = ByteBuffer.allocate(response.remaining());
            copy.put(response);
            // flip "copy" to make it readable
            copy.flip();
            result.set(copy);
        }

        @Override
        public void onFailure(Throwable e) {
            result.setException(e);
        }
    });

    try {
        return result.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.apache.jackrabbit.oak.run.osgi.OakOSGiRepositoryFactory.java

@SuppressWarnings("unchecked")
public Repository getRepository(Map parameters) throws RepositoryException {
    if (parameters == null || !parameters.containsKey(REPOSITORY_HOME)) {
        //Required param missing so repository cannot be created
        return null;
    }/*from   w w  w  . ja va 2  s.c o  m*/

    Map config = new HashMap();
    config.putAll(parameters);

    PojoServiceRegistry registry = initializeServiceRegistry(config);
    BundleActivator activator = getApplicationActivator(config);

    try {
        activator.start(registry.getBundleContext());
    } catch (Exception e) {
        log.warn("Error occurred while starting activator {}", activator.getClass(), e);
    }

    //Future which would be used to notify when repository is ready
    // to be used
    SettableFuture<Repository> repoFuture = SettableFuture.create();

    new RunnableJobTracker(registry.getBundleContext());

    int timeoutInSecs = PropertiesUtil.toInteger(config.get(REPOSITORY_TIMEOUT_IN_SECS), DEFAULT_TIMEOUT);

    //Start the tracker for repository creation
    new RepositoryTracker(registry, activator, repoFuture, timeoutInSecs);

    //Now wait for repository to be created with given timeout
    //if repository creation takes more time. This is required to handle case
    // where OSGi runtime fails to start due to bugs (like cycles)
    try {
        return repoFuture.get(timeoutInSecs, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RepositoryException("Repository initialization was interrupted");
    } catch (ExecutionException e) {
        throw new RepositoryException(e);
    } catch (TimeoutException e) {
        try {
            if (PropertiesUtil.toBoolean(config.get(REPOSITORY_SHUTDOWN_ON_TIMEOUT), true)) {
                shutdown(registry, timeoutInSecs);
                log.info("OSGi container shutdown after waiting for repository initialization for {} sec",
                        timeoutInSecs);
            } else {
                log.warn("[{}] found to be false. Container is not stopped", REPOSITORY_SHUTDOWN_ON_TIMEOUT);
            }
        } catch (BundleException be) {
            log.warn("Error occurred while shutting down the service registry (due to "
                    + "startup timeout) backing the Repository ", be);
        }
        throw new RepositoryException("Repository could not be started in " + timeoutInSecs + " seconds", e);
    }
}