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.pentaho.platform.repository2.unified.ExceptionLoggingDecorator.java

/**
 * Calls the Callable and returns the value it returns. If an exception occurs, it is logged and a new
 * non-chained exception is thrown./*from   w w  w. j  a  v a2s .  c o  m*/
 * 
 * @param <T>
 *          return type
 * @param callable
 *          code to call
 * @param message
 *          verbose description of operation
 * @return return value of Callable
 */
private <T> T callLogThrow(final Callable<T> callable, final String message) {
    try {
        return callable.call();
    } catch (Exception e) {
        // generate reference #
        String refNum = UUID.randomUUID().toString();
        if (logger.isDebugEnabled()) {
            logger.debug(Messages.getInstance().getString("ExceptionLoggingDecorator.referenceNumber", refNum), //$NON-NLS-1$
                    e);
        }

        // list all exceptions in stack
        @SuppressWarnings("unchecked")
        List<Throwable> throwablesInStack = ExceptionUtils.getThrowableList(e);
        // reverse them so most specific exception (root cause) comes first
        Collections.reverse(throwablesInStack);

        for (Throwable t : throwablesInStack) {
            String className = t.getClass().getName();
            if (exceptionConverterMap.containsKey(className)) {
                throw exceptionConverterMap.get(className).convertException((Exception) t, message, refNum);
            }

        }

        // no converter; throw general exception
        throw new UnifiedRepositoryException(Messages.getInstance()
                .getString("ExceptionLoggingDecorator.generalException", message, refNum)); //$NON-NLS-1$

    }
}

From source file:com.thinkbiganalytics.spark.repl.SparkScriptEngine.java

/**
 * Executes the specified callable after replacing the current context class loader.
 *
 * <p>This is a work-around to avoid {@link ClassCastException} issues caused by conflicts between Hadoop and Kylo Spark Shell. Spark uses the context class loader when loading Hadoop components
 * for running Spark on YARN. When both Hadoop and Kylo Spark Shell provide the same class then both classes are loaded when creating a {@link SparkContext}. The fix is to set the context class
 * loader to the same class loader that was used to load the {@link SparkContext} class.</p>
 *
 * @param callable the function to be executed
 * @param <T>      the return type
 * @return the return value/*from   ww  w. j  a  va 2s.c o m*/
 */
private <T> T executeWithSparkClassLoader(@Nonnull final Callable<T> callable) {
    // Set context class loader
    final Thread currentThread = Thread.currentThread();
    final ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    final ClassLoader sparkClassLoader = new ForwardingClassLoader(SparkContext.class.getClassLoader(),
            contextClassLoader);
    currentThread.setContextClassLoader(sparkClassLoader);

    // Execute callable
    try {
        return callable.call();
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    } finally {
        // Reset context class loader
        currentThread.setContextClassLoader(contextClassLoader);
    }
}

From source file:com.liferay.sync.engine.lan.session.LanSession.java

