Search in sources :

Example 6 with FutureCallback

use of org.apache.http.concurrent.FutureCallback in project kontraktor by RuedigerMoeller.

the class RemoteActorConnection method startLongPoll.

protected void startLongPoll() {
    final AtomicReference<Runnable> lp = new AtomicReference<>();
    lp.set(new Runnable() {

        @Override
        public void run() {
            if (!isConnected)
                return;
            // 1 = reply, 2 = timeout
            final AtomicInteger timedout = new AtomicInteger(0);
            delayed(new Runnable() {

                @Override
                public void run() {
                    checkTimeout();
                    if (timedout.compareAndSet(0, 2)) {
                        // long poll timeout, retry
                        myExec.execute(lp.get());
                    }
                }
            }, // give 1 second trip latency
            LONG_POLL_MAX_TIME + 1000);
            HttpPost request = createRequest(sessionUrl, conf.asByteArray(new Object[] { lastSeenSeq }));
            getClient().execute(request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(HttpResponse result) {
                    if (!timedout.compareAndSet(0, 1)) {
                        return;
                    }
                    if (result.getStatusLine().getStatusCode() != 200) {
                        log("unexpected return status " + result.getStatusLine().getReasonPhrase());
                        delayed(lp.get(), 2000);
                        return;
                    }
                    lastPing = System.currentTimeMillis();
                    String cl = result.getFirstHeader("Content-Length").getValue();
                    int len = Integer.parseInt(cl);
                    if (len > 0) {
                        final byte[] b = new byte[len];
                        try {
                            result.getEntity().getContent().read(b);
                            myExec.execute(new Runnable() {

                                @Override
                                public void run() {
                                    processResponse(b);
                                }
                            });
                            myExec.execute(lp.get());
                        } catch (Throwable e) {
                            log(e);
                            // delay next longpoll to avoid exception spam
                            delayed(lp.get(), 2000);
                        }
                    } else {
                        myExec.execute(lp.get());
                    }
                }

                @Override
                public void failed(Exception ex) {
                    if (!timedout.compareAndSet(0, 1)) {
                        return;
                    }
                    log(ex);
                    // delay next longpoll to avoid exception spam
                    delayed(lp.get(), 2000);
                }

                @Override
                public void cancelled() {
                    if (!timedout.compareAndSet(0, 1)) {
                        return;
                    }
                    log("request canceled");
                    // delay next longpoll to avoid exception spam
                    delayed(lp.get(), 2000);
                }
            });
        }
    });
    delayed(lp.get(), 1000);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpResponse(org.apache.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ParseException(org.apache.http.ParseException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 7 with FutureCallback

use of org.apache.http.concurrent.FutureCallback in project jmeter by apache.

the class HttpMetricsSender method writeAndSendMetrics.

private void writeAndSendMetrics(List<MetricTuple> copyMetrics) {
    try {
        if (httpRequest == null) {
            httpRequest = createRequest(url, token);
        }
        StringBuilder sb = new StringBuilder(copyMetrics.size() * 35);
        for (MetricTuple metric : copyMetrics) {
            // Add TimeStamp in nanosecond from epoch ( default in InfluxDB )
            sb.append(metric.measurement).append(metric.tag).append(// $NON-NLS-1$
            " ").append(metric.field).append(" ").append(metric.timestamp).append("000000").append(// $NON-NLS-1$
            "\n");
        }
        String data = sb.toString();
        log.debug("Sending to influxdb:{}", data);
        httpRequest.setEntity(new StringEntity(data, StandardCharsets.UTF_8));
        lastRequest = httpClient.execute(httpRequest, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {
                int code = response.getStatusLine().getStatusCode();
                /*
                     * If your write request received HTTP
                     * 204 No Content: it was a success!
                     * 4xx: InfluxDB could not understand the request.
                     * 5xx: The system is overloaded or significantly impaired.
                     */
                if (MetricUtils.isSuccessCode(code)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Success, number of metrics written: {}", copyMetrics.size());
                    }
                } else {
                    log.error("Error writing metrics to influxDB Url: {}, responseCode: {}, responseBody: {}", url, code, getBody(response));
                }
            }

            @Override
            public void failed(final Exception ex) {
                log.error("failed to send data to influxDB server.", ex);
            }

            @Override
            public void cancelled() {
                log.warn("Request to influxDB server was cancelled");
            }
        });
    } catch (URISyntaxException ex) {
        log.error(ex.getMessage(), ex);
    }
}
Also used : StringEntity(org.apache.http.entity.StringEntity) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) FutureCallback(org.apache.http.concurrent.FutureCallback) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException)

Example 8 with FutureCallback

use of org.apache.http.concurrent.FutureCallback in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method sourceWithMockedRemoteCall.

/**
     * Creates a hit source that doesn't make the remote request and instead returns data from some files. Also requests are always returned
     * synchronously rather than asynchronously.
     */
