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

The following examples show how to use com.ning.http.client.AsyncHttpClient#BoundRequestBuilder . 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: ProxyServiceImpl.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private boolean existAgent(String url, @RequestParam String agentIp) {
    try {
        AsyncHttpClient.BoundRequestBuilder builder = httpClient.prepareGet(url);
        builder.addQueryParam("ip", agentIp);
        Response response = httpClient.executeRequest(builder.build()).get();
        if (response.getStatusCode() == 200) {
            ApiResult<AgentInfo> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), AGENT_TYPE_REFERENCE);
            if (result.getStatus() == 0) {
                return true;
            }
        }
    } catch (Exception e) {
        logger.error("query exist agent error, agent ip [{}], url [{}]", agentIp, url, e);
    }
    return false;
}
 
Example 2
Source File: Configs.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private static ProxyConfig getProxyConfig(String bistouryHost) {
    String url = "http://" + bistouryHost + PROXY_URI;
    try {
        AsyncHttpClient client = AsyncHttpClientHolder.getInstance();
        AsyncHttpClient.BoundRequestBuilder builder = client.prepareGet(url);
        builder.setHeader("content-type", "application/json;charset=utf-8");
        Response response = client.executeRequest(builder.build()).get();
        if (response.getStatusCode() != 200) {
            logger.error("get proxy config error, http code [{}], url [{}]", response.getStatusCode(), url);
            return null;
        }

        JsonResult<ProxyConfig> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), PROXY_REFERENCE);
        if (!result.isOK()) {
            logger.error("get proxy config error, status code [{}], url [{}]", result.getStatus(), url);
            return null;
        }

        return result.getData();
    } catch (Throwable e) {
        logger.error("get proxy config error, url [{}]", url, e);
        return null;
    }
}
 
