List of usage examples for org.apache.http.concurrent FutureCallback FutureCallback
FutureCallback
From source file:com.spotify.helios.serviceregistration.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/*from www . j a v a 2 s . c om*/ 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); } }); }
From source file:com.imagesleuth.imagesleuthclient2.Poster.java
public String Post(final File imgFile) throws IOException, ImageReadException, InterruptedException { final ArrayList<String> idArray = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(1); try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray) .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) { httpclient.start();/*from w w w .j a v a 2 s. c om*/ final byte[] imageAsBytes = IOUtils.toByteArray(new FileInputStream(imgFile)); final ImageInfo info = Imaging.getImageInfo(imageAsBytes); final HttpPost request = new HttpPost(urlval); String boundary = UUID.randomUUID().toString(); HttpEntity mpEntity = MultipartEntityBuilder.create().setBoundary("-------------" + boundary) .addBinaryBody("file", imageAsBytes, ContentType.create(info.getMimeType()), imgFile.getName()) .build(); ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); mpEntity.writeTo(baoStream); request.setHeader("Content-Type", "multipart/form-data;boundary=-------------" + boundary); //equest.setHeader("Content-Type", "multipart/form-data"); NByteArrayEntity entity = new NByteArrayEntity(baoStream.toByteArray(), ContentType.MULTIPART_FORM_DATA); request.setEntity(entity); httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { int code = response.getStatusLine().getStatusCode(); //System.out.println(" response code: " + code + " for image: " + imgFile.getName()); if (response.getEntity() != null && code == 202) { StringWriter writer = new StringWriter(); try { IOUtils.copy(response.getEntity().getContent(), writer); idArray.add(writer.toString()); writer.close(); //System.out.println(" response id: " + id + " for image "+ img.getName()); latch.countDown(); } catch (Exception ex) { ex.printStackTrace(); } } else { System.out.println(" response code: " + code + " for image: " + imgFile.getName() + " reason " + response.getStatusLine().getReasonPhrase()); } } @Override public void failed(final Exception ex) { System.out.println(request.getRequestLine() + imgFile.getName() + "->" + ex); latch.countDown(); } @Override public void cancelled() { System.out.println(request.getRequestLine() + " cancelled"); latch.countDown(); } }); latch.await(); } if (idArray.isEmpty()) { return null; } else { return idArray.get(0); } }
From source file:io.galeb.services.healthchecker.testers.ApacheHttpClientTester.java
public boolean connect() throws RuntimeException, InterruptedException, ExecutionException { if (url == null || returnType == null || expectedReturn == null) { return false; }/* w w w . j a va 2s . com*/ final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try { httpclient.start(); final CountDownLatch latch = new CountDownLatch(1); final HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.HOST, host); final HttpAsyncRequestProducer producer = HttpAsyncMethods.create(request); final RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT) .setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout) .setConnectionRequestTimeout(defaultTimeout).build(); request.setConfig(requestConfig); final AsyncCharConsumer<HttpResponse> consumer = new AsyncCharConsumer<HttpResponse>() { HttpResponse response; @Override protected void onCharReceived(CharBuffer buf, IOControl iocontrol) throws IOException { return; } @Override protected HttpResponse buildResult(HttpContext context) throws Exception { return response; } @Override protected void onResponseReceived(HttpResponse response) throws HttpException, IOException { this.response = response; } }; httpclient.execute(producer, consumer, new FutureCallback<HttpResponse>() { @Override public void cancelled() { latch.countDown(); isOk = false; } @Override public void completed(HttpResponse response) { latch.countDown(); final int statusCode = response.getStatusLine().getStatusCode(); InputStream contentIS = null; String content = ""; try { contentIS = response.getEntity().getContent(); content = IOUtils.toString(contentIS); } catch (IllegalStateException | IOException e) { logger.ifPresent(log -> log.debug(e)); } if (returnType.startsWith("httpCode")) { returnType = returnType.replaceFirst("httpCode", ""); } // isOk = statusCode == Integer.parseInt(returnType); // Disable temporarily statusCode check isOk = true; } @Override public void failed(Exception e) { latch.countDown(); isOk = false; logger.ifPresent(log -> log.debug(e)); } }); latch.await(); } catch (final RuntimeException e) { isOk = false; logger.ifPresent(log -> log.error(e)); } finally { try { httpclient.close(); } catch (final IOException e) { logger.ifPresent(log -> log.debug(e)); } } return isOk; }
From source file:com.micro.rent.common.comm.aio.AsyncClientHttpExchangeFutureCallback.java
public void httpAsync() throws Exception { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) .build();/*from w ww . j ava2s. com*/ try { httpclient.start(); final HttpGet[] requests = new HttpGet[list.size()]; for (int i = 0; i < list.size(); i++) { BigDecimal lat = list.get(i).getLatitude(); BigDecimal lon = list.get(i).getLongitude(); RequestParam reqParam = new RequestParam(); reqParam.setDestination(lat.toString().concat(",").concat(lon.toString())); reqParam.setOrigin(String.valueOf(wpLat).concat(",").concat(String.valueOf(wpLon))); reqParam.setMode(queryVo.getTrafficType()); switch (ETranfficType.getSelfByCode(queryVo.getTrafficType())) { case DRIVING: reqParam.setOrigin_region(queryVo.getCityName()); reqParam.setDestination_region(queryVo.getCityName()); break; case TRANSIT: case WALKING: reqParam.setRegion(queryVo.getCityName()); break; default: break; } requests[i] = new HttpGet(timeUrl(reqParam)); } long start = System.currentTimeMillis(); final CountDownLatch latch = new CountDownLatch(requests.length); for (int j = 0; j < requests.length; j++) { final HttpGet request = requests[j]; final int k = j; httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); try { InputStream a = response.getEntity().getContent(); String responseString = readInputStream(a); String duration = duration(responseString); list.get(k).setDuration(duration); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void failed(final Exception ex) { latch.countDown(); } public void cancelled() { latch.countDown(); } }); } latch.await(); log.info(System.currentTimeMillis() - start + "-----------------ms----"); } finally { httpclient.close(); } }
From source file:com.ysheng.auth.common.restful.BaseClient.java
/** * Performs an asynchronous DELETE operation. * * @param path The path of the RESTful operation. * @param expectedHttpStatus The expected HTTP status of the operation. * @param responseHandler The asynchronous response handler. * @throws IOException The error that contains detail information. *//*from w w w . ja v a 2s.c om*/ public final void deleteAsync(final String path, final int expectedHttpStatus, final FutureCallback<Void> responseHandler) throws IOException { restClient.performAsync(RestClient.Method.DELETE, path, null, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { try { restClient.checkResponse(httpResponse, expectedHttpStatus); } catch (Exception e) { responseHandler.failed(e); } responseHandler.completed(null); } @Override public void failed(Exception e) { responseHandler.failed(e); } @Override public void cancelled() { responseHandler.cancelled(); } }); }
From source file:com.spotify.helios.serviceregistration.skydns.MiniEtcdClient.java
Future<HttpResponse> set(final String key, final String value, final Integer ttl) { final List<BasicNameValuePair> data = Lists.newArrayList(); data.add(new BasicNameValuePair("value", value)); if (ttl != null) { data.add(new BasicNameValuePair("ttl", Integer.toString(ttl))); }/*from w ww .j ava 2 s . co m*/ final URI uri = URI.create(baseUri + key); final HttpPut request = new HttpPut(uri); request.setEntity(new UrlEncodedFormEntity(data, Charsets.UTF_8)); return httpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void cancelled() { log.warn("Attempt to set {} to {} was cancelled", key, value); } @Override public void completed(HttpResponse arg0) { log.info("Succeeded setting {} to {}", key, value); } @Override public void failed(Exception e) { log.warn("Failed setting {} to {}", key, value, e); } }); }
From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java
@Override public CompletableFuture<RRHttpResponse> send(RRHttpRequest request) { CompletableFuture<HttpResponse> promise = new CompletableFuture<>(); URI uri;//from w w w . j av a 2s.co m HttpRequestBase hcRequest; try { if (request.getMethod() == HttpMethod.POST) { uri = new URIBuilder(request.getUrl().toASCIIString()).build(); hcRequest = new HttpPost(uri); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); request.getQueryParams().entrySet() .forEach(x -> urlParameters.add(new BasicNameValuePair(x.getKey(), x.getValue()))); ((HttpPost) hcRequest).setEntity(new UrlEncodedFormEntity(urlParameters)); } else { uri = new URIBuilder(request.getUrl().toASCIIString()).addParameters(request.getQueryParams() .entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue())) .collect(Collectors.toList())).build(); hcRequest = new HttpGet(uri); } } catch (URISyntaxException e) { throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage()); } request.getHeaders().entrySet().forEach(e -> hcRequest.addHeader(e.getKey(), e.getValue())); AccessController.doPrivileged((PrivilegedAction<Void>) () -> { hcHttpClient.execute(hcRequest, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse hcResponse) { int statusCode = hcResponse.getStatusLine().getStatusCode(); logger.debug("HTTP REQ SUCCESS with status: " + statusCode + " " + request); promise.complete(hcResponse); } public void failed(final Exception ex) { logger.debug("HTTP REQ FAILED " + request); logger.info("HTTP client failed to connect: " + request + " reason: " + ex.getMessage()); promise.completeExceptionally(ex); } public void cancelled() { promise.completeExceptionally(new RuntimeException("HTTP REQ CANCELLED: " + request)); } }); return null; }); return promise.thenApply(hcResp -> new RRHttpResponse(hcResp.getStatusLine().getStatusCode(), () -> { try { return hcResp.getEntity().getContent(); } catch (IOException e) { throw new RuntimeException("Cannot read content", e); } })); }
From source file:com.mycompany.wolf.Room.java
public void removePlayer(String playerId) throws IOException { synchronized (mutex) { sessions.removeIf(equalityPredicate(playerId)); List<Map<String, String>> roomInfo = sessions.stream() .map(s -> ImmutableMap.of("playerId", getPlayerId(s))) .collect(Collectors.toCollection(LinkedList::new)); Map<String, Object> m = ImmutableMap.of("code", "exitResp", "properties", roomInfo); String json = new Gson().toJson(m); sessions.stream().forEach(s -> { s.getAsyncRemote().sendText(json); });/* w w w . j a va2 s. c o m*/ } RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) .build(); httpclient.start(); try { String routerAddress = SpringContext.getBean("routerAddress"); httpclient.execute(new HttpGet(routerAddress), new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse t) { } @Override public void failed(Exception excptn) { } @Override public void cancelled() { } }); } finally { httpclient.close(); } }
From source file:net.tirasa.wink.client.asynchttpclient.ApacheHttpAsyncClientConnectionHandler.java
private Future<HttpResponse> processRequest(ClientRequest request, HandlerContext context) throws IOException, KeyManagementException, NoSuchAlgorithmException { final CloseableHttpAsyncClient client = openConnection(request); // TODO: move this functionality to the base class NonCloseableOutputStream ncos = new NonCloseableOutputStream(); EntityWriter entityWriter = null;// w w w . ja v a 2 s . co m if (request.getEntity() != null) { OutputStream os = adaptOutputStream(ncos, request, context.getOutputStreamAdapters()); // cast is safe because we're on the client ApacheHttpClientConfig config = (ApacheHttpClientConfig) request.getAttribute(WinkConfiguration.class); // prepare the entity that will write our entity entityWriter = new EntityWriter(this, request, os, ncos, config.isChunked()); } HttpRequestBase entityRequest = setupHttpRequest(request, entityWriter); try { return client.execute(entityRequest, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse t) { LOG.debug("Client completed with response {}", t); try { client.close(); } catch (IOException e) { LOG.error("While closing", e); } } @Override public void failed(Exception excptn) { LOG.error("Client failed with exception", excptn); try { client.close(); } catch (IOException e) { LOG.error("While closing", e); } } @Override public void cancelled() { LOG.debug("Client execution cancelled"); try { client.close(); } catch (IOException e) { LOG.error("While closing", e); } } }); } catch (Exception ex) { entityRequest.abort(); throw new RuntimeException(ex); } }