Example usage for java.util.concurrent Future Future

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

Introduction

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

Prototype

Future

Source Link

Usage

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

public <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request, true);

    CloseableHttpAsyncClient asyncHttpClient = options.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();//  www .  j  av a 2 s  . c  om
        AsyncIdleConnectionMonitorThread asyncIdleConnectionMonitorThread = (AsyncIdleConnectionMonitorThread) options
                .getOption(Option.ASYNC_MONITOR);
        asyncIdleConnectionMonitorThread.start();
    }

    final Future<org.apache.http.HttpResponse> future = asyncHttpClient.execute(requestObj,
            prepareCallback(responseClass, callback));

    return new Future<HttpResponse<T>>() {

        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        public boolean isCancelled() {
            return future.isCancelled();
        }

        public boolean isDone() {
            return future.isDone();
        }

        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }

        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout, unit);
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }
    };
}

From source file:com.msopentech.odatajclient.engine.communication.request.ODataStreamManager.java

/**
 * Closes the payload input stream and ask for an asynchronous response.
 *
 * @return <code>Future&lt;ODataResponse&gt;</code> about the executed request.
 *///w  w  w . j  a v a2  s.c om
public final Future<T> getAsyncResponse() {
    return new Future<T>() {

        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return futureWrap.getWrapped().cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isCancelled() {
            return futureWrap.getWrapped().isCancelled();
        }

        @Override
        public boolean isDone() {
            return futureWrap.getWrapped().isDone();
        }

        @Override
        public T get() throws InterruptedException, ExecutionException {
            return getResponse(0, TimeUnit.SECONDS);
        }

        @Override
        public T get(final long timeout, final TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {

            return getResponse(timeout, unit);
        }
    };
}

From source file:com.vmware.photon.controller.api.client.resource.ApiTestBase.java

@SuppressWarnings("unchecked")
public final void setupMocksForPagination(String serializedResponse, String serializedResponseForNextPage,
        String nextPageLink, int responseCode) throws IOException {
    this.asyncHttpClient = mock(CloseableHttpAsyncClient.class);
    this.httpClient = mock(HttpClient.class);

    doAnswer(new Answer<Object>() {
        @Override//from  ww  w .  j av  a2  s  .  c  om
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(this.asyncHttpClient).close();

    this.restClient = new RestClient("http://1.1.1.1", this.asyncHttpClient, this.httpClient);

    final HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(responseCode);
    when(httpResponse.getEntity())
            .thenReturn(new StringEntity(serializedResponse, ContentType.APPLICATION_JSON));

    final HttpResponse httpResponseForNextPage = mock(HttpResponse.class);
    StatusLine statusLineForNextPage = mock(StatusLine.class);
    when(httpResponseForNextPage.getStatusLine()).thenReturn(statusLineForNextPage);
    when(statusLineForNextPage.getStatusCode()).thenReturn(responseCode);
    when(httpResponseForNextPage.getEntity())
            .thenReturn(new StringEntity(serializedResponseForNextPage, ContentType.APPLICATION_JSON));

    final Future<HttpResponse> httpResponseFuture = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponse;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponse;
        }
    };

    final Future<HttpResponse> httpResponseFutureForNextPage = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponseForNextPage;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponseForNextPage;
        }
    };

    when(this.httpClient.execute(any(HttpUriRequest.class))).thenAnswer(new Answer<HttpResponse>() {
        @Override
        public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
            HttpUriRequest httpUriRequest = (HttpUriRequest) invocation.getArguments()[0];
            if (httpUriRequest.getURI().toString().contains(nextPageLink)) {
                return httpResponseForNextPage;
            }
            return httpResponse;
        }
    });

    when(this.asyncHttpClient.execute(any(HttpUriRequest.class), any(BasicHttpContext.class),
            any(FutureCallback.class))).thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    HttpUriRequest httpUriRequest = (HttpUriRequest) invocation.getArguments()[0];
                    if (httpUriRequest.getURI().toString().contains(nextPageLink)) {
                        if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                            ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                    .completed(httpResponseForNextPage);
                        }
                        return httpResponseFutureForNextPage;
                    }

                    if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                        ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
}

From source file:com.dtolabs.rundeck.plugin.resources.gcp.InstanceToNodeMapper.java

/**
 * Perform the query asynchronously and return the set of instances
 *
 *///from  w w  w.  j a  v  a  2  s .  c om
