Java 类org.apache.http.concurrent.FutureCallback 实例源码

项目:helios-skydns    文件:MiniEtcdClient.java   
Future<HttpResponse> delete(final String key) {
  final URI uri = URI.create(baseUri + key);
  return httpClient.execute(new HttpDelete(uri), new FutureCallback<HttpResponse>() {
    @Override
    public void cancelled() {
      log.warn("Attempt to delete {} to was cancelled", key);
    }

    @Override
    public void completed(HttpResponse arg0) {
      log.info("Succeeded deleting {}", key);
    }

    @Override
    public void failed(Exception e) {
      log.warn("Failed deleting {}", key, e);
    }
  });
}
项目:ZTLib    文件:AbstractConnPool.java   
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    Args.notNull(route, "Route");
    Asserts.check(!this.isShutDown, "Connection pool shut down");
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                final long timeout,
                final TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);
            onLease(entry);
            return entry;
        }

    };
}
项目:ZTLib    文件:FutureRequestExecutionService.java   
/**
 * Schedule a request for execution.
 *
 * @param <T>
 *
 * @param request
 *            request to execute
 * @param context
 *            optional context; use null if not needed.
 * @param responseHandler
 *            handler that will process the response.
 * @param callback
 *            callback handler that will be called when the request is scheduled,
 *            started, completed, failed, or cancelled.
 * @return HttpAsyncClientFutureTask for the scheduled request.
 * @throws InterruptedException
 */
public <T> HttpRequestFutureTask<T> execute(
        final HttpUriRequest request,
        final HttpContext context,
        final ResponseHandler<T> responseHandler,
        final FutureCallback<T> callback) {
    if(closed.get()) {
        throw new IllegalStateException("Close has been called on this httpclient instance.");
    }
    metrics.getScheduledConnections().incrementAndGet();
    final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
        httpclient, request, context, responseHandler, callback, metrics);
    final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
        request, callable);
    executorService.execute(httpRequestFutureTask);

    return httpRequestFutureTask;
}
项目:Mob-Platform    文件:ServiceCallManager_callServiceWith_UnitTests.java   
@SuppressWarnings("unchecked")
public ServiceCallManager_callServiceWith_UnitTests(String serviceCall, String data, String contentType, String serviceEndpoint, Map<String,String> tokenLookup, HttpResponse httpResponse, HttpResponse expectedResponse, boolean isDataTest) throws InterruptedException, ExecutionException
{
    this.serviceCall = serviceCall;
    this.expectedResponse = expectedResponse;
    this.data = data;
    this.contentType = contentType;
    this.isDataTest = isDataTest;

    this.context = mock(ServiceCallContext.class);
    when(this.context.getTokenLookup()).thenReturn(tokenLookup);

    IServiceContracts contract = mock(IServiceContracts.class);
    when(contract.getEndpointFromAlias(serviceCall, context)).thenReturn(serviceEndpoint);

    Future<HttpResponse> response = mock(Future.class);
    when(response.get()).thenReturn(httpResponse);

    this.client = mock(DefaultHttpAsyncClient.class);
    when(this.client.execute(any(HttpUriRequest.class), any(FutureCallback.class))).thenReturn(response);

    this.service.setHttpClient(client)
                .setServiceContracts(contract);
}
项目:opentsdb-elasticsearch    文件:TestDefaultUIDMetaSchema.java   
@SuppressWarnings("unchecked")
@Before
public void before() throws Exception {
  config = new ESPluginConfig(new Config(false));
  client = mock(CloseableHttpAsyncClient.class);
  es = mock(ElasticSearch.class);
  meta = new UIDMeta(UniqueIdType.METRIC, new byte[] { 1 }, "sys.cpu.user");
  index = config.getString("tsd.search.elasticsearch.index");
  doc_type = config.getString("tsd.search.elasticsearch.uidmeta_type");

  when(es.httpClient()).thenReturn(client);
  when(es.host()).thenReturn(HOST);
  when(es.index()).thenReturn(index);
  when(es.config()).thenReturn(config);
  when(client.execute(any(HttpUriRequest.class), 
      any(FutureCallback.class)))
    .thenAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        request = (HttpUriRequest) invocation.getArguments()[0];
        cb = (FutureCallback<HttpResponse>) invocation.getArguments()[1];
        return null;
      }
    });
}
项目:wechat-mall    文件:AsynHttpClient.java   
public static Future<HttpResponse> GET(String url, FutureCallback<HttpResponse> callback,
        Map<String, String> headers) {
    HttpGet get = new HttpGet(url);
    headers.forEach((key, value) -> {
        get.setHeader(key, value);
    });
    return HTTP_CLIENT.execute(get, callback);
}
项目:wechat-mall    文件:AsynHttpClient.java   
public static Future<HttpResponse> POST(String url, FutureCallback<HttpResponse> callback,
        List<NameValuePair> params, String encoding, Map<String, String> headers) {
    HttpPost post = new HttpPost(url);
    headers.forEach((key, value) -> {
        post.setHeader(key, value);
    });
    HttpEntity entity = new UrlEncodedFormEntity(params, HttpClientUtil.getEncode(encoding));
    post.setEntity(entity);
    return HTTP_CLIENT.execute(post, callback);
}
项目:elasticsearch_my    文件:RemoteScrollableHitSourceTests.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testTooLargeResponse() throws Exception {
    ContentTooLongException tooLong = new ContentTooLongException("too long!");
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class),
            any(HttpClientContext.class), any(FutureCallback.class))).then(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HeapBufferedAsyncResponseConsumer consumer = (HeapBufferedAsyncResponseConsumer) invocationOnMock.getArguments()[1];
            FutureCallback callback = (FutureCallback) invocationOnMock.getArguments()[3];
            assertEquals(new ByteSizeValue(100, ByteSizeUnit.MB).bytesAsInt(), consumer.getBufferLimit());
            callback.failed(tooLong);
            return null;
        }
    });
    RemoteScrollableHitSource source = sourceWithMockedClient(true, httpClient);

    AtomicBoolean called = new AtomicBoolean();
    Consumer<Response> checkResponse = r -> called.set(true);
    Throwable e = expectThrows(RuntimeException.class,
            () -> source.doStartNextScroll(FAKE_SCROLL_ID, timeValueMillis(0), checkResponse));
    // Unwrap the some artifacts from the test
    while (e.getMessage().equals("failed")) {
        e = e.getCause();
    }
    // This next exception is what the user sees
    assertEquals("Remote responded with a chunk that was too large. Use a smaller batch size.", e.getMessage());
    // And that exception is reported as being caused by the underlying exception returned by the client
    assertSame(tooLong, e.getCause());
    assertFalse(called.get());
}
项目:elasticsearch_my    文件:RestClientSingleHostTests.java   
/**
 * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client
 */
