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.loopj.android.http.sample.AsyncBackgroundThreadSample.java

@Override
public RequestHandle executeSample(final AsyncHttpClient client, final String URL, final Header[] headers,
        HttpEntity entity, final ResponseHandlerInterface responseHandler) {

    final Activity ctx = this;
    FutureTask<RequestHandle> future = new FutureTask<>(new Callable<RequestHandle>() {
        public RequestHandle call() {
            Log.d(LOG_TAG, "Executing GET request on background thread");
            return client.get(ctx, URL, headers, null, responseHandler);
        }/* ww  w. ja v  a  2 s.  com*/
    });

    executor.execute(future);

    RequestHandle handle = null;
    try {
        handle = future.get(5, TimeUnit.SECONDS);
        Log.d(LOG_TAG, "Background thread for GET request has finished");
    } catch (Exception e) {
        Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    return handle;
}

From source file:at.ac.univie.isc.asio.metadata.AtosMetadataRepository.java

/**
 * Find metadata on the dataset with given {@code globalID}.
 *
 * @param globalIdentifier identifier of the target dataset
 * @return metadata on target dataset if present
 *///from ww  w.  j  a v  a2 s .com
public Observable<AtosDataset> findOne(final String globalIdentifier) {
    return checkedRequest(new Callable<AtosDataset>() {
        @Override
        public AtosDataset call() throws Exception {
            final Response response = endpoint.path("/metadata/{identifier}")
                    .resolveTemplate("identifier", globalIdentifier).request(MediaType.APPLICATION_XML_TYPE)
                    .get();
            switch (response.getStatus()) {
            case HttpStatus.SC_OK:
                return response.readEntity(AtosResourceMetadata.class).getDataset();
            case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            case HttpStatus.SC_NOT_FOUND:
                return null;
            default:
                throw new WebApplicationException("unexpected http response code", response.getStatus());
            }
        }
    });
}

From source file:org.zenoss.zep.impl.AbstractQueueListener.java

protected void rejectMessage(final Consumer<?> consumer, final Message<?> message, final boolean requeue) {
    try {/*from ww  w. j ava  2 s  . c o  m*/
        metricRegistry.timer(rejectMessageTimerName).time(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    consumer.rejectMessage(message, requeue);
                } catch (AmqpException e) {
                    logger.warn("Failed rejecting message", e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.topekalabs.synchronization.LockTest.java

@Test
public void testLockAndUnlock() {
    final long timeout = 500;

    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Integer> future = es.submit(new Callable<Integer>() {
        @Override//from   www  . j  a  v a 2  s . c  o  m
        public Integer call() throws Exception {
            Lock lock = lockClass.newInstance();
            lock.lock();
            lock.unlock();
            return 1;
        }
    });

    try {
        future.get(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException ex) {
        ErrorThrower.kill(ex);
    }

    es.shutdown();
}

From source file:net.pms.io.ByteProcessWrapperConsumer.java

@Override
@Nullable//from w  w  w . j  a v a 2s.co m
public FutureTask<byte[]> consume(@Nullable final InputStream inputStream, @Nullable String threadName) {
    if (inputStream == null) {
        return null;
    }
    Callable<byte[]> callable = new Callable<byte[]>() {

        @Override
        public byte[] call() throws Exception {
            byte[] result = IOUtils.toByteArray(inputStream);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Captured {} bytes of process output", result.length);
            }
            return result;
        }
    };
    FutureTask<byte[]> result = new FutureTask<byte[]>(callable);
    Thread runner;
    if (isBlank(threadName)) {
        runner = new Thread(result);
    } else {
        runner = new Thread(result, threadName);
    }
    runner.start();
    return result;
}

From source file:com.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetry() throws Exception {
    Timing timing = new Timing();
    final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(),
            timing.session(), timing.connection(), null, new RetryOneTime(1));
    SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
    retryLoop.start();//  ww  w.j a v  a 2s. c o m
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        while (retryLoop.shouldContinue()) {
            try {
                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        if (firstTime.compareAndSet(true, false)) {
                            Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                            KillSession.kill(client.getZooKeeper(), server.getConnectString());
                            client.getZooKeeper();
                            client.blockUntilConnectedOrTimedOut();
                        }

                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        return null;
                    }
                });

                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        Assert.assertFalse(firstTime.get());
                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        secondWasDone.set(true);
                        return null;
                    }
                });
            } catch (Exception e) {
                retryLoop.takeException(e);
            }
        }

        Assert.assertTrue(secondWasDone.get());
    } finally {
        retryLoop.close();
        IOUtils.closeQuietly(client);
    }
}

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

@RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD })
public Callable<ResponseEntity<Entity>> get(@PathVariable final String name,
        final EntityResponseBuilder<Entity> builder) {

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

        @Override/*from w w  w  .j  a  v a 2  s .  c  om*/
        public ResponseEntity<Entity> call() throws Exception {
            Entity entity = service.getEntity(name);
            return builder.entity(entity).etag().build();
        }
    };

}

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

private static Future<?> execute(final KeyedBarrier<String, Object> barrier, final String key,
        final Callable<Object> callable, final long timeout) {
    return executorService.submit(new Callable<Object>() {
        @Override//from ww w . ja va2 s  .  c  om
        public Object call() throws Exception {
            return barrier.execute(key, callable, timeout);
        }
    });
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ConferenceUserDaoImplTest.java

@Test
public void testEmptyQueries() throws Exception {
    this.execute(new Callable<Object>() {
        @Override/*from  w  w  w  . java2 s .c  o  m*/
        public Object call() {
            final ConferenceUser user = conferenceUserDao.getUser(1);
            assertNull(user);

            return null;
        }
    });
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final ConferenceUser user = conferenceUserDao.getUserByUniqueId("012332412");
            assertNull(user);

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final ConferenceUser user = conferenceUserDao.getExternalUserByEmail("user@example.com");
            assertNull(user);

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final ConferenceUser user = conferenceUserDao.getUser(1);
            final Set<Session> chairedSessions = conferenceUserDao.getChairedSessionsForUser(user);
            assertNull(chairedSessions);

            return null;
        }
    });

    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final ConferenceUser user = conferenceUserDao.getUser(1);
            final Set<Session> participatingSessions = conferenceUserDao.getNonChairedSessionsForUser(user);
            assertNull(participatingSessions);

            return null;
        }
    });
}

From source file:io.brooklyn.ambari.rest.RequestCheckRunnable.java

@Override
public void run() {
    boolean done = Repeater.create(String.format("Request %s status check", builder.request.toString()))
            .every(Duration.ONE_SECOND).until(new Callable<Boolean>() {
                @Override/*from  ww w.j  ava  2s .c o  m*/
                public Boolean call() throws Exception {
                    final String json = HttpTool
                            .httpGet(builder.httpClient, URI.create(builder.request.getHref()), builder.headers)
                            .getContentAsString();
                    final String status = JsonPath.read(json, "$.Requests.request_status");
                    if (!VALID_STATES.contains(status)) {
                        throw new RuntimeException("Request fails with state " + status
                                + ". Check here for details " + builder.request.getHref());
                    }
                    return StringUtils.equals(status, "COMPLETED");
                }
            }).limitTimeTo(builder.timeout).rethrowExceptionImmediately().run();

    if (!done) {
        throw new RuntimeException(builder.errorMessage);
    }
}