public Future<INodeSet> performQueryAsync() {
    logger.error("PerformQueryAsync start");
    //final AmazonEC2AsyncClient ec2;
    /*if(null!=credentials){
    ec2= new AmazonEC2AsyncClient(credentials, clientConfiguration, executorService);
    } else{
    ec2 = new AmazonEC2AsyncClient(new DefaultAWSCredentialsProviderChain(), clientConfiguration, executorService);
    }
    if (null != getEndpoint()) {
    ec2.setEndpoint(getEndpoint());
    }*/
    //final ArrayList<Filter> filters = buildFilters();

    //final Future<DescribeInstancesResult> describeInstancesRequest = ec2.describeInstancesAsync(
    //    new DescribeInstancesRequest().withFilters(filters));

    return new Future<INodeSet>() {

        public boolean cancel(boolean b) {
            return true;
            //return describeInstancesRequest.cancel(b);
        }

        public boolean isCancelled() {
            return true;
            //return describeInstancesRequest.isCancelled();
        }

        public boolean isDone() {
            return true;
            //return describeInstancesRequest.isDone();
        }

        public INodeSet get() throws InterruptedException, ExecutionException {
            //DescribeInstancesResult describeInstancesResult = describeInstancesRequest.get();

            final NodeSetImpl nodeSet = new NodeSetImpl();
            //final Set<Instance> instances = examineResult(describeInstancesResult);
            final Set<Instance> instances = query(compute, projectId);

            mapInstances(nodeSet, instances);
            return nodeSet;
        }

        public INodeSet get(final long l, final TimeUnit timeUnit)
                throws InterruptedException, ExecutionException, TimeoutException {
            //DescribeInstancesResult describeInstancesResult = describeInstancesRequest.get(l, timeUnit);

            final NodeSetImpl nodeSet = new NodeSetImpl();
            final Set<Instance> instances = query(compute, projectId);
            //final Set<Instance> instances = examineResult(describeInstancesResult);

            mapInstances(nodeSet, instances);
            return nodeSet;
        }
    };
}

From source file:gobblin.couchbase.writer.CouchbaseWriter.java

@Override
public Future<WriteResponse> write(final D record, final WriteCallback callback) {
    assertRecordWritable(record);/*from   w w  w.j a va2 s .  c om*/
    if (record instanceof TupleDocument) {
        ((TupleDocument) record).content().value1().retain();
    }
    Observable<D> observable = _bucket.async().upsert(record);
    if (callback == null) {
        return new WriteResponseFuture<>(
                observable.timeout(_operationTimeout, _operationTimeunit).toBlocking().toFuture(),
                _defaultWriteResponseMapper);
    } else {

        final AtomicBoolean callbackFired = new AtomicBoolean(false);
        final BlockingQueue<Pair<WriteResponse, Throwable>> writeResponseQueue = new ArrayBlockingQueue<>(1);

        final Future<WriteResponse> writeResponseFuture = new Future<WriteResponse>() {
            @Override
            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            @Override
            public boolean isCancelled() {
                return false;
            }

            @Override
            public boolean isDone() {
                return callbackFired.get();
            }

            @Override
            public WriteResponse get() throws InterruptedException, ExecutionException {
                Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.take();
                return getWriteResponseorThrow(writeResponseThrowablePair);
            }

            @Override
            public WriteResponse get(long timeout, TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                Pair<WriteResponse, Throwable> writeResponseThrowablePair = writeResponseQueue.poll(timeout,
                        unit);
                if (writeResponseThrowablePair == null) {
                    throw new TimeoutException("Timeout exceeded while waiting for future to be done");
                } else {
                    return getWriteResponseorThrow(writeResponseThrowablePair);
                }
            }
        };

        observable.timeout(_operationTimeout, _operationTimeunit).subscribe(new Subscriber<D>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                callbackFired.set(true);
                writeResponseQueue.add(new Pair<WriteResponse, Throwable>(null, e));
                callback.onFailure(e);
            }

            @Override
            public void onNext(D doc) {
                try {
                    callbackFired.set(true);
                    WriteResponse writeResponse = new GenericWriteResponse<D>(doc);
                    writeResponseQueue.add(new Pair<WriteResponse, Throwable>(writeResponse, null));
                    callback.onSuccess(writeResponse);
                } finally {
                    if (doc instanceof TupleDocument) {
                        ((TupleDocument) doc).content().value1().release();
                    }
                }
            }
        });
        return writeResponseFuture;
    }
}

From source file:com.alibaba.openapi.client.rpc.AlibabaClientReactor.java

public <T> Future<T> send(Request request, Class<T> resultType, ClientPolicy clientPolicy,
        final RequestPolicy requestPolicy, FutureCallback<T> callback) {
    final InvokeContext context = new InvokeContext();
    context.setRequest(request);//w w  w.  j ava  2s.  co m
    context.setPolicy(requestPolicy);
    context.setCallback(callback);
    context.setResultType(resultType);
    int serverPort = requestPolicy.isUseHttps() ? clientPolicy.getHttpsPort() : clientPolicy.getHttpPort();
    LoggerHelper.getClientLogger().finer(
            "Use " + (clientPolicy.isUseHttps() ? "https" : "http") + " connect and create SessionRequest");
    //SessionRequestCallback??
    //SessionRequest??
    final SessionRequest req = ioReactor.connect(
            new InetSocketAddress(clientPolicy.getServerHost(), serverPort), null, context,
            new SessionRequestCallbackTrigger());

    return new Future<T>() {
        private boolean cancelled = false;

        public boolean cancel(boolean mayInterruptIfRunning) {
            if (req.isCompleted() || cancelled) {
                return false;
            }
            cancelled = true;
            req.cancel();
            context.completed();
            return true;
        }

        public boolean isCancelled() {
            return cancelled;
        }

        public boolean isDone() {
            return context.isCompleted() || cancelled;
        }

        public T get() throws InterruptedException, ExecutionException {
            context.waitForComplete();
            return _get();
        }

        public T get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            context.waitForComplete(timeout, unit);
            return _get();
        }

        @SuppressWarnings("unchecked")
        private T _get() throws ExecutionException {
            Response response = ((InvokeContext) req.getAttachment()).getResponse();
            Throwable targetException = response.getException();
            if (targetException != null) {
                if (requestPolicy.getErrorHandler() != null && targetException instanceof OceanException) {
                    requestPolicy.getErrorHandler().handle((OceanException) targetException);
                }
                throw new ExecutionException(targetException.getMessage(), targetException);
            }
            return (T) response.getResult();
        }
    };
}

