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.gs.collections.impl.test.Verify.java

/**
 * Runs the {@link Callable} {@code code} and asserts that it throws an {@code Exception} of the type
 * {@code expectedExceptionClass}.//from  w  ww . j av  a  2  s  .c  o m
 * <p>
 * {@code Callable} is most appropriate when a checked exception will be thrown.
 * If a subclass of {@link RuntimeException} will be thrown, the form
 * {@link #assertThrows(Class, Runnable)} may be more convenient.
 * <p>
 * e.g.
 * <pre>
 * Verify.<b>assertThrows</b>(StringIndexOutOfBoundsException.class, new Callable&lt;String&gt;()
 * {
 *    public String call() throws Exception
 *    {
 *        return "Craig".substring(42, 3);
 *    }
 * });
 * </pre>
 *
 * @see #assertThrows(Class, Runnable)
 */
public static void assertThrows(Class<? extends Exception> expectedExceptionClass, Callable<?> code) {
    try {
        code.call();
    } catch (Exception ex) {
        try {
            Assert.assertSame("Caught exception of type <" + ex.getClass().getName()
                    + ">, expected one of type <" + expectedExceptionClass.getName() + '>' + '\n'
                    + "Exception Message: " + ex.getMessage() + '\n', expectedExceptionClass, ex.getClass());
            return;
        } catch (AssertionError e) {
            Verify.throwMangledException(e);
        }
    }

    try {
        Assert.fail("Block did not throw an exception of type " + expectedExceptionClass.getName());
    } catch (AssertionError e) {
        Verify.throwMangledException(e);
    }
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private ArrayList<Object> buildServiceDetails() {
    ArrayList<Object> serviceDetails = new ArrayList<Object>();

    Collection<ServiceDetailsProvider> serviceDetailsProviders = container.getServiceDetailsProviders();
    for (ServiceDetailsProvider serviceDetailsProvider : serviceDetailsProviders) {
        ServiceDetails[] details = serviceDetailsProvider.getServicesDetails();
        if (details != null) {
            for (ServiceDetails detail : details) {
                serviceDetails.add(detail);
            }//from   w  ww  .j  a v a2  s  .c om
        }
    }

    List<Callable> serviceDetailsProvider = SharedServiceData.removeServiceDetails(clusterInfo.getUniqueName());
    if (serviceDetailsProvider != null) {
        for (Callable serProvider : serviceDetailsProvider) {
            try {
                Object[] details = (Object[]) serProvider.call();
                Collections.addAll(serviceDetails, details);
            } catch (Exception e) {
                logger.error("Failed to add service details from custom provider", e);
            }
        }
    }
    return serviceDetails;
}

From source file:com.gs.collections.impl.test.Verify.java

/**
 * Runs the {@link Callable} {@code code} and asserts that it throws an {@code Exception} of the type
 * {@code expectedExceptionClass}, which contains a cause of type expectedCauseClass.
 * <p>/*w  w  w . j  av a  2 s  .  c  om*/
 * {@code Callable} is most appropriate when a checked exception will be thrown.
 * If a subclass of {@link RuntimeException} will be thrown, the form
 * {@link #assertThrowsWithCause(Class, Class, Runnable)} may be more convenient.
 * <p>
 * e.g.
 * <pre>
 * Verify.assertThrowsWithCause(RuntimeException.class, IOException.class, new Callable<Void>()
 * {
 *    public Void call() throws Exception
 *    {
 *        try
 *        {
 *            new File("").createNewFile();
 *        }
 *        catch (final IOException e)
 *        {
 *            throw new RuntimeException("Uh oh!", e);
 *        }
 *        return null;
 *    }
 * });
 * </pre>
 *
 * @see #assertThrowsWithCause(Class, Class, Runnable)
 */
public static void assertThrowsWithCause(Class<? extends Exception> expectedExceptionClass,
        Class<? extends Throwable> expectedCauseClass, Callable<?> code) {
    try {
        code.call();
    } catch (Exception ex) {
        try {
            Assert.assertSame("Caught exception of type <" + ex.getClass().getName()
                    + ">, expected one of type <" + expectedExceptionClass.getName() + '>',
                    expectedExceptionClass, ex.getClass());
            Throwable actualCauseClass = ex.getCause();
            Assert.assertNotNull("Caught exception with null cause, expected cause of type <"
                    + expectedCauseClass.getName() + '>', actualCauseClass);
            Assert.assertSame(
                    "Caught exception with cause of type<" + actualCauseClass.getClass().getName()
                            + ">, expected cause of type <" + expectedCauseClass.getName() + '>',
                    expectedCauseClass, actualCauseClass.getClass());
            return;
        } catch (AssertionError e) {
            Verify.throwMangledException(e);
        }
    }

    try {
        Assert.fail("Block did not throw an exception of type " + expectedExceptionClass.getName());
    } catch (AssertionError e) {
        Verify.throwMangledException(e);
    }
}

From source file:org.springframework.web.context.request.async.WebAsyncManager.java

/**
 * Use the given {@link WebAsyncTask} to configure the task executor as well as
 * the timeout value of the {@code AsyncWebRequest} before delegating to
 * {@link #startCallableProcessing(Callable, Object...)}.
 * @param webAsyncTask a WebAsyncTask containing the target {@code Callable}
 * @param processingContext additional context to save that can be accessed
 * via {@link #getConcurrentResultContext()}
 * @throws Exception if concurrent processing failed to start
 *//* ww  w. j av a  2s  .c  o  m*/
public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext)
        throws Exception {

    Assert.notNull(webAsyncTask, "WebAsyncTask must not be null");
    Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");

    Long timeout = webAsyncTask.getTimeout();
    if (timeout != null) {
        this.asyncWebRequest.setTimeout(timeout);
    }

    AsyncTaskExecutor executor = webAsyncTask.getExecutor();
    if (executor != null) {
        this.taskExecutor = executor;
    }

    List<CallableProcessingInterceptor> interceptors = new ArrayList<>();
    interceptors.add(webAsyncTask.getInterceptor());
    interceptors.addAll(this.callableInterceptors.values());
    interceptors.add(timeoutCallableInterceptor);

    final Callable<?> callable = webAsyncTask.getCallable();
    final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors);

    this.asyncWebRequest.addTimeoutHandler(() -> {
        logger.debug("Processing timeout");
        Object result = interceptorChain.triggerAfterTimeout(this.asyncWebRequest, callable);
        if (result != CallableProcessingInterceptor.RESULT_NONE) {
            setConcurrentResultAndDispatch(result);
        }
    });

    this.asyncWebRequest.addErrorHandler(ex -> {
        logger.debug("Processing error");
        Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex);
        result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex);
        setConcurrentResultAndDispatch(result);
    });

    this.asyncWebRequest.addCompletionHandler(
            () -> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, callable));

    interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable);
    startAsyncProcessing(processingContext);
    try {
        Future<?> future = this.taskExecutor.submit(() -> {
            Object result = null;
            try {
                interceptorChain.applyPreProcess(this.asyncWebRequest, callable);
                result = callable.call();
            } catch (Throwable ex) {
                result = ex;
            } finally {
                result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, result);
            }
            setConcurrentResultAndDispatch(result);
        });
        interceptorChain.setTaskFuture(future);
    } catch (RejectedExecutionException ex) {
        Object result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, ex);
        setConcurrentResultAndDispatch(result);
        throw ex;
    }
}

