Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:de.btobastian.javacord.entities.impl.ImplVoiceChannel.java

@Override
public Future<Void> delete() {
    return api.getThreadPool().getExecutorService().submit(new Callable<Void>() {
        @Override//  w  ww  .ja v a2  s  .c o  m
        public Void call() throws Exception {
            logger.debug("Trying to delete voice channel {}", ImplVoiceChannel.this);
            HttpResponse<JsonNode> response = Unirest.delete("https://discordapp.com/api/channels/" + id)
                    .header("authorization", api.getToken()).asJson();
            api.checkResponse(response);
            api.checkRateLimit(response, RateLimitType.UNKNOWN, server, null);
            server.removeVoiceChannel(ImplVoiceChannel.this);
            logger.info("Deleted voice channel {}", ImplVoiceChannel.this);
            // call listener
            api.getThreadPool().getSingleThreadExecutorService("listeners").submit(new Runnable() {
                @Override
                public void run() {
                    List<VoiceChannelDeleteListener> listeners = api
                            .getListeners(VoiceChannelDeleteListener.class);
                    synchronized (listeners) {
                        for (VoiceChannelDeleteListener listener : listeners) {
                            try {
                                listener.onVoiceChannelDelete(api, ImplVoiceChannel.this);
                            } catch (Throwable t) {
                                logger.warn("Uncaught exception in VoiceChannelDeleteListener!", t);
                            }
                        }
                    }
                }
            });
            return null;
        }
    });
}

From source file:de.btobastian.javacord.entities.message.impl.ImplReaction.java

@Override
public Future<List<User>> getUsers(FutureCallback<List<User>> callback) {
    ListenableFuture<List<User>> future = api.getThreadPool().getListeningExecutorService()
            .submit(new Callable<List<User>>() {
                @Override/* www.j av a 2s  . c  om*/
                public List<User> call() throws Exception {
                    logger.debug("Trying to get reactors of reaction {} of message {}", ImplReaction.this,
                            message);
                    String reactionString = isCustomEmoji()
                            ? getCustomEmoji().getName() + ":" + getCustomEmoji().getId()
                            : getUnicodeEmoji();
                    HttpResponse<JsonNode> response = Unirest
                            .get("/channels/" + ((ImplMessage) message).getChannelId() + "/messages/"
                                    + message.getId() + "/reactions/" + reactionString)
                            .header("authorization", api.getToken()).asJson();
                    api.checkResponse(response);
                    api.checkRateLimit(response, RateLimitType.UNKNOWN, null, message.getChannelReceiver());
                    logger.debug("Got reactors of reaction {} of message {}", ImplReaction.this, message);
                    JSONArray userArray = response.getBody().getArray();
                    List<User> users = new ArrayList<>();
                    for (int i = 0; i > userArray.length(); i++) {
                        User user = api.getOrCreateUser(userArray.getJSONObject(i));
                        if (user != null) {
                            users.add(user);
                        }
                    }
                    return users;
                }
            });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}

From source file:annis.gui.frequency.FrequencyResultPanel.java

public FrequencyResultPanel(String aql, Set<String> corpora, final List<FrequencyTableEntry> freqDefinition,
        FrequencyQueryPanel queryPanel) {
    this.aql = aql;
    this.corpora = corpora;
    this.freqDefinition = freqDefinition;
    this.queryPanel = queryPanel;

    setSizeFull();/*from   w  w w .j a va 2 s  . co  m*/

    pbQuery = new ProgressBar();
    pbQuery.setCaption("Please wait, the frequencies analysis can take some time");
    pbQuery.setIndeterminate(true);
    pbQuery.setEnabled(true);

    addComponent(pbQuery);
    setComponentAlignment(pbQuery, Alignment.TOP_CENTER);

    chart = new FrequencyChart(this);
    chart.setHeight("350px");
    chart.setVisible(false);
    addComponent(chart);

    btDownloadCSV = new Button("Download as CSV");
    btDownloadCSV.setDescription("Download as CSV");
    btDownloadCSV.setSizeUndefined();
    addComponent(btDownloadCSV);
    setComponentAlignment(btDownloadCSV, Alignment.TOP_RIGHT);

    btDownloadCSV.setVisible(false);
    btDownloadCSV.setIcon(FontAwesome.DOWNLOAD);
    btDownloadCSV.addStyleName(ValoTheme.BUTTON_SMALL);

    final UI ui = UI.getCurrent();
    // actually start query
    Callable<FrequencyTable> r = new Callable<FrequencyTable>() {
        @Override
        public FrequencyTable call() throws Exception {
            final FrequencyTable t = loadBeans();

            ui.access(new Runnable() {

                @Override
                public void run() {
                    showResult(t);
                }
            });

            return t;
        }
    };

    PollControl.callInBackground(1000, ui, r);
}