Example 3
Source File: HttpRequestClient.java    From qconfig with MIT License 6 votes vote down vote up
public <R> JsonV2<R> get(String url, Map<String, String> params, TypeReference<JsonV2<R>> typeReference) {
    AsyncHttpClient.BoundRequestBuilder prepareGet = httpClient.prepareGet(url);
    prepareGet.setHeader("Accept", "application/json");
    prepareGet.setHeader("Content-Type", "application/json; charset=utf-8");
    if (!CollectionUtils.isEmpty(params)) {
        for (Map.Entry<String, String> param : params.entrySet()) {
            prepareGet.addQueryParam(param.getKey(), param.getValue());
        }
    }
    Request request = prepareGet.build();
    try {
        Response response = httpClient.executeRequest(request).get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
        int statusCode = response.getStatusCode();
        if (statusCode != Constants.OK_STATUS) {
            throw new RuntimeException(String.format("http request error,url:%s,status code:%d",url,statusCode));
        }
        return mapper.readValue(response.getResponseBody(DEFAULT_CHARSET), typeReference);
    }  catch (Exception e) {
        logger.error("request failOf, url [{}], params {}", url, params, e);
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: BaseClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
protected Response post(String endpoint, String data) throws Exception {
    AsyncHttpClient.BoundRequestBuilder request = this.httpClient.preparePost(endpoint);
    request = request.setBody(data);
    request = request.setCookies(cookies);
    Response response = request.execute().get();
    this.log.debug("PUT to " + response.getUri() + ":" + response.getResponseBody());
    return response;
}
 
Example 5
Source File: HttpClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
/**
 * Http delete request
 *
 * @param url url for the request
 * @return request builder
 */
public RequestBuilder delete(final String url) {

  checkNotNull(url, "url may not be null");
  final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.prepareDelete(url);
  return createNewRequestBuilder(url, ningRequestBuilder);
}
 
Example 6
Source File: HttpClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
/**
 * Http post request
 *
 * @param url url for the request
 * @return request builder
 */
public RequestBuilder post(final String url) {

  checkNotNull(url, "url may not be null");
  final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.preparePost(url);
  return createNewRequestBuilder(url, ningRequestBuilder);
}
 
Example 7
Source File: QConfigAdminClient.java    From qconfig with MIT License 5 votes vote down vote up
@Override
protected AsyncHttpClient.BoundRequestBuilder buildRequest(String url) throws IOException {
    AsyncHttpClient.BoundRequestBuilder builder = HttpClientHolder.INSTANCE.preparePost(url);
    builder.addQueryParam(Constants.TOKEN_NAME, token)
            .addQueryParam(Constants.GROUP_NAME, meta.getGroupName())
            .addQueryParam(Constants.DATAID_NAME, meta.getFileName())
            .addQueryParam(Constants.EDIT_VERSION, String.valueOf(basedVersion))
            .addQueryParam(Constants.BUILD_GROUP, EnvironmentAware.determinedEnv())
            .addQueryParam(Constants.FILE_PROFILE, fileProfile)
            .addQueryParam(Constants.API_VERSION, API_V)
            .addQueryParam(Constants.OPERATOR, operator)
            .addQueryParam(Constants.STATUS_CODE, String.valueOf(statusType.code()))
            .addQueryParam(Constants.ISPUBLIC, String.valueOf(isPublic));
    return builder;
}
 
Example 8
Source File: QConfigAdminClient.java    From qconfig with MIT License 5 votes vote down vote up
@Override
protected AsyncHttpClient.BoundRequestBuilder buildRequest(String url) throws IOException {
    AsyncHttpClient.BoundRequestBuilder builder = HttpClientHolder.INSTANCE.prepareGet(url);
    builder.addQueryParam(Constants.TOKEN_NAME, token)
            .addQueryParam(Constants.GROUP_NAME, group)
            .addQueryParam(Constants.DATAID_NAME, dataId)
            .addQueryParam(Constants.BUILD_GROUP, EnvironmentAware.determinedEnv())
            .addQueryParam(Constants.API_VERSION, API_V);
    return builder;
}
 
Example 9
Source File: QConfigHttpServerClient.java    From qconfig with MIT License 5 votes vote down vote up
@Override
protected AsyncHttpClient.BoundRequestBuilder buildRequest(String url) throws IOException {
    return HttpClientHolder.INSTANCE.prepareGet(url)
            .addQueryParam(Constants.GROUP_NAME, meta.getGroupName())
            .addQueryParam(Constants.DATAID_NAME, meta.getFileName())
            .addQueryParam(Constants.VERSION_NAME, String.valueOf(version.getVersion()))
            .addQueryParam(Constants.LOAD_PROFILE_NAME, version.getProfile());
}
 
Example 10
Source File: QConfigHttpServerClient.java    From qconfig with MIT License 5 votes vote down vote up
@Override
protected AsyncHttpClient.BoundRequestBuilder buildRequest(String url) {
    return HttpClientHolder.INSTANCE.preparePost(url)
            .addQueryParam(Constants.GROUP_NAME, meta.getGroupName())
            .addQueryParam(Constants.DATAID_NAME, meta.getFileName())
            .addQueryParam(Constants.VERSION_NAME, String.valueOf(version))
            .addQueryParam(Constants.CONFIG_LOG_TYPE_CODE, String.valueOf(type.getCode()))
            .addQueryParam(Constants.REMARKS_NAME, remarks);
}
 
Example 11
Source File: HttpClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
/**
 * Http put request
 *
 * @param url url for the request
 * @return request builder
 */
public RequestBuilder put(final String url) {

  checkNotNull(url, "url may not be null");
  final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder = asyncHttpClient.preparePut(url);
  return createNewRequestBuilder(url, ningRequestBuilder);
}
 
Example 12
Source File: QConfigHttpServerClient.java    From qconfig with MIT License 5 votes vote down vote up
@Override
protected AsyncHttpClient.BoundRequestBuilder buildRequest(String url) throws IOException {
    AsyncHttpClient.BoundRequestBuilder builder = HttpClientHolder.INSTANCE.preparePost(url);
    builder.addHeader(Constants.NEED_PURGE, Boolean.TRUE.toString());
    if (!isEmpty(group)) {
        builder.addQueryParam(Constants.GROUP_NAME, group);
    }
    builder.setBody(params);
    return builder;
}
 
Example 13
Source File: NingRequestBuilder.java    From ob1k with Apache License 2.0 5 votes vote down vote up
public NingRequestBuilder(final AsyncHttpClient asyncHttpClient, final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder,
                          final String requestUrl, final long responseMaxSize, final MarshallingStrategy marshallingStrategy) {

  this.asyncHttpClient = checkNotNull(asyncHttpClient, "asyncHttpClient may not be null");
  this.ningRequestBuilder = checkNotNull(ningRequestBuilder, "ningRequestBuilder may not be null");
  this.requestUrl = checkNotNull(requestUrl, "requestUrl may not be null");
  this.responseMaxSize = responseMaxSize;
  this.marshallingStrategy = marshallingStrategy;
}
 
Example 14
Source File: NotifyServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
private Request getRequest(String url, String group, String dataId, String profile) {
    AsyncHttpClient.BoundRequestBuilder builder = httpClient.preparePost(url);
    builder.addFormParam(Constants.GROUP_NAME, group)
            .addFormParam(Constants.DATAID_NAME, dataId)
            .addFormParam(Constants.PROFILE_NAME, profile);
    return builder.build();
}
 
Example 15
Source File: DatastoreImpl.java    From async-datastore-client with Apache License 2.0 5 votes vote down vote up
AsyncHttpClient.BoundRequestBuilder prepareRequest(final String method, final ProtoHttpContent payload) throws IOException {
  final AsyncHttpClient.BoundRequestBuilder builder = client.preparePost(prefixUri + method);
  builder.addHeader("Authorization", "Bearer " + accessToken);
  builder.addHeader("Content-Type", "application/x-protobuf");
  builder.addHeader("User-Agent", USER_AGENT);
  builder.addHeader("Accept-Encoding", "gzip");
  builder.setContentLength((int) payload.getLength());
  builder.setBody(payload.getMessage().toByteArray());
  return builder;
}
 
Example 16
Source File: JsonAsyncHttpPinotClientTransport.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public Future<BrokerResponse> executePinotQueryAsync(String brokerAddress, final Request request) {
  try {
    ObjectNode json = JsonNodeFactory.instance.objectNode();
    String queryFormat = request.getQueryFormat();
    json.put(queryFormat, request.getQuery());

    final String url;
    if (queryFormat.equalsIgnoreCase("sql")) {
      url = "http://" + brokerAddress + "/query/sql";
      json.put("queryOptions", "groupByMode=sql;responseFormat=sql");
    } else {
      url = "http://" + brokerAddress + "/query";
    }

    AsyncHttpClient.BoundRequestBuilder requestBuilder = _httpClient.preparePost(url);

    if (_headers != null) {
      _headers.forEach((k, v) -> requestBuilder.addHeader(k, v));
    }

    final Future<Response> response =
        requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8").setBody(json.toString())
            .execute();

    return new BrokerResponseFuture(response, request.getQuery(), url);
  } catch (Exception e) {
    throw new PinotClientException(e);
  }
}
 
Example 17
Source File: BaseClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
protected Response put(String endpoint, String data) throws Exception {
    AsyncHttpClient.BoundRequestBuilder request = this.httpClient.preparePut(endpoint);
    request = request.setBody(data);
    request = request.setCookies(cookies);
    Response response = request.execute().get();
    this.log.debug("PUT to " + response.getUri() + ":" + response.getResponseBody());
    return response;
}
 
Example 18
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false"
}, splitBy = "\\|")
@Test
public void executeAsyncHttpRequest_sets_up_and_executes_call_as_expected(
    boolean performSubspan, boolean currentTracingInfoNull
) {
    // given
    Whitebox.setInternalState(helperSpy, "performSubSpanAroundDownstreamCalls", performSubspan);

    CircuitBreaker<Response> circuitBreakerMock = mock(CircuitBreaker.class);
    doReturn(Optional.of(circuitBreakerMock)).when(helperSpy).getCircuitBreaker(any(RequestBuilderWrapper.class));
    ManualModeTask<Response> cbManualTaskMock = mock(ManualModeTask.class);
    doReturn(cbManualTaskMock).when(circuitBreakerMock).newManualModeTask();

    String url = "http://localhost/some/path";
    String method = "GET";
    AsyncHttpClient.BoundRequestBuilder reqMock = mock(AsyncHttpClient.BoundRequestBuilder.class);
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(url, method, reqMock, Optional.empty(), false);
    AsyncResponseHandler responseHandlerMock = mock(AsyncResponseHandler.class);

    Span initialSpan = (currentTracingInfoNull) ? null : Tracer.getInstance().startRequestWithRootSpan("foo");
    Deque<Span> initialSpanStack = (currentTracingInfoNull)
                                   ? null
                                   : Tracer.getInstance().getCurrentSpanStackCopy();
    Map<String, String> initialMdc = (currentTracingInfoNull) ? null : MDC.getCopyOfContextMap();
    resetTracingAndMdc();

    // when
    CompletableFuture resultFuture = helperSpy.executeAsyncHttpRequest(
        rbw, responseHandlerMock, initialSpanStack, initialMdc
    );

    // then
    // Verify that the circuit breaker came from the getCircuitBreaker helper method and that its
    //      throwExceptionIfCircuitBreakerIsOpen() method was called.
    verify(helperSpy).getCircuitBreaker(rbw);
    verify(cbManualTaskMock).throwExceptionIfCircuitBreakerIsOpen();

    // Verify that the inner request's execute method was called with a
    //      AsyncCompletionHandlerWithTracingAndMdcSupport for the handler.
    ArgumentCaptor<AsyncHandler> executedHandlerCaptor = ArgumentCaptor.forClass(AsyncHandler.class);
    verify(reqMock).execute(executedHandlerCaptor.capture());
    AsyncHandler executedHandler = executedHandlerCaptor.getValue();
    assertThat(executedHandler).isInstanceOf(AsyncCompletionHandlerWithTracingAndMdcSupport.class);

    // Verify that the AsyncCompletionHandlerWithTracingAndMdcSupport was created with the expected args
    AsyncCompletionHandlerWithTracingAndMdcSupport achwtams =
        (AsyncCompletionHandlerWithTracingAndMdcSupport) executedHandler;
    assertThat(achwtams.completableFutureResponse).isSameAs(resultFuture);
    assertThat(achwtams.responseHandlerFunction).isSameAs(responseHandlerMock);
    assertThat(achwtams.performSubSpanAroundDownstreamCalls).isEqualTo(performSubspan);
    assertThat(achwtams.circuitBreakerManualTask).isEqualTo(Optional.of(cbManualTaskMock));
    if (performSubspan) {
        int initialSpanStackSize = (initialSpanStack == null) ? 0 : initialSpanStack.size();
        assertThat(achwtams.distributedTraceStackToUse).hasSize(initialSpanStackSize + 1);
        Span subspan = (Span) achwtams.distributedTraceStackToUse.peek();
        assertThat(subspan.getSpanName())
            .isEqualTo(initialSpanNameFromStrategy.get());
        if (initialSpan != null) {
            assertThat(subspan.getTraceId()).isEqualTo(initialSpan.getTraceId());
            assertThat(subspan.getParentSpanId()).isEqualTo(initialSpan.getSpanId());
        }
        assertThat(achwtams.mdcContextToUse.get(SpanFieldForLoggerMdc.TRACE_ID.mdcKey)).isEqualTo(subspan.getTraceId());
    }
    else {
        assertThat(achwtams.distributedTraceStackToUse).isSameAs(initialSpanStack);
        assertThat(achwtams.mdcContextToUse).isSameAs(initialMdc);
    }

    // Verify that the trace headers were added (or not depending on state).
    Span spanForDownstreamCall = achwtams.getSpanForCall();
    if (initialSpan == null && !performSubspan) {
        assertThat(spanForDownstreamCall).isNull();
        verifyNoMoreInteractions(reqMock);
    }
    else {
        assertThat(spanForDownstreamCall).isNotNull();
        verify(reqMock).setHeader(TraceHeaders.TRACE_SAMPLED,
                                  convertSampleableBooleanToExpectedB3Value(spanForDownstreamCall.isSampleable()));
        verify(reqMock).setHeader(TraceHeaders.TRACE_ID, spanForDownstreamCall.getTraceId());
        verify(reqMock).setHeader(TraceHeaders.SPAN_ID, spanForDownstreamCall.getSpanId());
        if (spanForDownstreamCall.getParentSpanId() == null) {
            verify(reqMock, never()).setHeader(eq(TraceHeaders.PARENT_SPAN_ID), anyString());
        }
        else {
            verify(reqMock).setHeader(TraceHeaders.PARENT_SPAN_ID, spanForDownstreamCall.getParentSpanId());
        }
        verify(reqMock, never()).setHeader(eq(TraceHeaders.SPAN_NAME), anyString());
    }

    // Verify that any subspan had request tagging performed.
    if (performSubspan) {
        strategyRequestTaggingArgs.get().verifyArgs(spanForDownstreamCall, rbw, wingtipsTagAndNamingAdapterMock);
    }
}
 
Example 19
Source File: HttpClient.java    From ob1k with Apache License 2.0 2 votes vote down vote up
private NingRequestBuilder createNewRequestBuilder(final String url, final AsyncHttpClient.BoundRequestBuilder ningRequestBuilder) {

    return new NingRequestBuilder(asyncHttpClient, ningRequestBuilder, url, responseMaxSize, marshallingStrategy);
  }
 
Example 20
Source File: QConfigAdminClient.java    From qconfig with MIT License votes vote down vote up
protected abstract AsyncHttpClient.BoundRequestBuilder buildRequest(String url) throws IOException;