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:org.apache.cassandra.auth.CassandraRoleManager.java

private void scheduleSetupTask(final Callable<Void> setupTask) {
    // The delay is to give the node a chance to see its peers before attempting the operation
    ScheduledExecutors.optionalTasks.schedule(new Runnable() {
        public void run() {
            // If not all nodes are on 2.2, we don't want to initialize the role manager as this will confuse 2.1
            // nodes (see CASSANDRA-9761 for details). So we re-schedule the setup for later, hoping that the upgrade
            // will be finished by then.
            if (!MessagingService.instance().areAllNodesAtLeast22()) {
                logger.trace(/*from ww  w  .j av  a2 s  .  co  m*/
                        "Not all nodes are upgraded to a version that supports Roles yet, rescheduling setup task");
                scheduleSetupTask(setupTask);
                return;
            }

            isClusterReady = true;
            try {
                setupTask.call();
            } catch (Exception e) {
                logger.info("Setup task failed with error, rescheduling");
                scheduleSetupTask(setupTask);
            }
        }
    }, AuthKeyspace.SUPERUSER_SETUP_DELAY, TimeUnit.MILLISECONDS);
}

From source file:org.apache.oozie.servlet.TestAuthFilterAuthOozieClient.java

protected void runTest(Callable<Void> assertions, Configuration additionalConf) throws Exception {
    Services services = new Services();
    try {// w w w  .  jav a2s .  c  o  m
        services.init();
        if (additionalConf != null) {
            for (Map.Entry<String, String> prop : additionalConf) {
                Services.get().getConf().set(prop.getKey(), prop.getValue());
            }
        }
        Services.get().setService(ForTestAuthorizationService.class);
        Services.get().setService(ForTestWorkflowStoreService.class);
        Services.get().setService(MockDagEngineService.class);
        Services.get().setService(MockCoordinatorEngineService.class);
        container = new EmbeddedServletContainer("oozie");
        container.addServletEndpoint("/versions", HeaderTestingVersionServlet.class);
        String version = "/v" + XOozieClient.WS_PROTOCOL_VERSION;
        container.addServletEndpoint(version + "/admin/*", V1AdminServlet.class);
        container.addFilter("*", HostnameFilter.class);
        container.addFilter("/*", AuthFilter.class);
        container.start();
        assertions.call();
    } finally {
        if (container != null) {
            container.stop();
        }
        services.destroy();
        container = null;
    }
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

/**
 * {@inheritDoc}//  w  ww.j av a2  s  . c o m
 */
@Override
@CheckForNull
public BitbucketTeam getTeam() throws IOException, InterruptedException {
    final String url = UriTemplate.fromTemplate(V2_TEAMS_API_BASE_URL + "{/owner}").set("owner", owner)
            .expand();

    Callable<BitbucketTeam> request = () -> {
        try {
            String response = getRequest(url);
            return JsonParser.toJava(response, BitbucketCloudTeam.class);
        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            throw new IOException("I/O error when parsing response from URL: " + url, e);
        }
    };

    try {
        if (enableCache) {
            return cachedTeam.get(owner, request);
        } else {
            return request.call();
        }
    } catch (Exception ex) {
        return null;
    }
}

From source file:mitm.common.util.KeyedBarrier.java

public U execute(T key, Callable<U> callable, long timeout) throws Exception {
    Check.notNull(key, "key");
    Check.notNull(callable, "runnable");

    boolean added = false;

    try {/*from   w  w w.  j a v a2s .  c  o  m*/
        long started = System.currentTimeMillis();

        synchronized (keys) {
            boolean allowed = false;

            do {
                if (keys.contains(key)) {
                    try {
                        logger.debug("Waiting for key {} to be removed", key);

                        keys.wait(waitTime);
                    } catch (InterruptedException e) {
                        /*
                         * ignore
                         */
                    }

                    if (timeout > 0 && (System.currentTimeMillis() - started) > timeout) {
                        throw new KeyedBarrierTimeoutException("Time exceeded the timeout value " + timeout);
                    }
                } else {
                    allowed = true;
                }
            } while (!allowed);

            keys.add(key);

            added = true;
        }

        /*
         * Execute the runnable since we now know that only one runnable is executing 
         * with this key.
         */
        return callable.call();
    } finally {
        /*
         * After executing the Runnable, we need to notify the waiting threads that they can try
         * again.
         */
        synchronized (keys) {
            /*
             * Only remove the key if it was added. It can happen that added is false when a 
             * KeyedBarrierTimeoutException was thrown and we do not want to remove the key 
             * if it was added by a different thread
             */
            if (added) {
                keys.remove(key);
            }

            keys.notify();
        }
    }
}

From source file:org.jasig.ssp.service.impl.ScheduledTaskWrapperServiceImpl.java

/**
 * Basically a deferred form of {@link #execWithTaskContext(Runnable)}.
 * Useful when you have a scheduled job that does its work in batches and
 * you'd like the effect of {@link #execWithTaskContext(Runnable)}
 * (except for the thread naming decoration) applied
 * independently for each batch. This is advisable for any long-running
 * job (which is probably why it was batched in the first place) b/c
 * otherwise you can end up with a system doing a great impression of
 * a memory leak as the Hib session grows indefinitely.
 *
 * <p>Batched jobs often need results from each batch to know what to
 * do next, hence the use of {@code Callable} rather than
 * {@link Runnable} here.</p>// w w w.  j a  v a 2s  .  c om
 *
 * <p>Since thread naming needs to happen prior to individual batch
 * executions, the caller is responsible for wrapping the actual
 * task invocation with that behavior, if necessary. E.g. see
 * {@link #execBatchedTaskWithName(String, org.jasig.ssp.service.external.BatchedTask)}</p>
 *
 * @param batchReturnType
 * @param <T>
 * @return
 */
protected <T> CallableExecutor<T> newTaskBatchExecutor(final Class<T> batchReturnType,
        final boolean isStatusedTask, final UUID runAsId) {
    return new CallableExecutor<T>() {
        @Override
        public T exec(final Callable<T> work) throws Exception {
            final AtomicReference<T> resultHolder = new AtomicReference<T>();
            final AtomicReference<Exception> exceptionHolder = new AtomicReference<Exception>();
            execWithTaskContext(null, new Runnable() {
                @Override
                public void run() {
                    try {
                        resultHolder.set(work.call());
                    } catch (Exception e) {
                        exceptionHolder.set(e);
                    }
                }
            }, isStatusedTask, runAsId);
            if (exceptionHolder.get() != null) {
                throw exceptionHolder.get();
            }
            return resultHolder.get();
        }
    };
}

From source file:org.languagetool.JLanguageTool.java

/**
 * @since 3.7//from w w  w .  j av  a 2 s .c o  m
 */
protected List<RuleMatch> performCheck(List<AnalyzedSentence> analyzedSentences, List<String> sentences,
        List<Rule> allRules, ParagraphHandling paraMode, AnnotatedText annotatedText,
        RuleMatchListener listener, Mode mode) throws IOException {
    Callable<List<RuleMatch>> matcher = new TextCheckCallable(allRules, sentences, analyzedSentences, paraMode,
            annotatedText, 0, 0, 1, listener, mode);
    try {
        return matcher.call();
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificate.java

@Override
public void serviceMail(Mail mail) {
    try {/*from ww w .  j  a  v a 2 s. c  om*/
        final ActivationContext activationContext = new ActivationContext();

        /*
         * Place the activationContext in the context so we can use it in onHandleUserEvent
         */
        getActivationContext().set(ACTIVATION_CONTEXT_KEY, activationContext);

        MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() {
            @Override
            public void handleUser(User user) throws MessagingException {
                onHandleUserEvent(user);
            }
        };

        final MailAddressHandler mailAddressHandler = new MailAddressHandler(sessionManager, userWorkflow,
                actionExecutor, eventHandler, ACTION_RETRIES);

        final InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

        /*
         * If the from is an invalid email address invalid@invalid.tld will be returned. We don't want to request
         * a certificate for that address.
         */
        if (originator != null && !EmailAddressUtils.isInvalidDummyAddress(originator)) {
            Callable<Null> callable = new Callable<Null>() {
                @Override
                public Null call() throws Exception {
                    mailAddressHandler.handleMailAddresses(
                            MailAddressUtils.fromAddressArrayToMailAddressList(originator));

                    /*
                     * activationContext.getUser() will return null if there was no certificate 
                     * requested for the user
                     */
                    makeNonPersistentUserPersistent(activationContext.getUser());

                    return null;
                }
            };

            try {
                if (synchronizeRequests) {
                    /*
                     * Synchronize certificate requests to make sure only one certificate is requested for
                     * a user even if multiple messages are sent by the same user at the same time
                     */
                    keyedBarrier.execute(originator, callable, keyedBarrierTimeout);
                } else {
                    callable.call();
                }
            } catch (Exception e) {
                throw new MessagingException("Error requesting a certificate.", e);
            }
        } else {
            logger.debug(
                    "Message originator is an invalid email address. Certificate request will be skipped.");
        }
    } catch (Exception e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);

        /*
         * If the MessagingException is caused by a CancelCertificateRequestException, do not log stacktrace 
         */
        if (rootCause instanceof CancelCertificateRequestException) {
            getLogger().warn("Certificate request was canceled. Message: " + rootCause.getMessage());
        } else {
            getLogger().error("Error requesting certificates.", e);
        }
    }
}

From source file:org.openconcerto.sql.model.graph.DatabaseGraph.java

/**
 * Execute the passed Callable with only one refresh at the end. This method is reentrant.
 * //from   w  w w.j ava2 s.  co  m
 * @param callable what to do.
 * @return the result of <code>callable</code>.
 * @throws SQLException if an error occurs.
 */
public final <V> V atomicRefresh(final Callable<V> callable) throws SQLException {
    final V res;
    this.atomicRefreshDepth.set(this.atomicRefreshDepth.get().intValue() + 1);
    // this method is useful for grouping multiple changes to the structure, so be sure to
    // prevent other threads from modifying and thus changing the graph
    synchronized (this.base.getTreeMutex()) {
        final int newVal;
        try {
            res = callable.call();
        } catch (Exception e) {
            throw new SQLException("Call failed", e);
        } finally {
            newVal = this.atomicRefreshDepth.get().intValue() - 1;
            this.atomicRefreshDepth.set(newVal);
            assert newVal >= 0;
        }
        if (newVal == 0) {
            final ToRefreshSpec itemsToRefresh = this.atomicRefreshItems.get();
            this.atomicRefreshItems.remove();
            this.atomicRefreshDepth.remove();
            // we need to call refresh() only once to avoid order and cycle issues
            refresh(itemsToRefresh);
        }
    }
    return res;
}

From source file:com.amazonaws.services.dynamodbv2.transactions.Transaction.java

private <T> T doWithMapper(Callable<T> callable) {
    try {//  ww  w  .j av  a 2  s.com
        txManager.getFacadeProxy().setBackend(new TransactionDynamoDBFacade(this, txManager));
        return callable.call();
    } catch (RuntimeException e) {
        // have to do this here in order to avoid having to declare a checked exception type
        throw e;
    } catch (Exception e) {
        // none of the callers of this method need to throw a checked exception
        throw new RuntimeException(e);
    } finally {
        txManager.getFacadeProxy().setBackend(null);
    }
}

From source file:org.pentaho.platform.engine.security.SecurityHelper.java

/**
 * Runs code as system with full privileges.
 *//*from  ww w.j a  va 2 s . c om*/
public <T> T runAsSystem(final Callable<T> callable) throws Exception {
    String singleTenantAdmin = PentahoSystem.get(String.class, "singleTenantAdminUserName", null);
    IPentahoSession origSession = PentahoSessionHolder.getSession();

    SecurityContext originalContext = SecurityContextHolder.getContext();

    StandaloneSession session = null;
    try {
        session = new StandaloneSession(singleTenantAdmin);
        session.setAuthenticated(singleTenantAdmin);

        // Set the session first or else the call to
        // createAuthentication will fail
        PentahoSessionHolder.setSession(session);

        // Clearing the SecurityContext to force the subsequent call to getContext() to generate a new SecurityContext.
        // This prevents us from modifying the Authentication on a SecurityContext isntance which may be shared between
        // threads.
        SecurityContextHolder.clearContext();

        // Now create the authentication
        Authentication auth = createAuthentication(singleTenantAdmin); //$NON-NLS-1$
        SecurityContextHolder.getContext().setAuthentication(auth);

        // Invoke the delta.
        return callable.call();
    } finally {
        // Make sure to destroy the system session so we don't leak anything.
        if (session != null) {
            try {
                session.destroy();
            } catch (Exception e) {
                // We can safely ignore this.
                e.printStackTrace();
            }
        }
        // Reset the original session.
        PentahoSessionHolder.setSession(origSession);
        SecurityContextHolder.setContext(originalContext);
    }
}