From source file:at.ac.univie.isc.asio.brood.Warden.java

/**
 * Assemble a container from the given configuration data and deploy it with the given id.
 *
 * @param target  id of the new container
 * @param source  raw configuration data of the deployed container
 * @param factory Assembler compatible with the given source
 * @param format  identifier of config format
 *//*from w ww . j  ava2 s.  c  o m*/
private void assembleAndDeploy(final Id target, final ByteSource source, final Assembler factory,
        final String format) {
    log.debug(Scope.SYSTEM.marker(), "creating <{}> from '{}' sources using {}", target, format,
            factory.getClass());
    monitor.ensureActive(); // fail fast before doing a costly assembly
    final Container container = factory.assemble(target, source);
    monitor.atomic(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            dispose(target);
            final URI location = config.save(target.asString(), format, source);
            log.debug(Scope.SYSTEM.marker(), "saved configuration at <{}>", location);
            container.activate();
            log.debug(Scope.SYSTEM.marker(), "activated {} as <{}>", container, target);
            final Optional<Container> replaced = catalog.deploy(container);
            cleanUpIfNecessary(replaced);
            assert !replaced.isPresent() : "container was present on deploying of " + target;
            return null;
        }
    });
}

From source file:io.fabric8.forge.camel.commands.project.helper.CamelCommandsHelper.java

public static Callable<Iterable<ComponentDto>> createComponentDtoValues(final Project project,
        final CamelCatalog camelCatalog, final UISelectOne<String> componentCategoryFilter,
        final boolean excludeComponentsOnClasspath, final boolean consumerOnly, final boolean producerOnly) {
    // use callable so we can live update the filter
    return new Callable<Iterable<ComponentDto>>() {
        @Override//w ww  .j av a  2 s. com
        public Iterable<ComponentDto> call() throws Exception {
            String label = componentCategoryFilter != null ? componentCategoryFilter.getValue() : null;
            return new CamelComponentsCompleter(project, camelCatalog, null, excludeComponentsOnClasspath,
                    false, consumerOnly, producerOnly).getValueChoices(label);
        }
    };
}

From source file:com.atomicleopard.thundr.ftp.FtpSession.java

public FTPFile[] listDirectories() {
    return timeLogAndCatch("List directories", new Callable<FTPFile[]>() {
        @Override/*  w w w .  j ava2s  .co  m*/
        public FTPFile[] call() throws Exception {
            return preparedClient.listDirectories();
        }
    });
}

From source file:com.echopf.ECHOTreeMap.java

/**
 * Does Fetch data from the remote server in a background thread.
 *
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. 
 *         (a synchronous communication)
 * @param callback invoked after the fetching is completed
 * @throws ECHOException //  w  ww . ja v  a2 s.  c  o  m
 */