@SuppressWarnings("unchecked")
private RemoteScrollableHitSource sourceWithMockedRemoteCall(boolean mockRemoteVersion, ContentType contentType, String... paths) throws Exception {
    URL[] resources = new URL[paths.length];
    for (int i = 0; i < paths.length; i++) {
        resources[i] = Thread.currentThread().getContextClassLoader().getResource("responses/" + paths[i].replace("fail:", ""));
        if (resources[i] == null) {
            throw new IllegalArgumentException("Couldn't find [" + paths[i] + "]");
        }
    }
    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>>() {

        int responseCount = 0;

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            // Throw away the current thread context to simulate running async httpclient's thread pool
            threadPool.getThreadContext().stashContext();
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) requestProducer.generateRequest();
            URL resource = resources[responseCount];
            String path = paths[responseCount++];
            ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
            if (path.startsWith("fail:")) {
                String body = Streams.copyToString(new InputStreamReader(request.getEntity().getContent(), StandardCharsets.UTF_8));
                if (path.equals("fail:rejection.json")) {
                    StatusLine statusLine = new BasicStatusLine(protocolVersion, RestStatus.TOO_MANY_REQUESTS.getStatus(), "");
                    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
                    futureCallback.completed(httpResponse);
                } else {
                    futureCallback.failed(new RuntimeException(body));
                }
            } else {
                StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "");
                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                httpResponse.setEntity(new InputStreamEntity(FileSystemUtils.openFileURLStream(resource), contentType));
                futureCallback.completed(httpResponse);
            }
            return null;
        }
    });
    return sourceWithMockedClient(mockRemoteVersion, httpClient);
}
Also used : InputStreamReader(java.io.InputStreamReader) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Matchers.containsString(org.hamcrest.Matchers.containsString) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StatusLine(org.apache.http.StatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 9 with FutureCallback

use of org.apache.http.concurrent.FutureCallback in project uavstack by uavorg.

the class ApacheAsyncHttpClientIT method doAsyncStart.

/**
 * for async http client
 *
 * @param args
 * @return
 */
@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
public FutureCallback doAsyncStart(Object[] args) {
    HttpAsyncRequestProducer requestProducer = null;
    HttpAsyncResponseConsumer responseConsumer = null;
    HttpContext context = null;
    FutureCallback callback = null;
    Map mObj = null;
    if (args.length == 4) {
        requestProducer = (HttpAsyncRequestProducer) args[0];
        responseConsumer = (HttpAsyncResponseConsumer) args[1];
        context = (HttpContext) args[2];
        callback = (FutureCallback) args[3];
    } else if (args.length == 5) {
        requestProducer = (HttpAsyncRequestProducer) args[1];
        responseConsumer = (HttpAsyncResponseConsumer) args[2];
        context = (HttpContext) args[3];
        callback = (FutureCallback) args[4];
    }
    String httpAction = null;
    try {
        HttpRequest hr = requestProducer.generateRequest();
        /**
         * 呵呵,就是把UAV的客户端标记加到http header里面,接收方就知道是哪个东东调用的了,便于实现来源快速匹配,这个模式只适合直连模式
         *
         * 对于代理模式,只匹配代理源即可
         */
        hr.addHeader("UAV-Client-Src", MonitorServerUtil.getUAVClientSrc(this.applicationId));
        RequestLine rl = hr.getRequestLine();
        httpAction = rl.getMethod();
        targetURL = rl.getUri();
        // 部分HttpRequest中没有ip:port,需要从httpHost中拿到再拼接
        if (!targetURL.startsWith("http")) {
            targetURL = requestProducer.getTarget().toURI() + targetURL;
        }
    } catch (IOException e) {
        // ignore thie exception
        return null;
    } catch (HttpException e) {
        // ignore thie exception
        return null;
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURL);
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_ACTION, httpAction);
    params.put(CaptureConstants.INFO_CLIENT_APPID, this.applicationId);
    params.put(CaptureConstants.INFO_CLIENT_TYPE, "apache.http.AsyncClient");
    if (logger.isDebugable()) {
        logger.debug("Invoke START:" + targetURL + "," + httpAction + "," + this.applicationId, null);
    }
    /**
     * for async, as not in the same thread
     */
    ccMap = UAVServer.instance().runMonitorAsyncCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT, Monitor.CapturePhase.PRECAP, params, null);
    // register invokechain adapter
    UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "registerAdapter", ApacheAsyncHttpClientAdapter.class);
    ccMap4Chain = (Map<String, Object>) UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap", InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.PRECAP, params, ApacheAsyncHttpClientAdapter.class, args);
    if (callback == null) {
        return null;
    }
    callback = JDKProxyInvokeUtil.newProxyInstance(HttpContext.class.getClassLoader(), new Class<?>[] { FutureCallback.class }, new JDKProxyInvokeHandler<FutureCallback>(callback, new FutureCallbackProxyInvokeProcessor(ccMap4Chain)));
    return callback;
}
Also used : HttpRequest(org.apache.http.HttpRequest) HashMap(java.util.HashMap) JDKProxyInvokeHandler(com.creditease.monitor.proxy.spi.JDKProxyInvokeHandler) HttpContext(org.apache.http.protocol.HttpContext) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) IOException(java.io.IOException) RequestLine(org.apache.http.RequestLine) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) HttpException(org.apache.http.HttpException) HashMap(java.util.HashMap) Map(java.util.Map) FutureCallback(org.apache.http.concurrent.FutureCallback)

Aggregations

FutureCallback (org.apache.http.concurrent.FutureCallback)9 HttpResponse (org.apache.http.HttpResponse)7 CloseableHttpAsyncClient (org.apache.http.impl.nio.client.CloseableHttpAsyncClient)5 HttpAsyncRequestProducer (org.apache.http.nio.protocol.HttpAsyncRequestProducer)5 HttpAsyncResponseConsumer (org.apache.http.nio.protocol.HttpAsyncResponseConsumer)5 Future (java.util.concurrent.Future)4 HttpHost (org.apache.http.HttpHost)4 ProtocolVersion (org.apache.http.ProtocolVersion)4 StatusLine (org.apache.http.StatusLine)4 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)4 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)4 BasicStatusLine (org.apache.http.message.BasicStatusLine)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 IOException (java.io.IOException)3 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)3 StringEntity (org.apache.http.entity.StringEntity)3 Before (org.junit.Before)3 InputStreamReader (java.io.InputStreamReader)2 SocketTimeoutException (java.net.SocketTimeoutException)2 URISyntaxException (java.net.URISyntaxException)2