當前位置: 首頁>>代碼示例>>Java>>正文


Java AsyncHttpClient.BoundRequestBuilder方法代碼示例

本文整理匯總了Java中com.ning.http.client.AsyncHttpClient.BoundRequestBuilder方法的典型用法代碼示例。如果您正苦於以下問題:Java AsyncHttpClient.BoundRequestBuilder方法的具體用法?Java AsyncHttpClient.BoundRequestBuilder怎麽用?Java AsyncHttpClient.BoundRequestBuilder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.ning.http.client.AsyncHttpClient的用法示例。


在下文中一共展示了AsyncHttpClient.BoundRequestBuilder方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testJobSidelining_ShouldSidelineJobsAfter404s

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Test
public void testJobSidelining_ShouldSidelineJobsAfter404s() throws Exception {
    /* Creating legit job */
    AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob1", "http://localhost:11000/test", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponse = request.execute();
    final Response response = futureResponse.get();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    /* Creating Job that is destined to be sidelined*/
    AsyncHttpClient.BoundRequestBuilder request2 = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request2.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob2", "http://localhost:11000/test/404", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponseForRequest2 = request2.execute();
    final Response response2 = futureResponseForRequest2.get();
    assertThat(response2.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    Thread.sleep(5 * TestConstants.ONE_SECOND + 100l);
    testApiCounter.assertHeard("test", 5); // Legit job executed 5 times in 5 seconds
    testApiCounter.assertHeard("test404", 3); // Doomed job executed just thrice
    final Iterable<Job> allJobs = repository.findAll();
    assertThat(allJobs).extracting(Job::getName).containsExactly("testJob1","testJob2");
    assertThat(allJobs).extracting("sideLined",Boolean.class).containsExactly(false,true);
}
 
開發者ID:flipkart-incubator,項目名稱:simpleJobScheduler,代碼行數:24,代碼來源:JobControllerIntegrationTest.java

示例2: testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Test
public void testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule() throws Exception {
    /* Creating Job that is destined to be sidelined*/
    AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob2", "http://localhost:11000/test/404", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponseForRequest = request.execute();
    final Response response = futureResponseForRequest.get();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    Thread.sleep(4 * TestConstants.ONE_SECOND + 100l);
    testApiCounter.assertHeard("test404", 3); // Doomed job executed just thrice
    final List<Job> allJobs = repository.findAll();
    assertThat(allJobs).extracting("sideLined", Boolean.class).containsExactly(true); // asserting job is sidelined

    AsyncHttpClient.BoundRequestBuilder requestUnSideline = asyncHttpClient.preparePut("http://localhost:11000/jobs/testJob2/unsideline").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    final ListenableFuture<Response> unsidelineResponse = requestUnSideline.execute();
    assertThat(unsidelineResponse.get().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    assertThat((repository.findByName("testJob2").isSidelined())).isFalse(); // This check should happen within 3 seconds of the job being unsidelined. Mostly we are good

}
 
開發者ID:flipkart-incubator,項目名稱:simpleJobScheduler,代碼行數:21,代碼來源:JobControllerIntegrationTest.java

示例3: getAsyncRequestBuilder

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
private AsyncHttpClient.BoundRequestBuilder getAsyncRequestBuilder(AsyncHttpClient client, Map<String, String> queryString, String... paths) {
    String target = config.getServerName();
    if (config.getServerPort() != 80) {
        target = target + ":" + config.getServerPort();
    }
    for (String path : paths) {
        target += path;
    }
    AsyncHttpClient.BoundRequestBuilder requestBuilder = client.preparePost(target);

    for (String key : queryString.keySet()) {
        requestBuilder.addQueryParameter(key, queryString.get(key));
    }
    requestBuilder.addHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
    return requestBuilder;
}
 
開發者ID:viant,項目名稱:jdsunit,代碼行數:17,代碼來源:DsUnitClientImpl.java

示例4: post

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
/**
 * Query Druid with Post.
 *
 * @param url     <Broker>:<Port, default: 8082>
 * @param json    query json
 * @param timeOut the timeout of http connection, default unit is millisecond
 * @param charset charset
 * @return the result of query
 */
public static String post(String url, String json, Long timeOut, TimeUnit timeUnit, String charset) {
    Future<Response> f = null;
    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient()) {
        AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient.preparePost(url);
        builder.setBodyEncoding(StrUtils.UTF_8).setBody(json);
        return (f = builder.execute()).get(timeOut == null ? DEFEAT_TIMEOUT : timeOut,
                timeUnit == null ? DEFEAT_UNIT : timeUnit)
                .getResponseBody(charset == null ? StrUtils.UTF_8 : charset);
    } catch (Exception e) {
        _log.error(ExceptionUtils.errorInfo(e));
        throw new RuntimeException(e);
    } finally {
        if (f != null) f.cancel(true);
    }
}
 
開發者ID:asdf2014,項目名稱:yuzhouwan,代碼行數:25,代碼來源:DruidRestUtils.java

示例5: doCall

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
private <T> T doCall(final String verb, final String uri, final Object body, final Map<String, String> options, final int timeoutSec, final Class<T> clazz) throws FeedzaiClientException {
    final String url = getFeedzaiUrl(location, uri);
    final AsyncHttpClient.BoundRequestBuilder builder = getBuilderWithHeaderAndQuery(verb, url, apiKey, options);
    if (!"GET".equals(verb) && !"HEAD".equals(verb)) {
        if (body != null) {
            try {
                final String bodyJson = mapper.writeValueAsString(body);
                if (isPrintRequestsDetails) {
                    log.info("DefaultFeedzaiClient Sending: " + bodyJson);
                }
                builder.setBody(bodyJson);
            } catch (JsonProcessingException e) {
            }
        } else {
            builder.setBody("{}");
        }
    }
    return executeAndWait(builder, timeoutSec, clazz);
}
 
開發者ID:killbill,項目名稱:feedzai-client,代碼行數:20,代碼來源:DefaultFeedzaiClient.java

示例6: populate

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
public void populate(AsyncHttpClient.BoundRequestBuilder req) {
    req.addParameter("count", count + "");

    if (follow != null && follow.length > 0) {
        req.addParameter("follow", ON_COMMA.join(Longs.asList(follow)));
    }

    if (track != null && track.length > 0) {
        req.addParameter("track"
                , ON_COMMA.join(track));
    }

    if (locations != null && locations.length > 0) {
        req.addParameter("locations"
                , toLocationsString(locations));
    }

    if (language != null && language.length > 0) {
        req.addParameter("language"
                , ON_COMMA.join(language));
    }
}
 
開發者ID:eshioji,項目名稱:toy-java8,代碼行數:23,代碼來源:FilterQuery.java

示例7: read

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@SuppressWarnings("deprecation")
public Optional<MesosFileChunkObject> read(String slaveHostname, String fullPath, Optional<Long> offset, Optional<Long> length) throws SlaveNotFoundException {
  try {
    final AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient.prepareGet(String.format("http://%s:5051/files/read.json", slaveHostname))
        .addQueryParameter("path", fullPath);

    PerRequestConfig timeoutConfig = new PerRequestConfig();
    timeoutConfig.setRequestTimeoutInMs((int) configuration.getSandboxHttpTimeoutMillis());
    builder.setPerRequestConfig(timeoutConfig);

    if (offset.isPresent()) {
      builder.addQueryParameter("offset", offset.get().toString());
    }

    if (length.isPresent()) {
      builder.addQueryParameter("length", length.get().toString());
    }

    final Response response = builder.execute().get();

    if (response.getStatusCode() == 404) {
      return Optional.absent();
    }

    if (response.getStatusCode() != 200) {
      throw new RuntimeException(String.format("Got HTTP %s from Mesos slave", response.getStatusCode()));
    }

    return Optional.of(objectMapper.readValue(response.getResponseBodyAsStream(), MesosFileChunkObject.class));
  } catch (ConnectException ce) {
    throw new SlaveNotFoundException(ce);
  } catch (Exception e) {
    if ((e.getCause() != null) && (e.getCause().getClass() == ConnectException.class)) {
      throw new SlaveNotFoundException(e);
    } else {
      throw Throwables.propagate(e);
    }
  }
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Mesos,代碼行數:40,代碼來源:SandboxManager.java

示例8: RequestBuilderWrapper

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
/**
 * Intentionally package-scoped. Instances of this class are generated and returned by calling one of the
 * request-starter methods in {@link AsyncHttpClientHelper}, e.g. {@link
 * AsyncHttpClientHelper#getRequestBuilder(String, HttpMethod)}.
 */
RequestBuilderWrapper(
    String url, String httpMethod, AsyncHttpClient.BoundRequestBuilder requestBuilder,
    Optional<CircuitBreaker<Response>> customCircuitBreaker, boolean disableCircuitBreaker
) {
    this.url = url;
    this.httpMethod = httpMethod;
    this.requestBuilder = requestBuilder;
    this.customCircuitBreaker = customCircuitBreaker;
    this.disableCircuitBreaker = disableCircuitBreaker;
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:16,代碼來源:RequestBuilderWrapper.java

示例9: testJobCreation_ShouldRunJobsAsPerSchedule

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Test
public void testJobCreation_ShouldRunJobsAsPerSchedule() throws Exception {
    AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob1", "http://localhost:11000/test", TestConstants.ONE_SECOND)));
    final ListenableFuture<Response> futureResponse = request.execute();
    final Response response = futureResponse.get();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    Thread.sleep(3 * TestConstants.ONE_SECOND + 100l);
    testApiCounter.assertHeard("test", 3);
    final Iterable<Job> allJobs = repository.findAll();
    assertThat(allJobs).extracting(Job::getName).containsExactly("testJob1");
}
 
開發者ID:flipkart-incubator,項目名稱:simpleJobScheduler,代碼行數:13,代碼來源:JobControllerIntegrationTest.java

示例10: testOneTimeJobCreation_ShouldRunJobAsPerSchedule

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Test
public void testOneTimeJobCreation_ShouldRunJobAsPerSchedule() throws JsonProcessingException, ExecutionException, InterruptedException {
    AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/oneTime").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestOneTimeJob("testJob1", "http://localhost:11000/test", System.currentTimeMillis() + 1000l)));
    final ListenableFuture<Response> futureResponse = request.execute();
    final Response response = futureResponse.get();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    Thread.sleep(TestConstants.ONE_SECOND + 200l);
    testApiCounter.assertHeard("test", 1);
    final Iterable<Job> allJobs = repository.findAll();
    assertThat(allJobs).isEmpty(); // one time job should be deleted
}
 
開發者ID:flipkart-incubator,項目名稱:simpleJobScheduler,代碼行數:13,代碼來源:JobControllerIntegrationTest.java

示例11: makeRequest

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
public Response makeRequest(final Request request) {
    if ("GET".equals(request.method())) {
        final String url = config.providerRoot().url() + request.path();

        try {
            AsyncHttpClient.BoundRequestBuilder boundRequestBuilder = httpClient
                    .prepareGet(url)
                    .addQueryParams(parseParams(request));

            if (request.headers().nonEmpty()) {
                ImmutableMap<String, String> headerMap = ScalaInterop.fromMap(request.headers().get());
                headerMap.entrySet()
                        .stream()
                        .forEach(entry -> boundRequestBuilder.addHeader(entry.getKey(), entry.getValue()));
            }

            com.ning.http.client.Response response = (com.ning.http.client.Response) boundRequestBuilder
                    .execute()
                    .get();
            return Response.apply(
                    response.getStatusCode(),
                    convertHeaders(response.getHeaders()),
                    response.getResponseBody(),
                    noResponseMatchingRules());
        } catch (InterruptedException | ExecutionException | IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("HTTP Method " + request.method() + " is not implemented yet");
    }
}
 
開發者ID:otto-de,項目名稱:pact-jvm-provider-generic,代碼行數:32,代碼來源:ProviderClient.java

示例12: getOrders

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Override
public ListenableFuture<Orders> getOrders(long timestamp, Order.Side side, Iterable<Order.Status> status, Iterable<Order.OrderType> orderTypes, int page, int pageSize) {
    AsyncHttpClient.BoundRequestBuilder builder = httpClient.prepareGet(baseUrl + "/v1/orders")
            .addHeader("X-Buttercoin-Date", "" + timestamp);

    if (side != null) builder.addQueryParam("side", side.getName());
    if (status != null && status.iterator().hasNext()) builder.addQueryParam("status", mkString(status, ","));
    if (orderTypes != null && orderTypes.iterator().hasNext())
        builder.addQueryParam("orderType", mkString(orderTypes, ","));

    if (page > 0) builder.addQueryParam("page", "" + page);
    if (pageSize > 0) builder.addQueryParam("pageSize", "" + pageSize);

    return transform(new ListenableFutureAdapter<>(builder.setSignatureCalculator(signatureCalculator()).execute(new ThrowOnHttpFailure())), new MapResponseJson<>(objectMapper.reader(Orders.class)));
}
 
開發者ID:buttercoin,項目名稱:buttercoin-java,代碼行數:16,代碼來源:Buttercoin.java

示例13: createOrder

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Override
public ListenableFuture<URL> createOrder(long timestamp, CreateOrder.Instrument instrument, Order.Side side, Order.OrderType orderType, BigDecimal price, BigDecimal quantity) {
    AsyncHttpClient.BoundRequestBuilder builder = httpClient.preparePost(baseUrl + "/v1/orders");
    builder.addHeader("Content-Type", "application/json");
    builder.addHeader("X-Buttercoin-Date", "" + timestamp);
    try {
        builder.setBody(objectMapper.writeValueAsString(new CreateOrder(instrument, side, orderType,
                price.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString(),
                quantity.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString())));
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
    return transform(new ListenableFutureAdapter<>(builder.setSignatureCalculator(signatureCalculator()).execute(new ThrowOnHttpFailure())), new Status202ExtractLocation());
}
 
開發者ID:buttercoin,項目名稱:buttercoin-java,代碼行數:15,代碼來源:Buttercoin.java

示例14: getTransactions

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Override
public ListenableFuture<Transactions> getTransactions(long timestamp, Iterable<Transaction.Status> status, Iterable<Transaction.TransactionType> transactionTypes, int page, int pageSize) {
    AsyncHttpClient.BoundRequestBuilder builder = httpClient.prepareGet(baseUrl + "/v1/transactions")
            .addHeader("X-Buttercoin-Date", "" + timestamp);

    if (status != null && status.iterator().hasNext()) builder.addQueryParam("status", mkString(status, ","));
    if (transactionTypes != null && transactionTypes.iterator().hasNext())
        builder.addQueryParam("transactionType", mkString(transactionTypes, ","));

    if (page > 0) builder.addQueryParam("page", "" + page);
    if (pageSize > 0) builder.addQueryParam("pageSize", "" + pageSize);

    return transform(new ListenableFutureAdapter<>(builder.setSignatureCalculator(signatureCalculator()).execute(new ThrowOnHttpFailure())), new MapResponseJson<>(objectMapper.reader(Transactions.class)));
}
 
開發者ID:buttercoin,項目名稱:buttercoin-java,代碼行數:15,代碼來源:Buttercoin.java

示例15: createDeposit

import com.ning.http.client.AsyncHttpClient; //導入方法依賴的package包/類
@Override
public ListenableFuture<URL> createDeposit(long timestamp, String method, String currency, BigDecimal amount) {
    AsyncHttpClient.BoundRequestBuilder builder = httpClient.preparePost(baseUrl + "/v1/transactions/deposit");
    builder.addHeader("Content-Type", "application/json");
    builder.addHeader("X-Buttercoin-Date", "" + timestamp);
    try {
        builder.setBody(objectMapper.writeValueAsString(new CreateDeposit(method, currency, amount)));
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
    return transform(new ListenableFutureAdapter<>(builder.setSignatureCalculator(signatureCalculator()).execute(new ThrowOnHttpFailure())), new Status202ExtractLocation());
}
 
開發者ID:buttercoin,項目名稱:buttercoin-java,代碼行數:13,代碼來源:Buttercoin.java


注:本文中的com.ning.http.client.AsyncHttpClient.BoundRequestBuilder方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。