From source file:de.hopmann.msc.slave.service.PackageInstallationBean.java

public Future<InstallationContext> acquireInstallation(PackageResolved packageResolved,
        PackageInstallerHolder packageInstallerHolder) throws PackageNotFoundException {
    // TODO exception, close context to rollback on error

    final InstallationContext context = new InstallationContext();

    final Future<PackageInstallationEntity> installationFuture = acquireInstallation(packageResolved,
            packageInstallerHolder, context);

    return new Future<InstallationContext>() {

        @Override//from   www.  j av  a2 s.  c  o  m
        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean cancelled = installationFuture.cancel(mayInterruptIfRunning);
            try {
                // Close installation context to release resources
                context.close();
            } catch (Exception e) {
                log.log(Level.WARNING, "Could not close installation context", e);
            }
            return cancelled;
        }

        @Override
        public InstallationContext get() throws InterruptedException, ExecutionException {
            context.setInstallation(installationFuture.get());
            return context;
        }

        @Override
        public InstallationContext get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            context.setInstallation(installationFuture.get(timeout, unit));
            return context;
        }

        @Override
        public boolean isCancelled() {
            return installationFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return installationFuture.isDone();
        }
    };

}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

public static Future<Boolean> rockBlockIsReachable() {
    return new Future<Boolean>() {
        Boolean result = null;//from  www  .jav  a2 s.  c o  m
        boolean canceled = false;
        long start = System.currentTimeMillis();
        {

            if (System.currentTimeMillis() - lastSuccess < 15000) {
                result = true;
            }

            try {
                URL url = new URL("https://secure.rock7mobile.com/rockblock");
                int len = url.openConnection().getContentLength();
                if (len > 0)
                    lastSuccess = System.currentTimeMillis();
                result = len > 0;
            } catch (Exception e) {
                NeptusLog.pub().error(e);
                result = false;
            }
        }

        @Override
        public Boolean get() throws InterruptedException, ExecutionException {
            while (result == null) {
                Thread.sleep(100);
            }
            return result;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            canceled = true;
            return false;
        }

        @Override
        public Boolean get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            while (result == null) {
                Thread.sleep(100);
                if (System.currentTimeMillis() - start > unit.toMillis(timeout))
                    throw new TimeoutException("Time out while connecting");
            }
            return result;
        }

        @Override
        public boolean isCancelled() {
            return canceled;
        }

        @Override
        public boolean isDone() {
            return result != null;
        }
    };
}

From source file:it.units.malelab.ege.util.Utils.java

public static <V> Future<V> future(final V v) {
    return new Future<V>() {

        @Override/*from  w  w w.  ja v  a2s  .  c  om*/
        public boolean cancel(boolean mayInterruptIfRunning) {
            throw new UnsupportedOperationException("Not supported.");
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public V get() throws InterruptedException, ExecutionException {
            return v;
        }

        @Override
        public V get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return v;
        }
    };
}

From source file:org.cleverbus.component.externalcall.ExternalCallComponentTest.java

private Future<String> getStringBodyFuture(final Future<Exchange> reply) {
    return new Future<String>() {
        @Override//from ww w.  jav  a2  s  .c o  m
        public boolean cancel(boolean mayInterruptIfRunning) {
            return reply.cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isCancelled() {
            return reply.isCancelled();
        }

        @Override
        public boolean isDone() {
            return reply.isDone();
        }

        @Override
        public String get() throws InterruptedException, ExecutionException {
            return getReplyString(reply.get());
        }

        @Override
        public String get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return getReplyString(reply.get(timeout, unit));
        }

        private String getReplyString(Exchange exchange) throws InterruptedException, ExecutionException {
            throwExceptionOptionally(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class));
            throwExceptionOptionally(exchange.getException());
            return exchange.getOut().getBody(String.class);
        }

        private void throwExceptionOptionally(Exception exc) throws InterruptedException, ExecutionException {
            if (exc != null) {
                if (exc instanceof InterruptedException) {
                    throw (InterruptedException) exc;
                } else if (exc instanceof ExecutionException) {
                    throw (ExecutionException) exc;
                } else {
                    throw new ExecutionException(exc);
                }
            }
        }
    };
}