com.ning.http.client.AsyncCompletionHandler Java Examples

The following examples show how to use com.ning.http.client.AsyncCompletionHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsyncTrelloHttpClient.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T delete(String url, final Class<T> responseType, String... params) {
    try {
        Future<T> f = asyncHttpClient.prepareDelete(UrlExpander.expandUrl(url, params)).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return mapper.readValue(response.getResponseBody(), responseType);
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #2
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz) {
    return new AsyncCompletionHandler<T>() {
        @Override
        public T onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsStream());
            }
            if (response.getStatusCode() == 404) {
                return null;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #3
Source File: AsyncTrelloHttpClient.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T putForObject(String url, Object object, final Class<T> responseType, String... params) {
    try {
        byte[] body = this.mapper.writeValueAsBytes(object);
        Future<T> f = asyncHttpClient.preparePut(UrlExpander.expandUrl(url, params)).setBody(body).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return mapper.readValue(response.getResponseBody(), responseType);
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #4
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected <T> AsyncCompletionHandler<List<T>> handleList(final Class<T> clazz) {
    return new AsyncCompletionHandler<List<T>>() {
        @Override
        public List<T> onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                List<T> values = new ArrayList<T>();
                for (JsonNode node : mapper.readTree(response.getResponseBodyAsStream())) {
                    values.add(mapper.convertValue(node, clazz));
                }
                return values;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #5
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected <T> AsyncCompletionHandler<List<T>> handleList(final Class<T> clazz, final String name) {
    return new AsyncCompletionHandler<List<T>>() {
        @Override
        public List<T> onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                List<T> values = new ArrayList<T>();
                for (JsonNode node : mapper.readTree(response.getResponseBodyAsStream()).get(name)) {
                    values.add(mapper.convertValue(node, clazz));
                }
                return values;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #6
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected AsyncCompletionHandler<List<SearchResultEntity>> handleSearchList(final String name) {
    return new AsyncCompletionHandler<List<SearchResultEntity>>() {
        @Override
        public List<SearchResultEntity> onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                List<SearchResultEntity> values = new ArrayList<SearchResultEntity>();
                for (JsonNode node : mapper.readTree(response.getResponseBodyAsStream()).get(name)) {
                    Class<? extends SearchResultEntity> clazz = searchResultTypes.get(node.get("result_type"));
                    if (clazz != null) {
                        values.add(mapper.convertValue(node, clazz));
                    }
                }
                return values;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #7
Source File: AsyncTrelloHttpClient.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T postForObject(String url, Object object, final Class<T> responseType, String... params) {
    try {
        byte[] body = this.mapper.writeValueAsBytes(object);
        Future<T> f = asyncHttpClient.preparePost(UrlExpander.expandUrl(url, params))
                .setHeader("Content-Type", "application/json")
                .setBody(body).execute(new AsyncCompletionHandler<T>() {
                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return mapper.readValue(response.getResponseBody(), responseType);
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #8
Source File: AsyncTrelloHttpClient.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(String url, final Class<T> responseType, String... params) {
    try {
        Future<T> f = asyncHttpClient.prepareGet(UrlExpander.expandUrl(url, params)).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return mapper.readValue(response.getResponseBody(), responseType);
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #9
Source File: AsyncUtil.java    From httpsig-java with The Unlicense 6 votes vote down vote up
/**
 * Executes and replays a login request until one is found which satisfies the
 * {@link net.adamcin.httpsig.api.Challenge} being returned by the server, or until there are no more keys in the
 * keychain.
 *
 * @since 1.0.4
 *
 * @param client the {@link AsyncHttpClient} to which the {@link Signer} will be attached
 * @param signer the {@link Signer} used for login and subsequent signature authentication
 * @param loginRequest the login {@link Request} to be executed and replayed while rotating the keychain
 * @param responseHandler an {@link AsyncCompletionHandler} of type {@code T}
 * @param calcBefore provide another {@link SignatureCalculator} to call (such as a Content-MD5 generator) prior to
 *                   generating the signature for authentication.
 * @param <T> type parameter for completion handler
 * @return a {@link Future} of type {@code T}
 * @throws IOException if thrown by a login request
 */
public static <T> Future<T> login(final AsyncHttpClient client,
                         final Signer signer,
                         final Request loginRequest,
                         final AsyncCompletionHandler<T> responseHandler,
                         final SignatureCalculator calcBefore) throws IOException {

    final AsyncHttpClientConfig.Builder configBuilder = new AsyncHttpClientConfig.Builder(client.getConfig());
    configBuilder.addResponseFilter(new RotateAndReplayResponseFilter(signer));
    AsyncHttpClient loginClient = new AsyncHttpClient(configBuilder.build());

    enableAuth(loginClient, signer, calcBefore);
    Future<T> response = loginClient.executeRequest(loginClient
                                                            .prepareRequest(loginRequest)
                                                            .setUrl(loginRequest.getUrl()).build(),
                                                    responseHandler);
    enableAuth(client, signer, calcBefore);
    return response;
}
 
Example #10
Source File: PlexConnector.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private void internalSendCommand(String machineIdentifier, String url) throws IOException {
    logger.debug("Calling url {}", url);

    BoundRequestBuilder builder = client.prepareGet(url).setHeaders(getDefaultHeaders())
            .setHeader("X-Plex-Target-Client-Identifier", machineIdentifier);

    builder.execute(new AsyncCompletionHandler<Response>() {
        @Override
        public Response onCompleted(Response response) throws Exception {
            if (response.getStatusCode() != 200) {
                logger.error("Error while sending command to Plex: {}\r\n{}", response.getStatusText(),
                        response.getResponseBody());
            }
            return response;
        }

        @Override
        public void onThrowable(Throwable t) {
            logger.error("Error sending command to Plex", t);
        }
    });
}
 
Example #11
Source File: SingularityHealthchecker.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private AsyncCompletionHandler<com.ning.http.client.Response> wrappedHttp1Handler(
  final SingularityHealthcheckAsyncHandler handler
) {
  return new AsyncCompletionHandler<com.ning.http.client.Response>() {

    @Override
    public void onThrowable(Throwable t) {
      handler.onFailed(t);
    }

    @Override
    public com.ning.http.client.Response onCompleted(
      com.ning.http.client.Response response
    )
      throws Exception {
      Optional<String> maybeResponseExcerpt = Optional.empty();

      if (response.hasResponseBody()) {
        maybeResponseExcerpt =
          Optional.of(
            response.getResponseBodyExcerpt(
              configuration.getMaxHealthcheckResponseBodyBytes()
            )
          );
      }

      handler.onCompleted(Optional.of(response.getStatusCode()), maybeResponseExcerpt);

      return response;
    }
  };
}
 
Example #12
Source File: AsyncTrelloHttpClient.java    From trello-java-wrapper with Apache License 2.0 5 votes vote down vote up
@Override
public URI postForLocation(String url, Object object, String... params) {
    try {
        byte[] body = this.mapper.writeValueAsBytes(object);
        Future<URI> f = asyncHttpClient.preparePost(UrlExpander.expandUrl(url, params)).setBody(body).execute(
                new AsyncCompletionHandler<URI>() {

                    @Override
                    public URI onCompleted(Response response) throws Exception {
                        String location = response.getHeader("Location");
                        if (location != null) {
                            return URI.create(location);
                        } else {
                            throw new TrelloHttpException("Location header not set");
                        }
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #13
Source File: AsyncUtil.java    From httpsig-java with The Unlicense 5 votes vote down vote up
/**
 * Executes and replays a login request until one is found which satisfies the
 * {@link net.adamcin.httpsig.api.Challenge} being returned by the server, or until there are no more keys in the
 * keychain.
 * @param client the {@link AsyncHttpClient} to which the {@link Signer} will be attached
 * @param signer the {@link Signer} used for login and subsequent signature authentication
 * @param loginRequest the login {@link Request} to be executed and replayed while rotating the keychain
 * @return a {@link Future} expecting a {@link Response}
 * @throws IOException if a request throws an exception
 */
public static Future<Response> login(final AsyncHttpClient client,
                                     final Signer signer,
                                     final Request loginRequest)
        throws IOException {

    return login(client, signer, loginRequest, new AsyncCompletionHandler<Response>() {
        @Override
        public Response onCompleted(Response response) throws Exception {
            return response;
        }
    });
}
 
Example #14
Source File: AgentManager.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void sendIndividualRequest(final String baseUrl, final String requestId, final AgentRequestType requestType) {
  if (!shouldSendRequest(baseUrl, requestId, requestType)) {
    return;
  }

  agentResponseDatastore.setPendingRequestStatus(requestId, baseUrl, true);

  final String url = String.format(baragonAgentRequestUriFormat, baseUrl, requestId);

  try {
    buildAgentRequest(url, requestType).execute(new AsyncCompletionHandler<Void>() {
      @Override
      public Void onCompleted(Response response) throws Exception {
        LOG.info(String.format("Got HTTP %d from %s for %s", response.getStatusCode(), baseUrl, requestId));
        final Optional<String> content = Strings.isNullOrEmpty(response.getResponseBody()) ? Optional.<String>absent() : Optional.of(response.getResponseBody());
        agentResponseDatastore.addAgentResponse(requestId, requestType, baseUrl, url, Optional.of(response.getStatusCode()), content, Optional.<String>absent());
        agentResponseDatastore.setPendingRequestStatus(requestId, baseUrl, false);
        return null;
      }

      @Override
      public void onThrowable(Throwable t) {
        LOG.info(String.format("Got exception %s when hitting %s for %s", t, baseUrl, requestId));
        agentResponseDatastore.addAgentResponse(requestId, requestType, baseUrl, url, Optional.<Integer>absent(), Optional.<String>absent(), Optional.of(t.getMessage()));
        agentResponseDatastore.setPendingRequestStatus(requestId, baseUrl, false);
      }
    });
  } catch (Exception e) {
    LOG.info(String.format("Got exception %s when hitting %s for %s", e, baseUrl, requestId));
    agentResponseDatastore.addAgentResponse(requestId, requestType, baseUrl, url, Optional.<Integer>absent(), Optional.<String>absent(), Optional.of(e.getMessage()));
    agentResponseDatastore.setPendingRequestStatus(requestId, baseUrl, false);
  }
}
 
Example #15
Source File: RpcCall.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void postRequest(Map<String, Object> request, Runnable completeHandler) {
    try {
        // we fire this request off asynchronously and let the completeHandler
        // process any response as necessary (can be null)
        String resultWrite = writeJson(request);
        logger.debug("Write JSON: {}", resultWrite);
        ListenableFuture<Response> future = client.preparePost(uri).setBody(resultWrite)
                .setHeader("content-type", "application/json").setHeader("accept", "application/json")
                .execute(new AsyncCompletionHandler<Response>() {
                    @Override
                    public Response onCompleted(Response response) throws Exception {
                        logger.debug("Read JSON: {}", response.getResponseBody());
                        Map<String, Object> json = readJson(response.getResponseBody());

                        // if we get an error then throw an exception to stop the
                        // completion handler getting executed
                        if (json.containsKey("error")) {
                            throw new RpcException(json.get("error").toString());
                        }

                        processResponse(json);
                        return response;
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        logger.error("Error handling POST response from XBMC", t);
                    }
                });

        // add the future listener to handle the response once this request completes
        if (completeHandler != null) {
            future.addListener(completeHandler, client.getConfig().executorService());
        }
    } catch (Exception e) {
        logger.error("Failed sending POST request to XBMC", e);
    }
}
 
Example #16
Source File: MiosUnitConnector.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void callMios(String url) {
    logger.debug("callMios: Would like to fire off the URL '{}'", url);

    try {
        @SuppressWarnings("unused")
        Future<Integer> f = getAsyncHttpClient().prepareGet(url).execute(new AsyncCompletionHandler<Integer>() {
            @Override
            public Integer onCompleted(Response response) throws Exception {

                // Yes, their content-type really does come back with just "xml", but we'll add "text/xml" for
                // when/if they ever fix that bug...
                if (!(response.getStatusCode() == 200 && ("text/xml".equals(response.getContentType())
                        || "xml".equals(response.getContentType())))) {
                    logger.debug("callMios: Error in HTTP Response code {}, content-type {}:\n{}",
                            new Object[] { response.getStatusCode(), response.getContentType(),
                                    response.hasResponseBody() ? response.getResponseBody() : "No Body" });
                }
                return response.getStatusCode();
            }

            @Override
            public void onThrowable(Throwable t) {
                logger.warn("callMios: Exception Throwable occurred fetching content: {}", t.getMessage(), t);
            }
        }

        );

        // TODO: Run it and walk away?
        //
        // Work out a better model to gather information about the
        // success/fail of the call, log details (etc) so things can be
        // diagnosed.
    } catch (Exception e) {
        logger.warn("callMios: Exception Error occurred fetching content: {}", e.getMessage(), e);
    }
}
 
Example #17
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private <T> ListenableFuture<T> submit(Request request, AsyncCompletionHandler<T> handler) {
    try {
        if (request.getStringData() != null) {
            logger.debug("Request {} {}\n{}", request.getMethod(), request.getUrl(), request.getStringData());
        } else if (request.getByteData() != null) {
            logger.debug("Request {} {} {} {} bytes", request.getMethod(), request.getUrl(), //
                    request.getHeaders().getFirstValue("Content-type"), request.getByteData().length);
        } else {
            logger.debug("Request {} {}", request.getMethod(), request.getUrl());
        }
        return client.executeRequest(request, handler);
    } catch (IOException e) {
        throw new ZendeskException(e.getMessage(), e);
    }
}
 
Example #18
Source File: AsyncHttpClientLambdaAware.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Response> execute(String url, final Completed c) throws IOException {
    return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {

        @Override
        public Response onCompleted(Response response) throws Exception {
            return c.onCompleted(response);
        }
    });
}
 
Example #19
Source File: AsyncHttpClientLambdaAware.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public ListenableFuture<Response> execute(String url, final Completed c, final Error e) throws IOException {
    return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {

        @Override
        public Response onCompleted(Response response) throws Exception {
            return c.onCompleted(response);
        }

        @Override
        public void onThrowable(Throwable t) {
            e.onThrowable(t);
        }

    });
}
 
Example #20
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz, final String name) {
    return new AsyncCompletionHandler<T>() {
        @Override
        public T onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), clazz);
            }
            if (response.getStatusCode() == 404) {
                return null;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #21
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
protected AsyncCompletionHandler<Void> handleStatus() {
    return new AsyncCompletionHandler<Void>() {
        @Override
        public Void onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                return null;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example #22
Source File: NingRequestBuilder.java    From ob1k with Apache License 2.0 4 votes vote down vote up
private ComposableFuture<com.ning.http.client.Response> executeAndTransformRequest() {

    try {
      prepareRequestBody();
    } catch (final IOException e) {
      return fromError(e);
    }

    final Request ningRequest = ningRequestBuilder.build();

    if (log.isTraceEnabled()) {
      final String body = ningRequest.getByteData() == null
        ? ningRequest.getStringData() :
        new String(ningRequest.getByteData(), Charset.forName(charset));

      log.trace("Sending HTTP call to {}: headers=[{}], body=[{}]", ningRequest.getUrl(), ningRequest.getHeaders(), body);
    }

    final Provider<com.ning.http.client.Response> provider = new Provider<com.ning.http.client.Response>() {
      private boolean aborted = false;
      private long size;

      @Override
      public ListenableFuture<com.ning.http.client.Response> provide() {
        return asyncHttpClient.executeRequest(ningRequest, new AsyncCompletionHandler<com.ning.http.client.Response>() {
          @Override
          public com.ning.http.client.Response onCompleted(final com.ning.http.client.Response response) throws Exception {
            if (aborted) {
              throw new RuntimeException("Response size is bigger than the limit: " + responseMaxSize);
            }
            return response;
          }

          @Override
          public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
            if (responseMaxSize > 0) {
              size += content.length();
              if (size > responseMaxSize) {
                aborted = true;
                return STATE.ABORT;
              }
            }
            return super.onBodyPartReceived(content);
          }
        });
      }
    };

    return fromListenableFuture(provider);
  }
 
Example #23
Source File: RouterNonBlockingAnonymousController.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 4 votes vote down vote up
/**
 * Sample usage: curl "http://localhost:9080/router-non-blocking-anonymous?minMs=1000&maxMs=2000"
 *
 * @param minMs
 * @param maxMs
 * @return
 * @throws java.io.IOException
 */
@RequestMapping("/router-non-blocking-anonymous")
public DeferredResult<String> nonBlockingRouter(
    @RequestParam(value = "minMs", required = false, defaultValue = "0") int minMs,
    @RequestParam(value = "maxMs", required = false, defaultValue = "0") int maxMs) throws IOException {

    LOG.logStartNonBlocking();

    final DeferredResult<String> deferredResult = new DeferredResult<>();

    String url = SP_NON_BLOCKING_URL + "?minMs=" + minMs + "&maxMs=" + maxMs;

    asyncHttpClient.prepareGet(url).execute(
        new AsyncCompletionHandler<Response>() {
            @Override
            public Response onCompleted(Response response) throws Exception {
                // TODO: Handle status codes other than 200...
                int httpStatus = response.getStatusCode();

                if (deferredResult.isSetOrExpired()) {
                    LOG.logAlreadyExpiredNonBlocking();

                } else {
                    boolean deferredStatus = deferredResult.setResult(response.getResponseBody());
                    LOG.logEndNonBlocking(httpStatus, deferredStatus);
                }
                return response;
            }

            @Override
            public void onThrowable(Throwable t){

                // TODO: Handle asynchronous processing errors...

                if (deferredResult.isSetOrExpired()) {
                    LOG.logExceptionNonBlocking(t);
                }
            }
        });

    LOG.logLeaveThreadNonBlocking();

    // Return to let go of the precious thread we are holding on to...
    return deferredResult;
}
 
Example #24
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
private PagedIterable(Uri url, AsyncCompletionHandler<List<T>> handler, int initialPage) {
    this.handler = handler;
    this.url = url;
    this.initialPage = initialPage;
}
 
Example #25
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
private PagedIterable(Uri url, AsyncCompletionHandler<List<T>> handler) {
    this(url, handler, 1);
}
 
Example #26
Source File: AsyncUtil.java    From httpsig-java with The Unlicense 3 votes vote down vote up
/**
 * Executes and replays a login request until one is found which satisfies the
 * {@link net.adamcin.httpsig.api.Challenge} being returned by the server, or until there are no more keys in the
 * keychain.
 *
 * @since 1.0.0
 *
 * @param client the {@link AsyncHttpClient} to which the {@link Signer} will be attached
 * @param signer the {@link Signer} used for login and subsequent signature authentication
 * @param loginRequest the login {@link Request} to be executed and replayed while rotating the keychain
 * @param responseHandler an {@link AsyncCompletionHandler} of type {@code T}
 * @param <T> type parameter for completion handler
 * @return a {@link Future} of type {@code T}
 * @throws IOException if thrown by a login request
 */
public static <T> Future<T> login(final AsyncHttpClient client,
                                  final Signer signer,
                                  final Request loginRequest,
                                  AsyncCompletionHandler<T> responseHandler) throws IOException {
    return login(client, signer, loginRequest, responseHandler, null);
}