@SuppressWarnings("unchecked")
public void testInternalHttpRequest() throws Exception {
    ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor.forClass(HttpAsyncRequestProducer.class);
    int times = 0;
    for (String httpMethod : getHttpMethods()) {
        HttpUriRequest expectedRequest = performRandomRequest(httpMethod);
        verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(),
                any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class));
        HttpUriRequest actualRequest = (HttpUriRequest)requestArgumentCaptor.getValue().generateRequest();
        assertEquals(expectedRequest.getURI(), actualRequest.getURI());
        assertEquals(expectedRequest.getClass(), actualRequest.getClass());
        assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders());
        if (expectedRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity();
            if (expectedEntity != null) {
                HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity();
                assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity));
            }
        }
    }
}
项目:elasticsearch_my    文件:RestClientMultipleHostsTests.java   
@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class),
           any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest();
            HttpHost httpHost = requestProducer.getTarget();
            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            //return the desired status code or exception depending on the path
            if (request.getURI().getPath().equals("/soe")) {
                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/coe")) {
                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/ioe")) {
                futureCallback.failed(new IOException(httpHost.toString()));
            } else {
                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, "");
                futureCallback.completed(new BasicHttpResponse(statusLine));
            }
            return null;
        }
    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}
项目:lams    文件:AbstractConnPool.java   
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    if (route == null) {
        throw new IllegalArgumentException("Route may not be null");
    }
    if (this.isShutDown) {
        throw new IllegalStateException("Connection pool shut down");
    }
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                long timeout,
                TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            return getPoolEntryBlocking(route, state, timeout, tunit, this);
        }

    };
}
项目:HiTSDB-Client    文件:HttpClient.java   
private void executeCallback(HttpEntityEnclosingRequestBase request, String json, FutureCallback<HttpResponse> httpCallback) {
    if (json != null && json.length() > 0) {
        request.addHeader("Content-Type", "application/json");
        if (!this.httpCompress) {
            request.setEntity(generateStringEntity(json));
        } else {
            request.addHeader("Accept-Encoding", "gzip, deflate");
            request.setEntity(generateGZIPCompressEntity(json));
        }
    }

    FutureCallback<HttpResponse> responseCallback = null;
    if (httpCallback != null) {
        unCompletedTaskNum.incrementAndGet();
        responseCallback = this.httpResponseCallbackFactory.wrapUpBaseHttpFutureCallback(httpCallback);
    }

    httpclient.execute(request,responseCallback);
}
项目:HiTSDB-Client    文件:HttpResponseCallbackFactory.java   
public FutureCallback<HttpResponse> createBatchPutDataCallback(
            final String address,
        final AbstractBatchPutCallback<?> batchPutCallback,
        final List<Point> pointList,
        final HiTSDBConfig config,
        final int batchPutRetryCount
) {
    FutureCallback<HttpResponse> httpCallback = new BatchPutHttpResponseCallback (
    address,
    hitsdbHttpclient,
    batchPutCallback,
    pointList,
    config,
    config.getBatchPutRetryCount()
            );
    return httpCallback;
}
项目:HiTSDB-Client    文件:HttpResponseCallbackFactory.java   
public FutureCallback<HttpResponse> createNoLogicBatchPutHttpFutureCallback(
            final String address,
        final List<Point> pointList,
        final HiTSDBConfig config,
        final int batchPutRetryTimes
) {
    FutureCallback<HttpResponse> httpCallback = 
            new BatchPutHttpResponseCallback (
    address,
    hitsdbHttpclient,
    null,
    pointList,
    config,
    batchPutRetryTimes
            );
    return httpCallback;
}
项目:HiTSDB-Client    文件:BatchPutHttpResponseCallback.java   
private void errorRetry() {
    String newAddress;
    boolean acquire;
    int retryTimes = this.batchPutRetryTimes;
    while(true) {
        newAddress = getNextAddress();
        acquire = this.hitsdbHttpClient.getSemaphoreManager().acquire(newAddress);
        retryTimes--;
        if(acquire || retryTimes <= 0) {
            break;
        }
    }

    if(retryTimes == 0) {
        this.hitsdbHttpClient.getSemaphoreManager().release(address);
        return ;
    }

    // retry!
    LOGGER.warn("retry put data!");
    HttpResponseCallbackFactory httpResponseCallbackFactory = this.hitsdbHttpClient.getHttpResponseCallbackFactory();

    FutureCallback<HttpResponse> retryCallback;
    if (batchPutCallback != null) {
        retryCallback = httpResponseCallbackFactory.createBatchPutDataCallback(newAddress,this.batchPutCallback,this.pointList, this.config, retryTimes);
    } else {
        retryCallback = httpResponseCallbackFactory.createNoLogicBatchPutHttpFutureCallback(newAddress,this.pointList,this.config, retryTimes);
    }

    String jsonString = JSON.toJSONString(pointList);
    this.hitsdbHttpClient.post(HttpAPI.PUT, jsonString, retryCallback);
}
项目:JavaNRPC    文件:EtcdClient.java   
private ListenableFuture<HttpResponse> asyncExecuteHttp(final HttpUriRequest request) {
    final SettableFuture<HttpResponse> future = SettableFuture.create();

    httpClient.execute(request, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse httpResponse) {
            future.set(httpResponse);
        }

        @Override
        public void failed(Exception e) {
            future.setException(e);
        }

        @Override
        public void cancelled() {
            future.setException(new InterruptedException());
        }
    });

    return future;
}
项目:remote-files-sync    文件:AbstractConnPool.java   
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    Args.notNull(route, "Route");
    Asserts.check(!this.isShutDown, "Connection pool shut down");
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                final long timeout,
                final TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);
            onLease(entry);
            return entry;
        }

    };
}
项目:remote-files-sync    文件:FutureRequestExecutionService.java   
/**
 * Schedule a request for execution.
 *
 * @param <T>
 *
 * @param request
 *            request to execute
 * @param context
 *            optional context; use null if not needed.
 * @param responseHandler
 *            handler that will process the response.
 * @param callback
 *            callback handler that will be called when the request is scheduled,
 *            started, completed, failed, or cancelled.
 * @return HttpAsyncClientFutureTask for the scheduled request.
 * @throws InterruptedException
 */
