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:com.vmware.photon.controller.clustermanager.clients.HttpClientTestUtil.java

@SuppressWarnings("unchecked")
public static CloseableHttpAsyncClient setupMocks(String serializedResponse, int responseCode)
        throws IOException {
    CloseableHttpAsyncClient asyncHttpClient = Mockito.mock(CloseableHttpAsyncClient.class);

    Mockito.doAnswer(new Answer<Object>() {
        @Override//  w  w  w . j a v a  2  s. c  o m
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(asyncHttpClient).close();

    final HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);
    Mockito.when(statusLine.getStatusCode()).thenReturn(responseCode);
    Mockito.when(httpResponse.getEntity())
            .thenReturn(new StringEntity(serializedResponse, 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;
        }
    };

    Mockito.when(
            asyncHttpClient.execute(Matchers.any(HttpUriRequest.class), Matchers.any(BasicHttpContext.class),
                    Matchers.any(org.apache.http.concurrent.FutureCallback.class)))
            .thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (invocation.getArguments()[2] != null) {
                        ((org.apache.http.concurrent.FutureCallback<HttpResponse>) invocation.getArguments()[2])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
    return asyncHttpClient;
}

From source file:org.wisdom.test.http.HttpClientHelper.java

/**
 * Emits an asynchronous request./*from   w  w w . j  a  va 2  s  .com*/
 *
 * @param request       the request
 * @param responseClass the response class
 * @param callback      the completion callback
 * @param <T>           the type of the expected result
 * @return the future to retrieve the result
 */
public static <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request);

    CloseableHttpAsyncClient asyncHttpClient = ClientFactory.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();
    }

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

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

        /**
         * Cancels the request.
         *
         * @param mayInterruptIfRunning whether or not we need to interrupt the request.
         * @return {@literal true} if the task is successfully canceled.
         */
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        /**
         * @return whether the future is cancelled.
         */
        public boolean isCancelled() {
            return future.isCancelled();
        }

        /**
         * @return whether the result is available.
         */
        public boolean isDone() {
            return future.isDone();
        }

        /**
         * Gets the result.
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         */
        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<>(httpResponse, responseClass);
        }

        /**
         * Gets the result.
         * @param timeout timeout configuration
         * @param unit unit timeout
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         * @throws TimeoutException if the set time out is reached before the completion of the request.
         */
        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout * TimeUtils.TIME_FACTOR, unit);
            return new HttpResponse<>(httpResponse, responseClass);
        }
    };
}

From source file:com.wolvereness.overmapped.lib.MultiProcessor.java

@Override
public <T> Future<T> submit(final Callable<T> task) {
    super.checkShutdown();
    try {//from   ww w.  j a  va 2  s. c om
        final T object = task.call();
        return new Future<T>() {
            @Override
            public boolean cancel(final boolean mayInterruptIfRunning) {
                return false;
            }

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

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

            @Override
            public T get() throws InterruptedException, ExecutionException {
                return object;
            }

            @Override
            public T get(final long timeout, final TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                return object;
            }
        };
    } catch (final Exception exception) {
        final Exception ex = exception;
        return new Future<T>() {
            @Override
            public boolean cancel(final boolean mayInterruptIfRunning) {
                return false;
            }

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

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

            @Override
            public T get() throws InterruptedException, ExecutionException {
                throw new ExecutionException(ex);
            }

            @Override
            public T get(final long timeout, final TimeUnit unit)
                    throws InterruptedException, ExecutionException, TimeoutException {
                throw new ExecutionException(ex);
            }
        };
    }
}

From source file:com.vmware.photon.controller.nsxclient.apis.NsxClientApiTest.java

protected void setupMocks(String serializedResponse, int responseCode) throws IOException {
    CloseableHttpAsyncClient asyncClient = mock(CloseableHttpAsyncClient.class);
    doAnswer(invocation -> null).when(asyncClient).close();
    restClient = new RestClient("https://1.2.3.4", "username", "password", asyncClient);

    final HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(responseCode);

    if (serializedResponse != null) {
        when(httpResponse.getEntity())//from  ww  w  . j a  va2 s . co  m
                .thenReturn(new StringEntity(serializedResponse, 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;
        }
    };

    when(asyncClient.execute(any(HttpUriRequest.class), any(BasicHttpContext.class), any(FutureCallback.class)))
            .thenAnswer(invocation -> {
                if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                    ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                            .completed(httpResponse);
                }
                return httpResponseFuture;
            });
}

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

