Java Code Examples for com.ning.http.client.AsyncHttpClient.BoundRequestBuilder#execute()

The following examples show how to use com.ning.http.client.AsyncHttpClient.BoundRequestBuilder#execute() . 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: 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 2
Source File: SingularityWebhookSender.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private <T> CompletableFuture<Response> executeWebhookAsync(
  String uri,
  Object payload,
  AbstractSingularityWebhookAsyncHandler<T> handler
) {
  LOG.trace("Sending {} to {}", payload, uri);
  BoundRequestBuilder postRequest = http.preparePost(uri);
  postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

  try {
    postRequest.setBody(objectMapper.writeValueAsBytes(payload));
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }

  CompletableFuture<Response> webhookFuture = new CompletableFuture<>();
  try {
    handler.setCompletableFuture(webhookFuture);
    postRequest.execute(handler);
  } catch (Throwable t) {
    LOG.warn("Couldn't execute webhook to {}", uri, t);

    if (handler.shouldDeleteUpdateDueToQueueAboveCapacity()) {
      handler.deleteWebhookUpdate();
    }
    webhookFuture.completeExceptionally(t);
  }
  return webhookFuture;
}
 
Example 3
Source File: HttpWorker.java    From parallec with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Object message) throws Exception {
    try {
        if (message instanceof RequestWorkerMsgType) {
            switch ((RequestWorkerMsgType) message) {
            case PROCESS_REQUEST:
                tryCount++;

                if (tryCount == 1) {
                    sender = getSender();

                    BoundRequestBuilder request = createRequest();

                    // 20150229: create the future and make sure future is
                    // killed when timeout.
                    responseFuture = request.execute(new HttpAsyncHandler(
                            this));
                    timeoutDuration = Duration.create(
                            actorMaxOperationTimeoutSec, TimeUnit.SECONDS);

                    // To handle cases where nio response never comes back,
                    // we
                    // schedule a 'timeout' message to be sent to us 2
                    // seconds
                    // after NIO's SO_TIMEOUT
                    timeoutMessageCancellable = getContext()
                            .system()
                            .scheduler()
                            .scheduleOnce(
                                    timeoutDuration,
                                    getSelf(),
                                    RequestWorkerMsgType.PROCESS_ON_TIMEOUT,
                                    getContext().system().dispatcher(),
                                    getSelf());
                } else {
                    getLogger().error(
                            "duplicated PROCESS_REQUEST msg. ignore...");
                }
                break;

            case CANCEL:
                getLogger().info(
                        "Request was CANCELLED.................{}",
                        requestUrl);
                cancelCancellable();
                if (sender == null)
                    sender = getSender();
                reply(null, true, PcConstants.REQUEST_CANCELED,
                        PcConstants.REQUEST_CANCELED, PcConstants.NA,
                        PcConstants.NA_INT, null);
                break;

            case PROCESS_ON_EXCEPTION:

                String errorSummary = PcErrorMsgUtils.replaceErrorMsg(cause
                        .toString());
                String stackTrace = PcStringUtils.printStackTrace(cause);
                cancelCancellable();
                reply(null, true, errorSummary, stackTrace, PcConstants.NA,
                        PcConstants.NA_INT, null);

                break;

            case PROCESS_ON_TIMEOUT:

                getLogger().error("PROCESS_ON_TIMEOUT.................{}",
                        requestUrl);
                cancelCancellable();

                String errorMsg = String
                        .format("HttpWorker Timedout after %d SEC (no response but no exception catched). Check URL: may be very slow or stuck.",
                                actorMaxOperationTimeoutSec);

                reply(null, true, errorMsg, errorMsg, PcConstants.NA,
                        PcConstants.NA_INT, null);
                break;

            case CHECK_FUTURE_STATE:
            default:
                this.cause = new ActorMessageTypeInvalidException(
                        "ActorMessageTypeInvalidException error for url "
                                + this.requestUrl);
                getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION,
                        getSelf());
                break;
            }
        } else {
            unhandled(message);
            this.cause = new ActorMessageTypeInvalidException(
                    "ActorMessageTypeInvalidException error for url "
                            + this.requestUrl);
            getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION,
                    getSelf());
        }
    } catch (Exception e) {
        this.cause = e;
        getSelf()
                .tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf());
    }
}
 
Example 4
Source File: HttpWorker.java    From restcommander with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Object message) throws Exception {
	try {
		if (message instanceof MessageType) {
			switch ((MessageType) message) {
			case PROCESS_REQUEST:
				tryCount++;

				if (tryCount == 1) {
					sender = getSender();

					// Construct and submit NING Request
					BoundRequestBuilder request = createRequest();
					// String targetUrl = request.build().getUrl();
					request.execute(new HttpAsyncHandler(this));

					timeoutDuration = Duration
							.create(VarUtils.ACTOR_MAX_OPERATION_TIME_SECONDS_DEFAULT,
									TimeUnit.SECONDS);

				}

				// To handle cases where nio response never comes back, we
				// schedule a 'timeout' message to be sent to us 2 seconds
				// after NIO's SO_TIMEOUT
				timeoutMessageCancellable = getContext()
						.system()
						.scheduler()
						.scheduleOnce(timeoutDuration, getSelf(),
								MessageType.PROCESS_ON_TIMEOUT,
								getContext().system().dispatcher());

				break;

			case CANCEL:
				cancelCancellable();
				reply(null, true, "RequestCanceled", null, VarUtils.NA);
				break;

			case PROCESS_ON_EXCEPTION:
				final StringWriter sw = new StringWriter();
				final PrintWriter pw = new PrintWriter(sw);
				cause.printStackTrace(pw);

				String displayError = ErrorMsgUtils.replaceErrorMsg(cause
						.toString());

				// 20130522: get details of error message out.
				String detailErrorMsgWithStackTrace = displayError
						+ " Details: " + sw.toString();
				cancelCancellable();
				reply(null, true, detailErrorMsgWithStackTrace,
						sw.toString(), VarUtils.NA);

				break;

			case PROCESS_ON_TIMEOUT:
				 models.utils.LogUtils.printLogError
						 ("!!!Inside PROCESS_ON_TIMEOUT................."
								+ requestUrl
								+ "......... at "
								+ DateUtils.getNowDateTimeStrSdsm());
				cancelCancellable();

				// 20130801 To match this:
				// PATTERN_EXTRACT_EXCEPTION_SUMMARY_FROM_ERROR_MSG to get
				// the regular
				// expression.
				String errorMsg = String
						.format("HttpWorker Timedout after %d SEC (no response but no exception catched). Check URL: may be very slow or stuck. Details more info",
								VarUtils.ACTOR_MAX_OPERATION_TIME_SECONDS_DEFAULT);

				reply(null, true, errorMsg, errorMsg, VarUtils.NA);
				break;

			case PROCESS_ON_RESPONSE_DATA:
				models.utils.LogUtils.printLogNormal
						 ("Inside PROCESS_ON_RESPONSE_DATA UnsupportedOperation.................");
				cancelCancellable();
				reply(null, true, "UnsupportedOperation", null, VarUtils.NA);
				break;
			}
		} else {
			unhandled(message);
		}
	} catch (Exception e) {
		tryCount = maxTries;
		this.cause = e;
		getSelf().tell(MessageType.PROCESS_ON_EXCEPTION, getSelf());
	}
}