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);
}
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);
}
}
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);
}
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;
}
Aggregations