From source file:org.zenoss.zep.index.impl.lucene.LuceneEventIndexBackend.java

private TopDocs timeLimitedSearch(final IndexSearcher searcher, final Query query, final Sort sort,
        final int offset, final int limit, final int numDocs) throws ZepException {

    TopDocs docs;/*w  w w. j a  v  a2 s  . c o m*/

    Callable search_call = new Callable<TopDocs>() {
        public TopDocs call() throws IOException, Exception {
            TopDocs tdocs;
            if (sort != null) {
                logger.debug("Query: {}, Sort: {}, Offset: {}, Limit: {}",
                        new Object[] { query, sort, offset, limit });
                tdocs = searcher.search(query, null, numDocs, sort);
            } else {
                logger.debug("Query: {}, Offset: {}, Limit: {}", new Object[] { query, offset, limit });
                tdocs = searcher.search(query, null, numDocs);
            }
            return tdocs;
        }
    };

    try {
        if (this.luceneSearchTimeout > 0) {
            TimeLimiter limiter = new SimpleTimeLimiter();
            docs = (TopDocs) limiter.callWithTimeout(search_call, this.luceneSearchTimeout, TimeUnit.SECONDS,
                    true);
        } else
            docs = (TopDocs) search_call.call();
    } catch (UncheckedTimeoutException e) {
        String msg = "Lucene search exceeded time limit ( " + this.luceneSearchTimeout + " seconds.)";
        if (sort != null)
            logger.warn(msg + "Query: {}, Sort: {}, Offset: {}, Limit: {}",
                    new Object[] { query, sort, offset, limit });
        else
            logger.warn(msg + "Query: {}, Offset: {}, Limit: {}", new Object[] { query, offset, limit });
        throw new ZepException(msg + e.getLocalizedMessage(), e);
    } catch (OutOfMemoryError oome) {
        throw oome;
    } catch (Exception e) {
        logger.error("Exception performing timed search: ", e);
        throw new ZepException(e.getLocalizedMessage(), e);
    }

    return docs;
}

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