public <T> HttpRequestFutureTask<T> execute(
        final HttpUriRequest request,
        final HttpContext context,
        final ResponseHandler<T> responseHandler,
        final FutureCallback<T> callback) {
    if(closed.get()) {
        throw new IllegalStateException("Close has been called on this httpclient instance.");
    }
    metrics.getScheduledConnections().incrementAndGet();
    final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
        httpclient, request, context, responseHandler, callback, metrics);
    final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
        request, callable);
    executorService.execute(httpRequestFutureTask);

    return httpRequestFutureTask;
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Before
public void setUp() {
    config = Configuration.buildFromConfig("config-mock.properties");
    when(connectionStrategy.getHttpClient()).thenReturn(asyncHttpClient);
    HttpResponse response = mock(HttpResponse.class);
    Future<HttpResponse> future = ConcurrentUtils.constantFuture(response);
    when(asyncHttpClient.execute(any(HttpUriRequest.class),any(FutureCallback.class))).thenReturn(future, null);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);
    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(200);
    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_RESPONSE_EXPECTED, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        client = new LogInsightClient(config, connectionStrategy);
        // client.connect(user, password);
        assertEquals("Invalid session id!!",
                "qyOLWEe7f/GjdM1WnczrCeQure97B/NpTbWTeqqYPBd1AYMf9cMNfQYqltITI4ffPMx822Sz9i/X47t8VwsDb0oGckclJUdn83cyIPk6WlsOpI4Yjw6WpurAnv9RhDsYSzKhAMzskzhTOJKfDHZjWR5v576WwtJA71wqI7igFrG91LG5c/3GfzMb68sUHF6hV+meYtGS4A1y/lUItvfkqTTAxBtTCZNoKrvCJZ4R+b6vuAAYoBNSWL7ycIy2LsALrVFxftAkA8n9DBAZYA9T5A==",
                client.getSessionId());
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
    }
}
项目:currencybg.server    文件:AbstractSource.java   
protected void doGet(URI uri, final HTTPCallback httpCallback) {
    HttpGet httpGet = new HttpGet(uri);
    getClient(uri.getScheme().startsWith("https")).execute(httpGet, new FutureCallback<HttpResponse>() {

        @Override
        public void failed(Exception e) {
            httpCallback.onRequestFailed(e);
        }

        @Override
        public void completed(HttpResponse response) {
            httpCallback.onRequestCompleted(response, false);
        }

        @Override
        public void cancelled() {
            httpCallback.onRequestCompleted(null, false);
        }
    });
}
项目:purecloud-iot    文件:FutureRequestExecutionService.java   
/**
 * Schedule a request for execution.
 *
 * @param <T>
 *
 * @param request
 *            request to execute
 * @param context
 *            optional context; use null if not needed.
 * @param responseHandler
 *            handler that will process the response.
 * @param callback
 *            callback handler that will be called when the request is scheduled,
 *            started, completed, failed, or cancelled.
 * @return HttpAsyncClientFutureTask for the scheduled request.
 */
