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:com.microsoft.windowsazure.management.scheduler.SchedulerIntegrationTestBase.java

protected static void createCloudServiceManagementService() throws Exception {
    Configuration config = createConfiguration();
    config.setProperty(ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER,
            new DefaultHttpRequestRetryHandler());
    cloudServiceManagementClient = CloudServiceManagementService.create(config);
    addClient((ServiceClient<?>) cloudServiceManagementClient, new Callable<Void>() {
        @Override//from  w  w w.j  a  v  a2 s  .  com
        public Void call() throws Exception {
            createCloudServiceManagementService();
            return null;
        }
    });
}

From source file:net.eusashead.hateoas.response.argumentresolver.AsyncEntityController.java

@RequestMapping(method = RequestMethod.PUT)
public Callable<ResponseEntity<Void>> put(@RequestBody final Entity entity,
        final PutResponseBuilder<Entity> builder) {

    return new Callable<ResponseEntity<Void>>() {

        @Override/*from ww  w  . j  a  v  a 2  s  .com*/
        public ResponseEntity<Void> call() throws Exception {
            Entity modified = service.save(entity);
            return builder.entity(modified).etag().build();
        }
    };
}

From source file:com.microsoft.windowsazure.management.LocationOperationsImpl.java

/**
* The List Locations operation lists all of the data center locations that
* are valid for your subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/gg441293.aspx for
* more information)//  ww w.jav a  2  s.co  m
*
* @return The List Locations operation response.
*/
@Override
public Future<LocationsListResponse> listAsync() {
    return this.getClient().getExecutorService().submit(new Callable<LocationsListResponse>() {
        @Override
        public LocationsListResponse call() throws Exception {
            return list();
        }
    });
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void testWaitingProcessKilledServer() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    try {//w ww.j  a va  2s.c  o m
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);

        final AtomicBoolean isFirst = new AtomicBoolean(true);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(
                Executors.newFixedThreadPool(2));
        for (int i = 0; i < 2; ++i) {
            service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    InterProcessLock lock = makeLock(client);
                    lock.acquire();
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            timing.sleepABit();

                            server.stop();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            server = new TestingServer(server.getPort(), server.getTempDirectory());
                        }
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            // ignore
                        }
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < 2; ++i) {
            service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:gobblin.compliance.restore.ComplianceRestoreJob.java

public void run() throws IOException {
    Preconditions.checkNotNull(this.finder, "Dataset finder class is not set");
    List<Dataset> datasets = this.finder.findDatasets();
    this.finishCleanSignal = Optional.of(new CountDownLatch(datasets.size()));
    for (final Dataset dataset : datasets) {
        ListenableFuture<Void> future = this.service.submit(new Callable<Void>() {
            @Override/*www .ja  v  a  2  s.  co m*/
            public Void call() throws Exception {
                if (dataset instanceof RestorableDataset) {
                    log.info("Trying to restore");
                    ((RestorableDataset) dataset).restore();
                } else {
                    log.warn("Not an instance of " + RestorableDataset.class + " Dataset won't be restored "
                            + dataset.datasetURN());
                }
                return null;
            }
        });
        Futures.addCallback(future, new FutureCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void result) {
                ComplianceRestoreJob.this.finishCleanSignal.get().countDown();
                log.info("Successfully restored: " + dataset.datasetURN());
            }

            @Override
            public void onFailure(Throwable t) {
                ComplianceRestoreJob.this.finishCleanSignal.get().countDown();
                log.warn("Exception caught when restoring " + dataset.datasetURN() + ".", t);
                ComplianceRestoreJob.this.throwables.add(t);
                ComplianceRestoreJob.this.eventSubmitter.submit(ComplianceEvents.Restore.FAILED_EVENT_NAME,
                        ImmutableMap.of(ComplianceEvents.FAILURE_CONTEXT_METADATA_KEY,
                                ExceptionUtils.getFullStackTrace(t), ComplianceEvents.DATASET_URN_METADATA_KEY,
                                dataset.datasetURN()));
            }
        });
    }
}

From source file:bear.ssh.MyStreamCopier.java