protected void doFetch(final boolean sync, final FetchCallback<S> callback) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            ECHOException exception = null;
            JSONObject data = null;

            try {

                synchronized (lock) {
                    data = ECHOQuery.getRequest(getRequestURLPath());
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;
                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHOTreeMap.this, fException);
                        }
                    });
                }

            } else {

                if (exception != null)
                    throw exception;
            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:logdruid.util.DataMiner.java

public static MineResultSet gatherMineResultSet(final Repository repo) {
    String test = Preferences.getPreference("ThreadPool_Group");
    int ini = Integer.parseInt(test);
    logger.info("gatherMineResultSet parallelism: " + ini);
    ThreadPool_GroupWorkers = Executors.newFixedThreadPool(ini);
    ChartData cd = new ChartData();
    Collection<Callable<MineResult>> tasks = new ArrayList<Callable<MineResult>>();
    MineResultSet mineResultSet = new MineResultSet();

    cd = gatherSourceData(repo);/*  w w  w.  j a  v a 2 s  . c  o m*/
    //   if (logger.isEnabledFor(Level.INFO))
    //      logger.info("ArrayList sourceFileGroup" + sourceFileGroup);
    Iterator<Source> sourceIterator2 = repo.getSources().iterator();

    while (sourceIterator2.hasNext()) {
        final Source source = sourceIterator2.next();
        // sourceFiles contains all the matched files for a given source
        if (source.getActive()) {
            Iterator<Entry<String, ArrayList<FileRecord>>> it = cd.getGroupFilesMap(source).entrySet()
                    .iterator();
            while (it.hasNext()) {
                final Map.Entry<String, ArrayList<FileRecord>> pairs = (Map.Entry<String, ArrayList<FileRecord>>) it
                        .next();
                logger.debug("Source:" + source.getSourceName() + ", group: " + pairs.getKey() + " = "
                        + pairs.getValue().toString());
                tasks.add(new Callable<MineResult>() {
                    public MineResult call() throws Exception {
                        return DataMiner.mine((String) pairs.getKey(), (ArrayList<FileRecord>) pairs.getValue(),
                                repo, source, Preferences.isStats(), Preferences.isTimings());
                    }

                });

            }
        }
    }
    /*
     * invokeAll blocks until all service requests complete, or a max of
     * 1000 seconds.
     */
    List<Future<MineResult>> results = null;
    try {
        results = ThreadPool_GroupWorkers.invokeAll(tasks, 1000, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (Future<MineResult> f : results) {
        MineResult mineRes = null;
        try {
            // if (mineRes!=null)
            mineRes = f.get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (mineRes != null) {
            mineResultSet.updateStartDate(mineRes.getStartDate());
            mineResultSet.updateEndDate(mineRes.getEndDate());
            if (!mineResultSet.mineResults.keySet().contains(mineRes.getSource())) {
                mineResultSet.mineResults.put(mineRes.getSource(), new HashMap<String, MineResult>());
            }
            mineResultSet.mineResults.get(mineRes.getSource())
                    .put(mineRes.getSource().getSourceName() + mineRes.getGroup(), mineRes);
        }
    }
    return mineResultSet;

}

From source file:io.druid.indexing.overlord.ForkingTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    synchronized (tasks) {
        if (!tasks.containsKey(task.getId())) {
            tasks.put(task.getId(),/*from  ww  w. j av a  2  s . c om*/
                    new ForkingTaskRunnerWorkItem(task.getId(), exec.submit(new Callable<TaskStatus>() {
                        @Override
                        public TaskStatus call() {
                            final String attemptUUID = UUID.randomUUID().toString();
                            final File taskDir = new File(taskConfig.getBaseTaskDir(), task.getId());
                            final File attemptDir = new File(taskDir, attemptUUID);

                            final ProcessHolder processHolder;
                            final int childPort = portFinder.findUnusedPort();
                            try {
                                final Closer closer = Closer.create();
                                try {
                                    if (!attemptDir.mkdirs()) {
                                        throw new IOException(
                                                String.format("Could not create directories: %s", attemptDir));
                                    }

                                    final File taskFile = new File(attemptDir, "task.json");
                                    final File statusFile = new File(attemptDir, "status.json");
                                    final File logFile = new File(attemptDir, "log");

                                    // time to adjust process holders
                                    synchronized (tasks) {
                                        final ForkingTaskRunnerWorkItem taskWorkItem = tasks.get(task.getId());

                                        if (taskWorkItem.shutdown) {
                                            throw new IllegalStateException("Task has been shut down!");
                                        }

                                        if (taskWorkItem == null) {
                                            log.makeAlert("WTF?! TaskInfo disappeared!")
                                                    .addData("task", task.getId()).emit();
                                            throw new ISE("TaskInfo disappeared for task[%s]!", task.getId());
                                        }

                                        if (taskWorkItem.processHolder != null) {
                                            log.makeAlert("WTF?! TaskInfo already has a processHolder")
                                                    .addData("task", task.getId()).emit();
                                            throw new ISE("TaskInfo already has processHolder for task[%s]!",
                                                    task.getId());
                                        }

                                        final List<String> command = Lists.newArrayList();
                                        final String childHost = node.getHost();
                                        final String taskClasspath;
                                        if (task.getClasspathPrefix() != null
                                                && !task.getClasspathPrefix().isEmpty()) {
                                            taskClasspath = Joiner.on(File.pathSeparator)
                                                    .join(task.getClasspathPrefix(), config.getClasspath());
                                        } else {
                                            taskClasspath = config.getClasspath();
                                        }

                                        command.add(config.getJavaCommand());
                                        command.add("-cp");
                                        command.add(taskClasspath);

                                        Iterables.addAll(command,
                                                new QuotableWhiteSpaceSplitter(config.getJavaOpts()));

                                        // Override task specific javaOpts
                                        Object taskJavaOpts = task
                                                .getContextValue("druid.indexer.runner.javaOpts");
                                        if (taskJavaOpts != null) {
                                            Iterables.addAll(command,
                                                    new QuotableWhiteSpaceSplitter((String) taskJavaOpts));
                                        }

                                        for (String propName : props.stringPropertyNames()) {
                                            for (String allowedPrefix : config.getAllowedPrefixes()) {
                                                if (propName.startsWith(allowedPrefix)) {
                                                    command.add(String.format("-D%s=%s", propName,
                                                            props.getProperty(propName)));
                                                }
                                            }
                                        }

                                        // Override child JVM specific properties
                                        for (String propName : props.stringPropertyNames()) {
                                            if (propName.startsWith(CHILD_PROPERTY_PREFIX)) {
                                                command.add(String.format("-D%s=%s",
                                                        propName.substring(CHILD_PROPERTY_PREFIX.length()),
                                                        props.getProperty(propName)));
                                            }
                                        }

                                        // Override task specific properties
                                        final Map<String, Object> context = task.getContext();
                                        if (context != null) {
                                            for (String propName : context.keySet()) {
                                                if (propName.startsWith(CHILD_PROPERTY_PREFIX)) {
                                                    command.add(String.format("-D%s=%s",
                                                            propName.substring(CHILD_PROPERTY_PREFIX.length()),
                                                            task.getContextValue(propName)));
                                                }
                                            }
                                        }

                                        command.add(String.format("-Ddruid.host=%s", childHost));
                                        command.add(String.format("-Ddruid.port=%d", childPort));

                                        command.add("io.druid.cli.Main");
                                        command.add("internal");
                                        command.add("peon");
                                        command.add(taskFile.toString());
                                        command.add(statusFile.toString());
                                        String nodeType = task.getNodeType();
                                        if (nodeType != null) {
                                            command.add("--nodeType");
                                            command.add(nodeType);
                                        }

                                        jsonMapper.writeValue(taskFile, task);

                                        log.info("Running command: %s", Joiner.on(" ").join(command));
                                        taskWorkItem.processHolder = new ProcessHolder(
                                                new ProcessBuilder(ImmutableList.copyOf(command))
                                                        .redirectErrorStream(true).start(),
                                                logFile, childPort);

                                        processHolder = taskWorkItem.processHolder;
                                        processHolder.registerWithCloser(closer);
                                    }

                                    log.info("Logging task %s output to: %s", task.getId(), logFile);
                                    boolean runFailed = true;

                                    try (final OutputStream toLogfile = Files.asByteSink(logFile)
                                            .openBufferedStream()) {
                                        ByteStreams.copy(processHolder.process.getInputStream(), toLogfile);
                                        final int statusCode = processHolder.process.waitFor();
                                        log.info("Process exited with status[%d] for task: %s", statusCode,
                                                task.getId());
                                        if (statusCode == 0) {
                                            runFailed = false;
                                        }
                                    } finally {
                                        // Upload task logs
                                        taskLogPusher.pushTaskLog(task.getId(), logFile);
                                    }

                                    if (!runFailed) {
                                        // Process exited successfully
                                        return jsonMapper.readValue(statusFile, TaskStatus.class);
                                    } else {
                                        // Process exited unsuccessfully
                                        return TaskStatus.failure(task.getId());
                                    }
                                } catch (Throwable t) {
                                    throw closer.rethrow(t);
                                } finally {
                                    closer.close();
                                }
                            } catch (Throwable t) {
                                log.info(t, "Exception caught during execution");
                                throw Throwables.propagate(t);
                            } finally {
                                try {
                                    synchronized (tasks) {
                                        final ForkingTaskRunnerWorkItem taskWorkItem = tasks
                                                .remove(task.getId());
                                        if (taskWorkItem != null && taskWorkItem.processHolder != null) {
                                            taskWorkItem.processHolder.process.destroy();
                                        }
                                    }
                                    portFinder.markPortUnused(childPort);
                                    log.info("Removing temporary directory: %s", attemptDir);
                                    FileUtils.deleteDirectory(attemptDir);
                                } catch (Exception e) {
                                    log.error(e, "Suppressing exception caught while cleaning up task");
                                }
                            }
                        }
                    })));
        }

        return tasks.get(task.getId()).getResult();
    }
}

From source file:gobblin.tunnel.TunnelTest.java

@Test
public void mustHandleMultipleConnections() throws Exception {
    mockExample();//ww  w  . java 2s  .  c om
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);
    int clients = 5;

    final CountDownLatch startSignal = new CountDownLatch(1);
    final CountDownLatch doneSignal = new CountDownLatch(clients);

    ExecutorService executor = Executors.newFixedThreadPool(clients);
    try {
        final int tunnelPort = tunnel.getPort();

        List<Future<String>> results = new ArrayList<Future<String>>();

        for (int i = 0; i < clients; i++) {
            Future<String> result = executor.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    startSignal.await();

                    try {
                        return fetchContent(tunnelPort);
                    } finally {
                        doneSignal.countDown();
                    }
                }
            });

            results.add(result);
        }

        startSignal.countDown();
        doneSignal.await();

        for (Future<String> result : results) {
            assertNotNull(result.get());
        }
    } finally {
        tunnel.close();
    }
}