public <T> HttpRequestFutureTask<T> execute(
        final HttpUriRequest request,
        final HttpContext context,
        final ResponseHandler<T> responseHandler,
        final FutureCallback<T> callback) {
    if(closed.get()) {
        throw new IllegalStateException("Close has been called on this httpclient instance.");
    }
    metrics.getScheduledConnections().incrementAndGet();
    final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
        httpclient, request, context, responseHandler, callback, metrics);
    final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
        request, callable);
    executorService.execute(httpRequestFutureTask);

    return httpRequestFutureTask;
}
项目:purecloud-iot    文件:Async.java   
public <T> Future<T> execute(
        final Request request, final ResponseHandler<T> handler, final FutureCallback<T> callback) {
    final BasicFuture<T> future = new BasicFuture<T>(callback);
    final ExecRunnable<T> runnable = new ExecRunnable<T>(
            future,
            request,
            this.executor != null ? this.executor : Executor.newInstance(),
            handler);
    if (this.concurrentExec != null) {
        this.concurrentExec.execute(runnable);
    } else {
        final Thread t = new Thread(runnable);
        t.setDaemon(true);
        t.start();
    }
    return future;
}
项目:Visit    文件:AbstractConnPool.java   
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    Args.notNull(route, "Route");
    Asserts.check(!this.isShutDown, "Connection pool shut down");
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                final long timeout,
                final TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);
            onLease(entry);
            return entry;
        }

    };
}
项目:Visit    文件:FutureRequestExecutionService.java   
/**
 * Schedule a request for execution.
 *
 * @param <T>
 *
 * @param request
 *            request to execute
 * @param context
 *            optional context; use null if not needed.
 * @param responseHandler
 *            handler that will process the response.
 * @param callback
 *            callback handler that will be called when the request is scheduled,
 *            started, completed, failed, or cancelled.
 * @return HttpAsyncClientFutureTask for the scheduled request.
 * @throws InterruptedException
 */