public Future<TaskResult<?>> spawn(ExecutorService service, final long finishAtMs) {
    this.finishAtMs = finishAtMs;
    return service.submit(new CatchyCallable<TaskResult<?>>(new Callable<TaskResult<?>>() {
        @Override//from ww w.  j  a  va  2s .c  o m
        public TaskResult<?> call() {
            boolean interrupted = false;

            while (!stopFlag) {
                interrupted = Thread.currentThread().isInterrupted();

                if (interrupted)
                    break;

                try {
                    if (nonBlockingCopy() == -1) {
                        break;
                    }

                    if (MyStreamCopier.this.finishAtMs != -1
                            && MyStreamCopier.this.finishAtMs < System.currentTimeMillis()) {
                        break;
                    }

                    listener.reportProgress(count, null, -1);

                    if (!(periodMs <= 0 && periodNano <= 0)) {
                        Thread.sleep(periodMs, periodNano);
                    }
                } catch (Exception e) {
                    if (e instanceof InterruptedIOException) {
                        GlobalContext.AwareThread t = (GlobalContext.AwareThread) Thread.currentThread();
                        log.error("interrupted by: {}, at: {}, I am at {}", t.getInterruptedBy(),
                                Throwables.getStackTraceAsString(t.getInterruptedAt()),
                                Throwables.getStackTraceAsString(e));
                    } else {
                        log.error("", e);
                    }
                    return TaskResult.of(e);
                }
            }

            try {
                nonBlockingCopy();

                // try one more time as it's buggy
                // they asked us to stop but did not interrupt, let's have one more chance
                //todo remove this
                /*
                                    if(stopFlag){
                try {
                    Thread.sleep(periodMs, periodNano);
                } catch (InterruptedException e) {
                    //they are interrupting our attempt to wait
                    //we cancel and try to instantly copy...
                    nonBlockingCopy();
                }
                                    }
                */
            } catch (Exception e) {
                log.error("", e);

                return TaskResult.of(e);
            } finally {
                if (stopFlag || interrupted) {
                    IOUtils.closeQuietly(in);
                }
            }

            finished = true;

            return TaskResult.OK;
        }
    }));
}

From source file:com.cognifide.aet.job.common.collectors.source.SourceCollector.java

private byte[] getContent() throws ProcessingException {
    byte[] content;
    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
        @Override//from w w w  .  ja  va 2  s.  c  o  m
        public Object call() throws IOException {
            return httpRequestBuilder.executeRequest().getContent();
        }
    };
    Future<Object> future = executor.submit(task);
    try {
        content = (byte[]) future.get(timeoutValue, TimeUnit.MILLISECONDS);
    } catch (TimeoutException | InterruptedException | ExecutionException e) {
        throw new ProcessingException(e.getMessage(), e);
    } finally {
        future.cancel(true);
    }
    return content;
}

From source file:bolts.WebViewAppLinkResolver.java

@Override
public Task<AppLink> getAppLinkFromUrlInBackground(final Uri url) {
    final Capture<String> content = new Capture<String>();
    final Capture<String> contentType = new Capture<String>();
    return Task.callInBackground(new Callable<Void>() {
        @Override/*from   www  .j  av a 2 s  .  c o m*/
        public Void call() throws Exception {
            URL currentURL = new URL(url.toString());
            URLConnection connection = null;
            while (currentURL != null) {
                // Fetch the content at the given URL.
                connection = currentURL.openConnection();
                if (connection instanceof HttpURLConnection) {
                    // Unfortunately, this doesn't actually follow redirects if they go from http->https,
                    // so we have to do that manually.
                    ((HttpURLConnection) connection).setInstanceFollowRedirects(true);
                }
                connection.setRequestProperty(PREFER_HEADER, META_TAG_PREFIX);
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() >= 300 && httpConnection.getResponseCode() < 400) {
                        currentURL = new URL(httpConnection.getHeaderField("Location"));
                        httpConnection.disconnect();
                    } else {
                        currentURL = null;
                    }
                } else {
                    currentURL = null;
                }
            }

            try {
                content.set(readFromConnection(connection));
                contentType.set(connection.getContentType());
            } finally {
                if (connection instanceof HttpURLConnection) {
                    ((HttpURLConnection) connection).disconnect();
                }
            }
            return null;
        }
    }).onSuccessTask(new Continuation<Void, Task<JSONArray>>() {
        @Override
        public Task<JSONArray> then(Task<Void> task) throws Exception {
            // Load the content in a WebView and use JavaScript to extract the meta tags.
            final TaskCompletionSource<JSONArray> tcs = new TaskCompletionSource<>();
            final WebView webView = new WebView(context);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setNetworkAvailable(false);
            webView.setWebViewClient(new WebViewClient() {
                private boolean loaded = false;

                private void runJavaScript(WebView view) {
                    if (!loaded) {
                        // After the first resource has been loaded (which will be the pre-populated data)
                        // run the JavaScript meta tag extraction script
                        loaded = true;
                        view.loadUrl(TAG_EXTRACTION_JAVASCRIPT);
                    }
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    runJavaScript(view);
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    super.onLoadResource(view, url);
                    runJavaScript(view);
                }
            });
            // Inject an object that will receive the JSON for the extracted JavaScript tags
            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void setValue(String value) {
                    try {
                        tcs.trySetResult(new JSONArray(value));
                    } catch (JSONException e) {
                        tcs.trySetError(e);
                    }
                }
            }, "boltsWebViewAppLinkResolverResult");
            String inferredContentType = null;
            if (contentType.get() != null) {
                inferredContentType = contentType.get().split(";")[0];
            }
            webView.loadDataWithBaseURL(url.toString(), content.get(), inferredContentType, null, null);
            return tcs.getTask();
        }
    }, Task.UI_THREAD_EXECUTOR).onSuccess(new Continuation<JSONArray, AppLink>() {
        @Override
        public AppLink then(Task<JSONArray> task) throws Exception {
            Map<String, Object> alData = parseAlData(task.getResult());
            AppLink appLink = makeAppLinkFromAlData(alData, url);
            return appLink;
        }
    });
}

