本文整理汇总了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);
}
示例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
}
示例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;
}
示例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);
}
}
示例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);
}
示例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));
}
}
示例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);
}
}
}
示例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;
}
示例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");
}
示例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
}
示例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");
}
}
示例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)));
}
示例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());
}
示例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)));
}
示例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());
}