public <T> HttpRequestFutureTask<T> execute(
        final HttpUriRequest request,
        final HttpContext context,
        final ResponseHandler<T> responseHandler,
        final FutureCallback<T> callback) {
    if(closed.get()) {
        throw new IllegalStateException("Close has been called on this httpclient instance.");
    }
    metrics.getScheduledConnections().incrementAndGet();
    final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
        httpclient, request, context, responseHandler, callback, metrics);
    final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
        request, callable);
    executorService.execute(httpRequestFutureTask);

    return httpRequestFutureTask;
}
项目:zeppelin    文件:HttpProxyClient.java   
private FutureCallback<HttpResponse> getCallback(final HttpRequestBase request) {
  return new FutureCallback<HttpResponse>() {

    public void completed(final HttpResponse response) {
      request.releaseConnection();
      LOG.info("Note {} completed with {} status", request.getMethod(),
          response.getStatusLine());
    }

    public void failed(final Exception ex) {
      request.releaseConnection();
      LOG.error("Note {} failed with {} message", request.getMethod(),
          ex.getMessage());
    }

    public void cancelled() {
      request.releaseConnection();
      LOG.info("Note {} was canceled", request.getMethod());
    }
  };
}
项目:astrix    文件:HttpRemotingTransport.java   
private FutureCallback<HttpResponse> serviceResponseCallback(
        final Subscriber<? super AstrixServiceInvocationResponse> t1) {
    return new FutureCallback<HttpResponse>() {
        public void completed(final HttpResponse response) {
            try {
                t1.onNext(getResponse(response));
                t1.onCompleted();
            } catch (Exception e) {
                t1.onError(e);
            }
        }
        public void failed(final Exception ex) {
            t1.onError(ex);
        }
        public void cancelled() {
            t1.onError(new RuntimeException("Request cancelled"));
        }
    };
}
项目:jenkins-spark-plugin    文件:SparkApi.java   
public void notify(String function) {
    HttpPost request = new HttpPost(sparkCloudUrl + String.format("/devices/%s/%s", deviceId, function));
    request.addHeader("Authorization", "Bearer " + accessToken);
    httpclient.execute(request, new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse httpResponse) {
            try {
                LOGGER.info("Request completed: " + IOUtils.toString(httpResponse.getEntity().getContent()));
            } catch (IOException ignored) { }
        }

        @Override
        public void failed(Exception e) {
            LOGGER.info("Request failed: " + e);
        }

        @Override
        public void cancelled() {
        }
    });
}
项目:incubator-gobblin    文件:ApacheHttpAsyncClient.java   
@Override
public void sendAsyncRequestImpl(HttpUriRequest request, Callback<HttpResponse> callback) throws IOException {
  this.client.execute(request, new FutureCallback<HttpResponse>() {
    @Override
    public void completed(HttpResponse result) {
      callback.onSuccess(result);
    }

    @Override
    public void failed(Exception ex) {
      callback.onFailure(ex);
    }

    @Override
    public void cancelled() {
      throw new UnsupportedOperationException();
    }
  });
}
项目:helios-skydns    文件:MiniEtcdClient.java   
Future<HttpResponse> get(final String key) {
  final URI uri = URI.create(baseUri + key);
  return httpClient.execute(new HttpGet(uri), new FutureCallback<HttpResponse>() {
    @Override
    public void cancelled() {
      log.warn("Attempt to get {} to was cancelled", key);
    }

    @Override
    public void completed(HttpResponse arg0) {
      log.info("Succeeded getting {}", key);
    }

    @Override
    public void failed(Exception e) {
      log.warn("Failed getting {}", key, e);
    }
  });
}
项目:HiTSDB-Client    文件:TestHttpAsyncClient.java   
@Test
public void testHttpAsyncClient() throws InterruptedException, IOException {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

    final CountDownLatch latch1 = new CountDownLatch(1);
    final HttpGet request2 = new HttpGet("http://www.apache.org/");
    httpclient.execute(request2, new FutureCallback<HttpResponse>() {

        public void completed(final HttpResponse response2) {
            latch1.countDown();
            System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine());
        }

        public void failed(final Exception ex) {
            latch1.countDown();
            System.out.println(request2.getRequestLine() + "->" + ex);
        }

        public void cancelled() {
            latch1.countDown();
            System.out.println(request2.getRequestLine() + " cancelled");
        }

    });

    latch1.await();
}
项目:yunpian-java-sdk    文件:AsyncClientHttpExchangeFutureCallback.java   
public static void main(final String[] args) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
    try {
        httpclient.start();
        final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"),
                new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
项目:remote-files-sync    文件:HttpRequestTaskCallable.java   
HttpRequestTaskCallable(
        final HttpClient httpClient,
        final HttpUriRequest request,
        final HttpContext context,
        final ResponseHandler<V> responseHandler,
        final FutureCallback<V> callback,
        final FutureRequestExecutionMetrics metrics) {
    this.httpclient = httpClient;
    this.responseHandler = responseHandler;
    this.request = request;
    this.context = context;
    this.callback = callback;
    this.metrics = metrics;
}
项目:loginsight-java-api    文件:LogInsightClient.java   
/**
 * Performs message query. Returns a CompletableFuture for
 * MessageQueryResponse
 * 
 * @param apiUrl
 *            relative url of the API
 * @return MessageQueryResponse CompletableFuture object
 * @throws LogInsightApiException
 *             Exception
 */
public CompletableFuture<MessageQueryResponse> messageQuery(String apiUrl) {
    HttpGet request = null;
    CompletableFuture<MessageQueryResponse> completableFuture = new CompletableFuture<MessageQueryResponse>();
    try {
        request = getHttpRequest(apiUrl, false);
        asyncHttpClient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse httpResponse) {

                try {
                    InputStream responseBody = httpResponse.getEntity().getContent();
                    String responseString = IOUtils.toString(responseBody, "UTF-8");
                    logger.warn("Response: " + responseString);
                    completableFuture.complete(MessageQueryResponse.fromJsonString(responseString));
                } catch (IOException e) {
                    e.printStackTrace();
                    completableFuture.completeExceptionally(e);
                }
            }

            @Override
            public void failed(Exception ex) {
                completableFuture.completeExceptionally(new LogInsightApiException("Failed message Query", ex));
            }

            @Override
            public void cancelled() {
                completableFuture.completeExceptionally(new LogInsightApiException("Cancelled message Query"));
            }

        });
    } catch (Exception ie) {
        completableFuture.completeExceptionally(new LogInsightApiException("Message query failed", ie));
    }
    return completableFuture;
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testMessageQuery() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));


    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());

        MessageQueryResponse messages = responseFuture.get(0, TimeUnit.MILLISECONDS);
        Assert.assertTrue("Invalid number of messages", messages.getEvents().size() <= 100);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(false);
    }
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testMessageQueryFailure() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));


    try {
        when(httpEntity.getContent()).thenThrow(IOException.class);
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        MessageQueryResponse messages = responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof IOException);
    }
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testMessageQueryRuntimeFailure() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));


    try {
        when(httpEntity.getContent()).thenThrow(Exception.class);
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        MessageQueryResponse messages = responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Message query failed");
    } catch (Exception e1) {
        Assert.assertTrue(false);
    }
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testAggregateQuery() {
    List<FieldConstraint> constraints =  new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100)
            .setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_AGGREGATE_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());

        AggregateResponse message = responseFuture.get(0, TimeUnit.MILLISECONDS);

        Assert.assertTrue("Invalid number of bins", message.getBins().size() <= 100);
        Assert.assertTrue("Invalid duration in the response", message.getDuration() > 0);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(false);
    }
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testAggregateQueryFailure() {
    List<FieldConstraint> constraints =  new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100)
            .setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_AGGREGATE_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenThrow(IOException.class);
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Unable to process the query response");
    }
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testAggregateQueryRuntimeFailure() {
    List<FieldConstraint> constraints =  new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100)
            .setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_AGGREGATE_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenThrow(Exception.class);
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Message query failed");
    }
}
项目:loginsight-java-api    文件:LogInsightClientMockTest.java   
@Test
public void testIngestion() {
    Message msg1 = new Message("Testing the ingestion");
    msg1.addField("vclap_test_id", "11111");
    IngestionRequest request = new IngestionRequest();
    request.addMessage(msg1);
    testIngestionQueryUrlAndHeaders(request);

    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);
    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(200);

    doAnswer(new Answer<Future<HttpResponse>>() {
          @Override
          public Future<HttpResponse> answer(InvocationOnMock invocation) {
              FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
              responseCallback.completed(response);
              return null;
          }})
      .when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_RESPONSE_FOR_INGESTION, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        CompletableFuture<IngestionResponse> responseFuture = client.ingest(request);
        Assert.assertTrue("Invalid status in ingestion response", "ok".equals(responseFuture.get().getStatus()));
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(false);
    }
}