From source file:dk.clanie.actor.ActorExecutionInterceptor.java

public Object invoke(final MethodInvocation invocation) throws Throwable {
    @SuppressWarnings("rawtypes")
    Future result = this.executor.submit(new Callable<Object>() {
        public Object call() throws Exception {
            try {
                Object result = invocation.proceed();
                if (result instanceof Future) {
                    return ((Future) result).get();
                }/*from   w  ww  .  ja  v a2s. c o m*/
            } catch (Throwable ex) {
                ReflectionUtils.rethrowException(ex);
            }
            return null;
        }
    });
    Class<?> returnType = invocation.getMethod().getReturnType();
    if (Future.class.isAssignableFrom(returnType)) {
        return result;
    } else if (Void.TYPE != returnType) {
        try {
            return result.get();
        } catch (Throwable ex) {
            ReflectionUtils.rethrowException(ex);
        }
    }
    return null;
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphoreCluster.java

@Test
public void testKilledServerWithEnsembleProvider() throws Exception {
    final int CLIENT_QTY = 10;
    final Timing timing = new Timing();
    final String PATH = "/foo/bar/lock";

    ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY);
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
    TestingCluster cluster = new TestingCluster(3);
    try {/*from  w  ww.  java 2 s .  co m*/
        cluster.start();

        final AtomicReference<String> connectionString = new AtomicReference<String>(
                cluster.getConnectString());
        final EnsembleProvider provider = new EnsembleProvider() {
            @Override
            public void start() throws Exception {
            }

            @Override
            public String getConnectionString() {
                return connectionString.get();
            }

            @Override
            public void close() throws IOException {
            }
        };

        final Semaphore acquiredSemaphore = new Semaphore(0);
        final AtomicInteger acquireCount = new AtomicInteger(0);
        final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY);
        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.builder().ensembleProvider(provider)
                            .sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection())
                            .retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
                    try {
                        final Semaphore suspendedSemaphore = new Semaphore(0);
                        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
                            @Override
                            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                                if ((newState == ConnectionState.SUSPENDED)
                                        || (newState == ConnectionState.LOST)) {
                                    suspendedLatch.countDown();
                                    suspendedSemaphore.release();
                                }
                            }
                        });

                        client.start();

                        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1);

                        while (!Thread.currentThread().isInterrupted()) {
                            Lease lease = null;
                            try {
                                lease = semaphore.acquire();
                                acquiredSemaphore.release();
                                acquireCount.incrementAndGet();
                                suspendedSemaphore.acquire();
                            } catch (Exception e) {
                                // just retry
                            } finally {
                                if (lease != null) {
                                    acquireCount.decrementAndGet();
                                    IOUtils.closeQuietly(lease);
                                }
                            }
                        }
                    } finally {
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        Assert.assertEquals(1, acquireCount.get());

        cluster.close();
        timing.awaitLatch(suspendedLatch);
        timing.forWaiting().sleepABit();
        Assert.assertEquals(0, acquireCount.get());

        cluster = new TestingCluster(3);
        cluster.start();

        connectionString.set(cluster.getConnectString());
        timing.forWaiting().sleepABit();

        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        timing.forWaiting().sleepABit();
        Assert.assertEquals(1, acquireCount.get());
    } finally {
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdownNow();
        IOUtils.closeQuietly(cluster);
    }
}