Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

In this page you can find the example usage for java.util.concurrent Callable call.

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:com.streamsets.pipeline.lib.remote.TestChrootSFTPClient.java

private void expectNotExist(Callable callable) throws Exception {
    try {//from  w w  w  . j a v a  2s.  com
        callable.call();
        Assert.fail("Expected an SFTPException");
    } catch (SFTPException e) {
        Assert.assertEquals("No such file or directory", e.getMessage());
    }
}

From source file:com.google.android.apps.forscience.whistlepunk.DataControllerImpl.java

private <T> void background(Executor dataThread, final MaybeConsumer<T> onSuccess, final Callable<T> job) {
    dataThread.execute(new Runnable() {
        @Override//from   w w w.j  a  v a  2s.c  o m
        public void run() {
            try {
                final T result = job.call();
                mUiThread.execute(new Runnable() {
                    @Override
                    public void run() {
                        onSuccess.success(result);
                    }
                });
            } catch (final Exception e) {
                mUiThread.execute(new Runnable() {
                    @Override
                    public void run() {
                        onSuccess.fail(e);
                    }
                });
            }
        }
    });
}

From source file:net.i2cat.netconf.messageQueue.MessageQueue.java

/**
 * Wait for a new message with the id <code>messageId</code> to arrive in the queue.
 *
 * @param messageId a string identifying the message to consume.
 * @param timeout a long indicating the length of the timeout in milliseconds. If zero or less, no timeout.
 * @throws Exception an UncheckedTimeoutException if there is no message with <code>messageId</code> after waiting for the specified timeout.
 * @return/*w  ww .  j  av  a2 s.  c o  m*/
 */
public RPCElement blockingConsumeById(String messageId, long timeout) throws Exception {

    final String messageIdFinal = messageId;
    Callable<RPCElement> consumeCaller = new Callable<RPCElement>() {
        public RPCElement call() throws Exception {
            RPCElement element;
            synchronized (queue) {
                while ((element = consumeById(messageIdFinal)) == null) {
                    try {
                        log.debug("Waiting (" + messageIdFinal + ")...");
                        queue.wait();
                    } catch (InterruptedException e) {
                        // Do nothing. It's probably a timeout.
                    }
                }
            }
            return element;
        }
    };

    if (timeout <= 0) {
        return consumeCaller.call();
    }

    SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter();

    try {
        return timeLimiter.callWithTimeout(consumeCaller, timeout, TimeUnit.MILLISECONDS, true);
    } catch (UncheckedTimeoutException e) {
        log.debug("BlockingConsumeById(messageId=" + messageId + ") failed due to timeout.", e);
        throw e;
    } catch (Exception e) {
        log.debug("BlockingConsumeById(messageId=" + messageId + ") failed.", e);
        throw e;
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.LockManager.java

/**
 * Calls the callable, inside a transaction if in cluster mode.
 * <p>//from www .  j  ava2  s .  c o m
 * Called under {@link #serializationLock}.
 */
protected Lock callInTransaction(Callable<Lock> callable) throws StorageException {
    boolean tx = clusteringEnabled;
    boolean ok = false;
    try {
        if (tx) {
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                throw new StorageException(e);
            }
        }
        // else no need to process invalidations,
        // only this mapper writes locks

        // actual call
        Lock result;
        try {
            result = callable.call();
        } catch (StorageException e) {
            throw e;
        } catch (Exception e) {
            throw new StorageException(e);
        }

        ok = true;
        return result;
    } finally {
        if (tx) {
            try {
                try {
                    if (ok) {
                        connection.commit();
                    } else {
                        connection.rollback();
                    }
                } catch (SQLException e) {
                    throw new StorageException(e);
                }
            } finally {
                try {
                    connection.setAutoCommit(true);
                } catch (SQLException e) {
                    throw new StorageException(e);
                }
            }
        }
    }
}

From source file:net.java.html.charts.ChartsTest.java

private void run(final Callable<?> r) throws Exception {
    final CountDownLatch await = new CountDownLatch(1);
    final Throwable[] arr = { null };
    Platform.runLater(() -> {//from  www . jav  a 2 s.c  o m
        try (Closeable c = Fn.activate(presenter)) {
            r.call();
        } catch (Throwable t) {
            arr[0] = t;
        } finally {
            await.countDown();
        }
    });
    await.await();
    if (arr[0] instanceof Exception) {
        throw (Exception) arr[0];
    }
    if (arr[0] instanceof Error) {
        throw (Error) arr[0];
    }
}

From source file:org.apache.storm.utils.Utils.java

/**
 * Creates a thread that calls the given code repeatedly, sleeping for an
 * interval of seconds equal to the return value of the previous call.
 *
 * The given afn may be a callable that returns the number of seconds to
 * sleep, or it may be a Callable that returns another Callable that in turn
 * returns the number of seconds to sleep. In the latter case isFactory.
 *
 * @param afn the code to call on each iteration
 * @param isDaemon whether the new thread should be a daemon thread
 * @param eh code to call when afn throws an exception
 * @param priority the new thread's priority
 * @param isFactory whether afn returns a callable instead of sleep seconds
 * @param startImmediately whether to start the thread before returning
 * @param threadName a suffix to be appended to the thread name
 * @return the newly created thread/*from w ww.j a  va  2s .co m*/
 * @see Thread
 */
public static SmartThread asyncLoop(final Callable afn, boolean isDaemon,
        final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory,
        boolean startImmediately, String threadName) {
    SmartThread thread = new SmartThread(new Runnable() {
        public void run() {
            Object s;
            try {
                Callable fn = isFactory ? (Callable) afn.call() : afn;
                while ((s = fn.call()) instanceof Long) {
                    Time.sleepSecs((Long) s);
                }
            } catch (Throwable t) {
                if (exceptionCauseIsInstanceOf(InterruptedException.class, t)) {
                    LOG.info("Async loop interrupted!");
                    return;
                }
                LOG.error("Async loop died!", t);
                throw new RuntimeException(t);
            }
        }
    });
    if (eh != null) {
        thread.setUncaughtExceptionHandler(eh);
    } else {
        thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOG.error("Async loop died!", e);
                exitProcess(1, "Async loop died!");
            }
        });
    }
    thread.setDaemon(isDaemon);
    thread.setPriority(priority);
    if (threadName != null && !threadName.isEmpty()) {
        thread.setName(thread.getName() + "-" + threadName);
    }
    if (startImmediately) {
        thread.start();
    }
    return thread;
}