/**
 * Calls the callable, inside a transaction if in cluster mode.
 * <p>/*from   ww w  . ja va2s .  c o  m*/
 * Called under {@link #serializationLock}.
 */
protected Lock callInTransaction(Callable<Lock> callable, boolean tx) throws StorageException {
    boolean ok = false;
    checkConnectionValid();
    try {
        if (log.isDebugEnabled()) {
            log.debug("callInTransaction setAutoCommit " + !tx);
        }
        connection.setAutoCommit(!tx);
    } catch (SQLException e) {
        throw new StorageException("Cannot set auto commit mode onto " + this + "'s connection", e);
    }
    try {
        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) {
                        if (log.isDebugEnabled()) {
                            log.debug("callInTransaction commit");
                        }
                        connection.commit();
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("callInTransaction rollback");
                        }
                        connection.rollback();
                    }
                } finally {
                    // restore autoCommit=true
                    if (log.isDebugEnabled()) {
                        log.debug("callInTransaction restoring autoCommit=true");
                    }
                    connection.setAutoCommit(true);
                }
            } catch (SQLException e) {
                throw new StorageException(e);
            }
        }
    }
}

From source file:org.wso2.carbon.humantask.core.scheduler.SimpleScheduler.java

public <T> T execTransaction(Callable<T> transaction, int timeout) throws Exception {
    TransactionManager txm = transactionManager;
    if (txm == null) {
        throw new HumanTaskException(
                "Cannot locate the transaction manager; " + "the server might be shutting down.");
    }/*ww w .  j  av  a  2  s. c o  m*/

    // The value of the timeout is in seconds. If the value is zero, 
    // the transaction service restores the default value.
    if (timeout < 0) {
        throw new IllegalArgumentException("Timeout must be positive, received: " + timeout);
    }

    boolean existingTransaction;
    try {
        existingTransaction = txm.getTransaction() != null;
    } catch (Exception ex) {
        String errMsg = "Internal Error, could not get current transaction.";
        throw new HumanTaskException(errMsg, ex);
    }

    // already in transaction, execute and return directly
    if (existingTransaction) {
        return transaction.call();
    }

    // run in new transaction
    Exception ex = null;
    //        int immediateRetryCount = _immediateTransactionRetryLimit;

    transactionManager.setTransactionTimeout(timeout);
    if (log.isDebugEnabled() && timeout != 0) {
        log.debug("Custom transaction timeout: " + timeout);
    }

    try {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Beginning a new transaction");
            }
            txm.begin();
        } catch (Exception e) {
            String errMsg = "Internal Error, could not begin transaction.";
            throw new HumanTaskException(errMsg, e);
        }

        try {
            ex = null;
            return transaction.call();
        } catch (Exception e) {
            ex = e;
        } finally {
            if (ex == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Committing on " + txm + "...");
                }
                try {
                    txm.commit();
                } catch (Exception e2) {
                    ex = e2;
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Rollbacking on " + txm + "...");
                }
                txm.rollback();
            }

            //                    if (ex != null && immediateRetryCount > 0) {
            //                        if (log.isDebugEnabled()) {
            //                            log.debug("Will retry the transaction in " +
            //                                    _immediateTransactionRetryInterval + " msecs on " +
            //                                    transactionManager + " for error: ", ex);
            //                        }
            //                        Thread.sleep(_immediateTransactionRetryInterval);
            //                    }
        }
    } finally {
        // 0 restores the default value
        transactionManager.setTransactionTimeout(0);
    }

    throw ex;
}

From source file:ml.shifu.shifu.core.Scorer.java