public final void setupMocks(String serializedResponse, int responseCode) throws IOException {
    this.asyncHttpClient = mock(CloseableHttpAsyncClient.class);
    this.httpClient = mock(HttpClient.class);

    doAnswer(new Answer() {
        @Override/*from w  w w .ja  va  2s  .c  o m*/
        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 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;
        }
    };

    when(this.httpClient.execute(any(HttpUriRequest.class))).thenReturn(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 {
                    if (invocation.getArguments()[2] != null) {
                        ((FutureCallback<HttpResponse>) invocation.getArguments()[2]).completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
}

From source file:com.blacklocus.qs.worker.WorkerQueueItemHandler.java

@SuppressWarnings("unchecked")
@Override/*from   w w  w .j a v a2 s .c o m*/
public void withFuture(QSTaskModel task, final Future<Pair<QSTaskModel, Object>> future) {
    // I don't know if this is useful or not.

    QSWorker worker = workers.get(task.handler);
    if (worker == null) {
        throw new RuntimeException("No worker available for worker identifier: " + task.handler);
    }

    final TaskKitFactory factory = new TaskKitFactory(task, worker, logService, workerIdService);
    worker.withFuture(factory, new Future<Pair<TaskKitFactory, Object>>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

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

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

        @Override
        public Pair<TaskKitFactory, Object> get() throws InterruptedException, ExecutionException {
            Pair<QSTaskModel, Object> theFuture = future.get();
            return Pair.of(factory, theFuture.getRight());
        }

        @Override
        public Pair<TaskKitFactory, Object> get(long timeout,
                @SuppressWarnings("NullableProblems") TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            Pair<QSTaskModel, Object> theFuture = future.get(timeout, unit);
            return Pair.of(factory, theFuture.getRight());
        }
    });
}

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

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

    doAnswer(new Answer<Object>() {
        @Override//from   w  w w  . j av  a  2s  . c o m
        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 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;
        }
    };

    when(this.httpClient.execute(any(HttpUriRequest.class))).thenReturn(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 {
                    if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                        ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
}

From source file:com.vmware.photon.controller.clustermanager.clients.HttpClientTestUtil.java

@SuppressWarnings("unchecked")
public static CloseableHttpAsyncClient setupMocksToThrowInCallback(final Exception exceptionToThrow)
        throws IOException {
    CloseableHttpAsyncClient asyncHttpClient = Mockito.mock(CloseableHttpAsyncClient.class);

    Mockito.doAnswer(new Answer<Object>() {
        @Override// w  w w .j av a2s .com
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(asyncHttpClient).close();

    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 null;
        }

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

    // async http request
    Mockito.when(
            asyncHttpClient.execute(Matchers.any(HttpUriRequest.class), Matchers.any(BasicHttpContext.class),
                    (org.apache.http.concurrent.FutureCallback<HttpResponse>) Matchers.any()))
            .thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (invocation.getArguments()[2] != null) {
                        ((org.apache.http.concurrent.FutureCallback<HttpResponse>) invocation.getArguments()[2])
                                .failed(exceptionToThrow);
                    }
                    return httpResponseFuture;
                }
            });
    return asyncHttpClient;
}

From source file:org.apache.rave.opensocial.service.impl.CoinGroupService.java

/**
 * Get all groups from an opensocial endpoint.
 *
 * http://localhost:8080/social/rest/groups/urn:collab:person:test.surfguest.nl:alle.veenstra
 *
 * @param userId/*from www  .j av  a2s . c o  m*/
 * @param options
 * @param fields
 * @param token
 * @return
 */
public Future<RestfulCollection<Group>> getGroups(UserId userId, CollectionOptions options, Set<String> fields,
        SecurityToken token) {

    OAuthService service = new ServiceBuilder().provider(new OpenConextApi10aTwoLegged()).apiKey(oauthKey)
            .apiSecret(oauthSecret).scope(OAUTH_OPENCONEXT_API_READ_SCOPE).callback("oob")
            .signatureType(SignatureType.QueryString).debug().build();

    OAuthRequest req = new OAuthRequest(Verb.GET,
            apiLocation + "social/rest/groups/" + userId.getUserId(token));
    service.signRequest(new Token("", ""), req);
    Response response = req.send();

    final String bodyText = response.getBody();
    logger.debug("Response body: {}", bodyText);

    ObjectMapper om = new ObjectMapper();
    Group20Entry group20Entry1 = null;
    try {
        group20Entry1 = om.readValue(bodyText, Group20Entry.class);
    } catch (IOException e) {
        logger.error("Unable to parse JSON", e);
        group20Entry1 = new Group20Entry();
    }

    final List<Group20> entry = group20Entry1.getEntry();

    final List<Group> groups = new ArrayList<Group>();

    for (Group20 group20 : entry) {
        GroupImpl group = new GroupImpl();
        group.setDescription(group20.getDescription());
        group.setTitle(group20.getTitle());
        GroupId groupId = new GroupId(GroupId.Type.groupId, group20.getId());
        group.setId(groupId);
        groups.add(group);
    }

    final RestfulCollection<Group> groupRestfulCollection = new RestfulCollection<Group>(groups);
    return new Future<RestfulCollection<Group>>() {
        public boolean cancel(final boolean b) {
            return false;
        }

        public boolean isCancelled() {
            return false;
        }

        public boolean isDone() {
            return true;
        }

        public RestfulCollection<Group> get() throws InterruptedException, ExecutionException {
            return groupRestfulCollection;
        }

        public RestfulCollection<Group> get(final long l, final TimeUnit timeUnit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return groupRestfulCollection;
        }
    };
}

From source file:org.apache.olingo.client.core.communication.request.AbstractODataStreamManager.java

/**
 * {@inheritDoc}/*from  www . ja v a 2s .c om*/
 */
@Override
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);
        }
    };
}