protected SyncLanClientQueryResult findSyncLanClient(SyncFile syncFile) throws Exception {

    SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncFile.getSyncAccountId());

    List<String> syncLanClientUuids = SyncLanEndpointService
            .findSyncLanClientUuids(syncAccount.getLanServerUuid(), syncFile.getRepositoryId());

    if (syncLanClientUuids.isEmpty()) {
        return null;
    }/*from   ww w .ja v a 2s .  c o m*/

    final List<Callable<SyncLanClientQueryResult>> syncLanClientQueryResultCallables = Collections
            .synchronizedList(new ArrayList<Callable<SyncLanClientQueryResult>>(syncLanClientUuids.size()));

    for (String syncLanClientUuid : syncLanClientUuids) {
        SyncLanClient syncLanClient = SyncLanClientService.fetchSyncLanClient(syncLanClientUuid);

        syncLanClientQueryResultCallables.add(createSyncLanClientQueryResultCallable(syncLanClient, syncFile));
    }

    int queryPoolSize = Math.min(syncLanClientUuids.size(), PropsValues.SYNC_LAN_SESSION_QUERY_POOL_MAX_SIZE);

    List<Future<SyncLanClientQueryResult>> pendingSyncLanClientQueryResults = new ArrayList<>(queryPoolSize);

    ExecutorCompletionService<SyncLanClientQueryResult> executorCompletionService = new ExecutorCompletionService<>(
            getExecutorService());

    for (int i = 0; i < queryPoolSize; i++) {
        Callable<SyncLanClientQueryResult> callable = new Callable<SyncLanClientQueryResult>() {

            @Override
            public synchronized SyncLanClientQueryResult call() throws Exception {

                if (syncLanClientQueryResultCallables.isEmpty()) {
                    return null;
                }

                Callable<SyncLanClientQueryResult> syncLanClientQueryResultCallable = syncLanClientQueryResultCallables
                        .remove(0);

                try {
                    return syncLanClientQueryResultCallable.call();
                } catch (Exception e) {
                    return call();
                }
            }

        };

        pendingSyncLanClientQueryResults.add(executorCompletionService.submit(callable));
    }

    List<Future<SyncLanClientQueryResult>> completedSyncLanClientQueryResult = new ArrayList<>(queryPoolSize);

    long timeout = PropsValues.SYNC_LAN_SESSION_QUERY_TOTAL_TIMEOUT;

    long endTime = System.currentTimeMillis() + timeout;

    for (int i = 0; i < queryPoolSize; i++) {
        Future<SyncLanClientQueryResult> future = executorCompletionService.poll(timeout,
                TimeUnit.MILLISECONDS);

        if (future == null) {
            for (Future<SyncLanClientQueryResult> pendingSyncLanClientQueryResult : pendingSyncLanClientQueryResults) {

                if (!pendingSyncLanClientQueryResult.isDone()) {
                    pendingSyncLanClientQueryResult.cancel(true);
                }
            }

            break;
        }

        completedSyncLanClientQueryResult.add(future);

        timeout = endTime - System.currentTimeMillis();
    }

    SyncLanClientQueryResult candidateSyncLanClientQueryResult = null;
    int candidateDownloadRatePerConnection = 0;

    for (Future<SyncLanClientQueryResult> completedFuture : completedSyncLanClientQueryResult) {

        SyncLanClientQueryResult syncLanClientQueryResult = null;

        try {
            syncLanClientQueryResult = completedFuture.get();
        } catch (Exception e) {
            continue;
        }

        if (syncLanClientQueryResult == null) {
            continue;
        }

        if (syncLanClientQueryResult.getConnectionsCount() >= syncLanClientQueryResult.getMaxConnections()) {

            if (candidateSyncLanClientQueryResult == null) {
                candidateSyncLanClientQueryResult = syncLanClientQueryResult;
            }

            continue;
        }

        if (syncLanClientQueryResult.getConnectionsCount() == 0) {
            return syncLanClientQueryResult;
        }

        int downloadRatePerConnection = syncLanClientQueryResult.getDownloadRate()
                / (syncLanClientQueryResult.getConnectionsCount() + 1);

        if (downloadRatePerConnection >= candidateDownloadRatePerConnection) {

            candidateDownloadRatePerConnection = downloadRatePerConnection;
            candidateSyncLanClientQueryResult = syncLanClientQueryResult;
        }
    }

    return candidateSyncLanClientQueryResult;
}

From source file:com.vmware.identity.interop.ldap.LdapConnection.java

private <T> T execute(Callable<T> ldapOp) {
    T result = null;//  www .  j a  v a  2 s .  c om
    long startedAt = System.nanoTime();
    try {
        result = ldapOp.call();
    } catch (LdapException le) {
        throw le;
    } catch (Exception e) {
        throw new LdapException(LdapErrors.LDAP_OTHER.getCode(), e.getMessage());
    } finally {
        if (perfLog.isTraceEnabled()) {
            perfLog.trace(String.format("ldap operation took [%d]ms",
                    TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt)));
        }
    }

    return result;
}

From source file:org.apache.servicemix.camel.JbiBinding.java

/**
 * Run a block of code with the {@link CamelContext#getApplicationContextClassLoader()} set as the thread context classloader.
 * /*from   w ww .j a  va  2 s.  com*/
 * @param callable the block of code to be run
 * @throws Exception exceptions being thrown while running the block of code
 */
public void runWithCamelContextClassLoader(Callable<Object> callable) throws Exception {
    ClassLoader original = Thread.currentThread().getContextClassLoader();
    try {
        ClassLoader loader = context.getApplicationContextClassLoader();
        if (loader != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Set the thread context classloader " + loader);
            }
            Thread.currentThread().setContextClassLoader(loader);
        }
        callable.call();
    } finally {
        // restore CL
        Thread.currentThread().setContextClassLoader(original);
    }
}

From source file:ddf.catalog.definition.impl.DefinitionParser.java

private void commitStaged(List<Callable<Boolean>> stagedAdds) throws Exception {
    for (Callable<Boolean> staged : stagedAdds) {
        try {/*from ww  w. j av a2  s.c o  m*/
            staged.call();
        } catch (RuntimeException e) {
            LOGGER.debug("Error adding staged item {}", staged, e);
        }
    }
}

From source file:com.wavemaker.tools.data.ExportDB.java