public ScoreObject scoreNsData(MLDataPair inputPair, Map<NSColumn, String> rawNsDataMap) {
    if (inputPair == null && !this.alg.equalsIgnoreCase(NNConstants.NN_ALG_NAME)) {
        inputPair = NormalUtils.assembleNsDataPair(binCategoryMap, noVarSelect, modelConfig,
                selectedColumnConfigList, rawNsDataMap, cutoff, alg);
    }/*from ww  w  . ja v  a  2  s .c  o m*/

    // clear cache
    this.cachedNormDataPair.clear();

    final MLDataPair pair = inputPair;
    List<MLData> modelResults = new ArrayList<MLData>();

    List<Callable<MLData>> tasks = null;
    if (this.multiThread) {
        tasks = new ArrayList<Callable<MLData>>();
    }

    for (final BasicML model : models) {
        // TODO, check if no need 'if' condition and refactor two if for loops please
        if (model instanceof BasicFloatNetwork || model instanceof NNModel) {
            final BasicFloatNetwork network = (model instanceof BasicFloatNetwork) ? (BasicFloatNetwork) model
                    : ((NNModel) model).getIndependentNNModel().getBasicNetworks().get(0);

            String cacheKey = featureSetToString(network.getFeatureSet());
            MLDataPair dataPair = cachedNormDataPair.get(cacheKey);
            if (dataPair == null) {
                dataPair = NormalUtils.assembleNsDataPair(binCategoryMap, noVarSelect, modelConfig,
                        selectedColumnConfigList, rawNsDataMap, cutoff, alg, network.getFeatureSet());
                cachedNormDataPair.put(cacheKey, dataPair);
            }
            final MLDataPair networkPair = dataPair;

            /*
             * if(network.getFeatureSet().size() != networkPair.getInput().size()) {
             * log.error("Network and input size mismatch: Network Size = " + network.getFeatureSet().size()
             * + "; Input Size = " + networkPair.getInput().size());
             * continue;
             * }
             */
            if (System.currentTimeMillis() % 1000 == 0L) {
                log.info("Network input count = {}, while input size = {}", network.getInputCount(),
                        networkPair.getInput().size());
            }

            final int fnlOutputHiddenLayerIndex = outputHiddenLayerIndex;

            Callable<MLData> callable = new Callable<MLData>() {
                @Override
                public MLData call() {
                    MLData finalOutput = network.compute(networkPair.getInput());

                    if (fnlOutputHiddenLayerIndex == 0) {
                        return finalOutput;
                    }

                    // append output values in hidden layer
                    double[] hiddenOutputs = network.getLayerOutput(fnlOutputHiddenLayerIndex);
                    double[] outputs = new double[finalOutput.getData().length + hiddenOutputs.length];

                    System.arraycopy(finalOutput.getData(), 0, outputs, 0, finalOutput.getData().length);
                    System.arraycopy(hiddenOutputs, 0, outputs, finalOutput.getData().length,
                            hiddenOutputs.length);
                    return new BasicMLData(outputs);
                }
            };

            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof BasicNetwork) {
            final BasicNetwork network = (BasicNetwork) model;
            final MLDataPair networkPair = NormalUtils.assembleNsDataPair(binCategoryMap, noVarSelect,
                    modelConfig, columnConfigList, rawNsDataMap, cutoff, alg, null);

            Callable<MLData> callable = new Callable<MLData>() {
                @Override
                public MLData call() {
                    return network.compute(networkPair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof SVM) {
            final SVM svm = (SVM) model;
            if (svm.getInputCount() != pair.getInput().size()) {
                log.error("SVM and input size mismatch: SVM Size = " + svm.getInputCount() + "; Input Size = "
                        + pair.getInput().size());
                continue;
            }

            Callable<MLData> callable = new Callable<MLData>() {
                @Override
                public MLData call() {
                    return svm.compute(pair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof LR) {
            final LR lr = (LR) model;
            if (lr.getInputCount() != pair.getInput().size()) {
                log.error("LR and input size mismatch: LR Size = " + lr.getInputCount() + "; Input Size = "
                        + pair.getInput().size());
                continue;
            }

            Callable<MLData> callable = new Callable<MLData>() {
                @Override
                public MLData call() {
                    return lr.compute(pair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof TreeModel) {
            final TreeModel tm = (TreeModel) model;
            if (tm.getInputCount() != pair.getInput().size()) {
                throw new RuntimeException("GBDT and input size mismatch: tm input Size = " + tm.getInputCount()
                        + "; data input Size = " + pair.getInput().size());
            }

            Callable<MLData> callable = new Callable<MLData>() {
                @Override
                public MLData call() {
                    MLData result = tm.compute(pair.getInput());
                    return result;
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else if (model instanceof GenericModel) {
            Callable<MLData> callable = new Callable<MLData>() {
                @Override
                public MLData call() {
                    return ((GenericModel) model).compute(pair.getInput());
                }
            };
            if (multiThread) {
                tasks.add(callable);
            } else {
                try {
                    modelResults.add(callable.call());
                } catch (Exception e) {
                    log.error("error in model evaluation", e);
                }
            }
        } else {
            throw new RuntimeException("unsupport models");
        }
    }

    List<Double> scores = new ArrayList<Double>();
    List<Integer> rfTreeSizeList = new ArrayList<Integer>();
    SortedMap<String, Double> hiddenOutputs = null;

    if (CollectionUtils.isNotEmpty(modelResults) || CollectionUtils.isNotEmpty(tasks)) {
        int modelSize = modelResults.size() > 0 ? modelResults.size() : tasks.size();
        if (modelSize != this.models.size()) {
            log.error("Get model results size doesn't match with models size.");
            return null;
        }

        if (multiThread) {
            modelResults = this.executorManager.submitTasksAndWaitResults(tasks);
        } else {
            // not multi-thread, modelResults is directly being populated in callable.call
        }

        if (this.outputHiddenLayerIndex != 0) {
            hiddenOutputs = new TreeMap<String, Double>(new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {
                    String[] split1 = o1.split("_");
                    String[] split2 = o2.split("_");
                    int model1Index = Integer.parseInt(split1[1]);
                    int model2Index = Integer.parseInt(split2[1]);
                    if (model1Index > model2Index) {
                        return 1;
                    } else if (model1Index < model2Index) {
                        return -1;
                    } else {
                        int hidden1Index = Integer.parseInt(split1[2]);
                        int hidden2Index = Integer.parseInt(split2[2]);
                        if (hidden1Index > hidden2Index) {
                            return 1;
                        } else if (hidden1Index < hidden2Index) {
                            return -1;
                        } else {
                            int hidden11Index = Integer.parseInt(split1[3]);
                            int hidden22Index = Integer.parseInt(split2[3]);
                            return Integer.valueOf(hidden11Index).compareTo(Integer.valueOf(hidden22Index));
                        }
                    }
                }
            });
        }
        for (int i = 0; i < this.models.size(); i++) {
            BasicML model = this.models.get(i);
            MLData score = modelResults.get(i);

            if (model instanceof BasicNetwork || model instanceof NNModel) {
                if (modelConfig != null && modelConfig.isRegression()) {
                    scores.add(toScore(score.getData(0)));
                    if (this.outputHiddenLayerIndex != 0) {
                        for (int j = 1; j < score.getData().length; j++) {
                            hiddenOutputs.put("model_" + i + "_" + this.outputHiddenLayerIndex + "_" + (j - 1),
                                    score.getData()[j]);
                        }
                    }
                } else if (modelConfig != null && modelConfig.isClassification()
                        && modelConfig.getTrain().isOneVsAll()) {
                    // if one vs all classification
                    scores.add(toScore(score.getData(0)));
                } else {
                    double[] outputs = score.getData();
                    for (double d : outputs) {
                        scores.add(toScore(d));
                    }
                }
            } else if (model instanceof SVM) {
                scores.add(toScore(score.getData(0)));
            } else if (model instanceof LR) {
                scores.add(toScore(score.getData(0)));
            } else if (model instanceof TreeModel) {
                if (modelConfig.isClassification() && !modelConfig.getTrain().isOneVsAll()) {
                    double[] scoreArray = score.getData();
                    for (double sc : scoreArray) {
                        scores.add(sc);
                    }
                } else {
                    // if one vs all multiple classification or regression
                    scores.add(toScore(score.getData(0)));
                }
                final TreeModel tm = (TreeModel) model;
                // regression for RF
                if (!tm.isClassfication() && !tm.isGBDT()) {
                    rfTreeSizeList.add(tm.getTrees().size());
                }
            } else if (model instanceof GenericModel) {
                scores.add(toScore(score.getData(0)));
            } else {
                throw new RuntimeException("unsupport models");
            }
        }
    }

    Integer tag = Constants.DEFAULT_IDEAL_VALUE;

    if (scores.size() == 0 && System.currentTimeMillis() % 100 == 0) {
        log.warn("No Scores Calculated...");
    }

    return new ScoreObject(scores, tag, rfTreeSizeList, hiddenOutputs);
}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public <T> T execTransaction(Callable<T> transaction, int timeout) throws Exception, ContextException {
    TransactionManager txm = _txm;/* w ww  .  ja  v a  2s . co m*/
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }

    // The value of the timeout is in seconds. If the value is zero, the transaction service restores the default value.
    if (timeout < 0) {
        throw new IllegalArgumentException("Timeout must be positive, received: " + timeout);
    }

    boolean existingTransaction = false;
    try {
        existingTransaction = txm.getTransaction() != null;
    } catch (Exception ex) {
        String errmsg = "Internal Error, could not get current transaction.";
        throw new ContextException(errmsg, ex);
    }

    // already in transaction, execute and return directly
    if (existingTransaction) {
        return transaction.call();
    }

    // run in new transaction
    Exception ex = null;
    int immediateRetryCount = _immediateTransactionRetryLimit;

    _txm.setTransactionTimeout(timeout);
    if (__log.isDebugEnabled() && timeout != 0)
        __log.debug("Custom transaction timeout: " + timeout);
    try {
        do {
            try {
                if (__log.isDebugEnabled())
                    __log.debug("Beginning a new transaction");
                txm.begin();
            } catch (Exception e) {
                String errmsg = "Internal Error, could not begin transaction.";
                throw new ContextException(errmsg, e);
            }

            try {
                ex = null;
                return transaction.call();
            } catch (Exception e) {
                ex = e;
            } finally {
                if (ex == null) {
                    if (__log.isDebugEnabled())
                        __log.debug("Commiting on " + txm + "...");
                    try {
                        txm.commit();
                    } catch (Exception e2) {
                        ex = e2;
                    }
                } else {
                    if (__log.isDebugEnabled())
                        __log.debug("Rollbacking on " + txm + "...");
                    txm.rollback();
                }

                if (ex != null && immediateRetryCount > 0) {
                    if (__log.isDebugEnabled())
                        __log.debug("Will retry the transaction in " + _immediateTransactionRetryInterval
                                + " msecs on " + _txm + " for error: ", ex);
                    Thread.sleep(_immediateTransactionRetryInterval);
                }
            }
        } while (immediateRetryCount-- > 0);
    } finally {
        // 0 restores the default value
        _txm.setTransactionTimeout(0);
    }

    throw ex;
}

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

/**
 * The role parameter only makes sense when the request is authenticated, so
 * if there is no auth information ({@link #authenticator}) the role will be omitted.
 *//*from  w  w w .  ja  v a 2 s .  c om*/
@NonNull
@Override
public List<BitbucketCloudRepository> getRepositories(@CheckForNull UserRoleInRepository role)
        throws InterruptedException, IOException {
    StringBuilder cacheKey = new StringBuilder();
    cacheKey.append(owner);

    if (authenticator != null) {
        cacheKey.append("::").append(authenticator.getId());
    } else {
        cacheKey.append("::<anonymous>");
    }

    final UriTemplate template = UriTemplate.fromTemplate(V2_API_BASE_URL + "{/owner}{?role,page,pagelen}")
            .set("owner", owner).set("pagelen", 50);
    if (role != null && authenticator != null) {
        template.set("role", role.getId());
        cacheKey.append("::").append(role.getId());
    }
    Callable<List<BitbucketCloudRepository>> request = () -> {
        List<BitbucketCloudRepository> repositories = new ArrayList<>();
        Integer pageNumber = 1;
        String url, response;
        PaginatedBitbucketRepository page;
        do {
            response = getRequest(url = template.set("page", pageNumber).expand());
            try {
                page = JsonParser.toJava(response, PaginatedBitbucketRepository.class);
                repositories.addAll(page.getValues());
            } catch (IOException e) {
                throw new IOException("I/O error when parsing response from URL: " + url, e);
            }
            pageNumber++;
        } while (page.getNext() != null);
        repositories.sort(Comparator.comparing(BitbucketCloudRepository::getRepositoryName));
        return repositories;
    };
    try {
        if (enableCache) {
            return cachedRepositories.get(cacheKey.toString(), request);
        } else {
            return request.call();
        }
    } catch (Exception ex) {
        throw new IOException("Error while loading repositories from cache", ex);
    }
}