From source file:com.evolveum.midpoint.web.application.AsyncWebProcessManagerImpl.java

@Override
public void submit(@NotNull String processId, @NotNull Callable callable) {
    AsyncWebProcess process = getProcess(processId);

    if (process == null) {
        throw new IllegalStateException("Process with id '" + processId + "' doesn't exist");
    }/*w ww  . j a  v a2s.  c o  m*/

    Callable securityAware = callable;

    if (!(callable instanceof SecurityContextAwareCallable)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        SecurityContextManager secManager = application.getSecurityContextManager();

        securityAware = new SecurityContextAwareCallable(secManager, auth) {

            @Override
            public Object callWithContextPrepared() throws Exception {
                return callable.call();
            }
        };
    }

    Future future = executor.submit(securityAware);
    process.setFuture(future);
}

From source file:com.cloudant.mazha.CouchClient.java

private InputStream executeToInputStreamWithRetry(final Callable<ExecuteResult> task) throws CouchException {
    int attempts = 10;
    CouchException lastException = null;
    while (attempts-- > 0) {
        ExecuteResult result = null;//  w w  w  .  j  av a 2  s  .  c  o m
        try {
            result = task.call();
        } catch (Exception e) {
            throw new CouchException("Unexpected exception", e, -1);
        }
        lastException = result.exception;
        if (result.stream != null) {
            // success - return the inputstream
            return result.stream;
        } else if (result.fatal) {
            // fatal exception - don't attempt any more retries
            throw result.exception;
        }
    }
    throw lastException;
}

From source file:org.labkey.nashorn.NashornController.java

private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine;/*w  w w.j av  a2  s.  com*/
    ScriptContext context;

    Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() {
        @Override
        @NotNull
        public ScriptEngine call() throws Exception {
            NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
            ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" });
            return engine;
        }
    };

    if (useSession) {
        HttpServletRequest req = getViewContext().getRequest();
        engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext);
    } else {
        engine = createContext.call();
    }

    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext()));

    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine
    // some docs mention enginScope.get("nashorn.global"), but that is also null
    if (null == globalScope)
        globalScope = (Bindings) engineScope.get("nashorn.global");
    if (null == globalScope)
        globalScope = engineScope;
    globalScope.put("console", new Console());

    return new Pair<>(engine, engine.getContext());
}

From source file:org.sakaiproject.tool.impl.SessionComponentRegressionTest.java

protected <V> V execBlockableSessionOp(final CountDownLatch opStarted, final CountDownLatch opBlocker,
        final CountDownLatch opCompleted, Callable<V> callback) {
    try {//from ww  w.  ja v a  2s. c o m
        opStarted.countDown();
        if (!(opBlocker.await(10, TimeUnit.SECONDS))) {
            fail("Took too long");
        }
        V result = callback.call();
        // Op only completes if the super impl returns non-exceptionally.
        // This allows us to detect failures outside the main test thread.
        opCompleted.countDown();
        return result;
    } catch (Throwable e) {
        e.printStackTrace();
        throw new RuntimeException(e); // typically ends up in logs, at best 
    }
}