@Override
protected void customRun() {

    init();/*ww w  .  j a va2 s . co  m*/

    final Configuration cfg = new Configuration();

    // cfg.addDirectory(this.hbmFilesDir);

    this.hbmFilesDir.find().files().performOperation(new ResourceOperation<com.wavemaker.tools.io.File>() {

        @Override
        public void perform(com.wavemaker.tools.io.File file) {
            if (file.getName().endsWith(".hbm.xml")) {
                cfg.addInputStream(file.getContent().asInputStream());
            }
        }
    });

    Properties connectionProperties = getHibernateConnectionProperties();

    cfg.addProperties(connectionProperties);

    SchemaExport export = null;
    SchemaUpdate update = null;
    File ddlFile = null;

    try {
        if (this.overrideTable) {
            Callable<SchemaExport> t = new Callable<SchemaExport>() {

                @Override
                public SchemaExport call() {
                    return new SchemaExport(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    export = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                export = ResourceClassLoaderUtils.runInClassLoaderContext(true, t, this.classesDir);
            }

            ddlFile = File.createTempFile("ddl", ".sql");
            ddlFile.deleteOnExit();

            export.setOutputFile(ddlFile.getAbsolutePath());
            export.setDelimiter(";");
            export.setFormat(true);

            String extraddl = prepareForExport(this.exportToDatabase);

            export.create(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(export.getExceptions());
            this.errors = filterError(this.errors, connectionProperties);

            this.ddl = IOUtils.read(ddlFile);

            if (!ObjectUtils.isNullOrEmpty(extraddl)) {
                this.ddl = extraddl + "\n" + this.ddl;
            }
        } else {
            Callable<SchemaUpdate> t = new Callable<SchemaUpdate>() {

                @Override
                public SchemaUpdate call() {
                    return new SchemaUpdate(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    update = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                update = ResourceClassLoaderUtils.runInClassLoaderContext(t, this.classesDir);
            }

            prepareForExport(this.exportToDatabase);

            Connection conn = JDBCUtils.getConnection(this.connectionUrl.toString(), this.username,
                    this.password, this.driverClassName);

            Dialect dialect = Dialect.getDialect(connectionProperties);

            DatabaseMetadata meta = new DatabaseMetadata(conn, dialect);

            String[] updateSQL = cfg.generateSchemaUpdateScript(dialect, meta);

            update.execute(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(update.getExceptions());
            StringBuilder sb = new StringBuilder();
            for (String line : updateSQL) {
                sb = sb.append(line);
                sb = sb.append("\n");
            }
            this.ddl = sb.toString();

        }
    } catch (IOException ex) {
        throw new DataServiceRuntimeException(ex);
    } catch (SQLException qex) {
        throw new DataServiceRuntimeException(qex);
    } catch (RuntimeException rex) {
        if (rex.getCause() != null && rex.getCause().getMessage().contains(NO_SUITABLE_DRIVER)
                && WMAppContext.getInstance().isCloudFoundry()) {
            String msg = rex.getMessage() + " - " + UNKNOWN_DATABASE;
            throw new DataServiceRuntimeException(msg);
        } else {
            throw new DataServiceRuntimeException(rex);
        }
    } finally {
        try {
            ddlFile.delete();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.linkedin.helix.TestHelper.java

public static <T> Map<String, T> startThreadsConcurrently(final int nrThreads, final Callable<T> method,
        final long timeout) {
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch finishCounter = new CountDownLatch(nrThreads);
    final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>();
    final List<Thread> threadList = new ArrayList<Thread>();

    for (int i = 0; i < nrThreads; i++) {
        Thread thread = new Thread() {
            @Override/* ww w.j  ava2s. c o m*/
            public void run() {
                try {
                    boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS);
                    if (isTimeout) {
                        LOG.error("Timeout while waiting for start latch");
                    }
                } catch (InterruptedException ex) {
                    LOG.error("Interrupted while waiting for start latch");
                }

                try {
                    T result = method.call();
                    if (result != null) {
                        resultsMap.put("thread_" + this.getId(), result);
                    }
                    LOG.debug("result=" + result);
                } catch (Exception e) {
                    LOG.error("Exeption in executing " + method.getClass().getName(), e);
                }

                finishCounter.countDown();
            }
        };
        threadList.add(thread);
        thread.start();
    }
    startLatch.countDown();

    // wait for all thread to complete
    try {
        boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS);
        if (isTimeout) {
            LOG.error("Timeout while waiting for finish latch. Interrupt all threads");
            for (Thread thread : threadList) {
                thread.interrupt();
            }
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for finish latch", e);
    }

    return resultsMap;
}

From source file:de.hska.ld.core.service.impl.UserServiceImpl.java

@Override
public Callable callAs(User user, Callable callable) {
    return () -> {
        Authentication authenticationBefore = SecurityContextHolder.getContext().getAuthentication();
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
        try {/*from  ww  w  .  ja  v  a 2s  . c o m*/
            return callable.call();
        } finally {
            SecurityContextHolder.getContext().setAuthentication(authenticationBefore);
        }
    };
}

From source file:org.apache.bookkeeper.common.util.OrderedExecutor.java

public <T> ListenableFuture<T> submitOrdered(long orderingKey, Callable<T> task) {
    SettableFuture<T> future = SettableFuture.create();
    executeOrdered(orderingKey, () -> {
        try {/* w w w  .  j  av a  2s. c  o  m*/
            T result = task.call();
            future.set(result);
        } catch (Throwable t) {
            future.setException(t);
        }
    });

    return future;
}