本文整理汇总了Java中com.ning.http.client.ListenableFuture类的典型用法代码示例。如果您正苦于以下问题:Java ListenableFuture类的具体用法?Java ListenableFuture怎么用?Java ListenableFuture使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ListenableFuture类属于com.ning.http.client包,在下文中一共展示了ListenableFuture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testJobSidelining_ShouldSidelineJobsAfter404s
import com.ning.http.client.ListenableFuture; //导入依赖的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.ListenableFuture; //导入依赖的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: replay
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
public ListenableFuture<Response> replay(final LogLineData logLineData) throws IOException {
BoundRequestBuilder req = asyncHttpClient.prepareGet(host + logLineData.getRequest());
req.setFollowRedirects(followRedirects);
String usedHostHeader = null;
if (logLineData.getHost() == null) {
if (hostHeader != null) {
usedHostHeader = hostHeader;
}
} else {
usedHostHeader = logLineData.getHost();
}
req = req.setVirtualHost(usedHostHeader);
for (final Header header : headers) {
req = req.setHeader(header.getName(), header.getValue());
}
if (logLineData.getUserAgent() != null) {
req.setHeader("user-agent", logLineData.getUserAgent());
}
LOG.info("Executing request {}: {} with host headers {}", req, host + logLineData.getRequest(), usedHostHeader);
return req.execute(new LoggingAsyncCompletionHandler(logLineData, resultDataLogger));
}
示例4: executeDirectTestCase
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
public List<TestCaseReport> executeDirectTestCase(TestCase testCase, TestCaseExecutorUtil testCaseExecutorUtil) {
TestCaseReport testCaseReport = new TestCaseReport();
testCaseReport.setTestCase(testCase);
testCaseReport.setNumberOfRuns(1);
ListenableFuture<TestCaseReport> report = testCaseExecutorUtil.executeTestCase(testCase, testCaseReport);
try {
testCaseReport = report.get();
} catch (Exception e) {
testCaseReport.setStatus(TestStatus.Failed.status);
testCaseReport.setError(e.getMessage());
testCaseReport.setErrorText(ExceptionUtils.getStackTrace(e));
e.printStackTrace();
}
List<TestCaseReport> lst = new ArrayList<TestCaseReport>();
lst.add(testCaseReport);
return lst;
}
示例5: expectZergCall
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private ListenableFuture<Response> expectZergCall() throws Exception {
BoundRequestBuilder requestBuilder = createMock(BoundRequestBuilder.class);
final com.ning.http.client.ListenableFuture<Response> future = createMock(com.ning.http.client.ListenableFuture.class);
expect(client.prepareGet("/path")).andReturn(requestBuilder);
expect(requestBuilder.execute()).andReturn(future);
final Capture<Runnable> chainingListenableFutureCapture = new Capture<Runnable>();
expect(future.addListener(capture(chainingListenableFutureCapture), isA(Executor.class))).andStubAnswer(new IAnswer<ListenableFuture<Response>>() {
@Override
public ListenableFuture<Response> answer() throws Throwable {
// Invoking this ChainingListenableFuture is necessary or the tests will hang.
chainingListenableFutureCapture.getValue().run();
return future;
}
});
return future;
}
示例6: get_text_content
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
/**
* Populate text_content field
*
* @param reddit Reddit class to access API with
* @return a ListenableFuture<Post> that runs when content is available
*/
public ListenableFuture<Post> get_text_content(Reddit reddit) {
ListenableFuture<Post> ret = new ListenableFutureTask<Post>();
if (!text_content.isEmpty()) {
ret.content(this);
} else {
try {
ListenableFuture<String> html = reddit.http.get_html(url);
html.addListener(
new BoilerpipeHandler(this, ret, html),
reddit.executor);
} catch (IOException ex) {
text_content = "<connection error:" + ex.getMessage() + ">";
ret.content(this);
}
}
return ret;
}
示例7: run
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
@Override
public void run() {
final List<Post> posts;
try {
posts = posts_future.get();
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(Rreader.class.getName()).log(Level.SEVERE, "Something bad happened", ex);
return;
}
System.out.format("Got %d posts, processing...", posts.size());
List<ChordHandler> handlers = new LinkedList<>();
Runnable finished = new PrintAllPosts(posts);
for (Post p : posts) {
ListenableFuture<Post> futu = p.get_text_content(reddit);
ChordHandler handler = new ChordHandler(futu, handlers, finished);
futu.addListener(handler, executor);
handlers.add(handler);
}
}
示例8: buildRequest
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
/**
* Take a given request and type and return a listenable future of {@link ApiResponse} for that request. This
* handles making the request, translating the response, and returning a future.
*
* @throws ApiClientException
* if the http client throws an {@link IOException}
*
* @param requestParams
* the request information
* @param type
* the type of the returned success response
*
* @return the future to the response of this request
*/
/* package */<T> ListenableFuture<ApiResponse<T>> getResponse(
final RequestParams requestParams, final Type type) {
log.debug("Call with request params: {}", requestParams);
Request request = buildRequest(requestParams);
try {
log.debug("Executing request: {}", request);
return client.executeRequest(request,
new ResponseCompletionHandler<ApiResponse<T>>(type));
} catch (IOException e) {
log.error("IOException making http request (message={})! "
+ " Throwing ApiClientException!", e.getMessage());
throw new ApiClientException(
"Exception while making http request!", e);
}
}
示例9: login
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
@Override
public boolean login(String username, String password) throws IOException {
Request request = getClient().preparePost(getBaseUrl() + LOGIN_PATH)
.addParameter(LOGIN_PARAM_USERNAME, username)
.addParameter(LOGIN_PARAM_PASSWORD, password)
.addParameter(LOGIN_PARAM_VALIDATE, LOGIN_VALUE_VALIDATE)
.addParameter(LOGIN_PARAM_CHARSET, LOGIN_VALUE_CHARSET).build();
try {
ListenableFuture<Response> fResponse = getClient().executeRequest(request);
Response response = getRequestTimeout() >= 0L ?
fResponse.get(getRequestTimeout(), TimeUnit.MILLISECONDS) : fResponse.get();
if (response.getStatusCode() == 200) {
this.setCookies(response.getCookies());
return true;
} else if (response.getStatusCode() == 405) {
// fallback to legacy in case of 405 response
return loginLegacy(username, password);
}
} catch (Exception e) {
throw new IOException("Failed to login with provided credentials");
}
return false;
}
示例10: sendRequest
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
private LoadBalancerUpdateHolder sendRequest(LoadBalancerRequestId loadBalancerRequestId, Request request, BaragonRequestState onFailure) {
try {
LOG.trace("Sending LB {} request for {} to {}", request.getMethod(), loadBalancerRequestId, request.getUrl());
ListenableFuture<Response> future = httpClient.executeRequest(request);
Response response = future.get(loadBalancerTimeoutMillis, TimeUnit.MILLISECONDS);
LOG.trace("LB {} request {} returned with code {}", request.getMethod(), loadBalancerRequestId, response.getStatusCode());
if (response.getStatusCode() == 504) {
return new LoadBalancerUpdateHolder(BaragonRequestState.UNKNOWN, Optional.of(String.format("LB %s request %s timed out", request.getMethod(), loadBalancerRequestId)));
} else if (!JavaUtils.isHttpSuccess(response.getStatusCode())) {
return new LoadBalancerUpdateHolder(onFailure, Optional.of(String.format("Response status code %s", response.getStatusCode())));
}
BaragonResponse lbResponse = readResponse(response);
return new LoadBalancerUpdateHolder(lbResponse.getLoadBalancerState(), lbResponse.getMessage());
} catch (TimeoutException te) {
LOG.trace("LB {} request {} timed out after waiting {}", request.getMethod(), loadBalancerRequestId, JavaUtils.durationFromMillis(loadBalancerTimeoutMillis));
return new LoadBalancerUpdateHolder(BaragonRequestState.UNKNOWN, Optional.of(String.format("Timed out after %s", JavaUtils.durationFromMillis(loadBalancerTimeoutMillis))));
} catch (Throwable t) {
LOG.error("LB {} request {} to {} threw error", request.getMethod(), loadBalancerRequestId, request.getUrl(), t);
return new LoadBalancerUpdateHolder(BaragonRequestState.UNKNOWN, Optional.of(String.format("Exception %s - %s", t.getClass().getSimpleName(), t.getMessage())));
}
}
示例11: setMockClientReturnStatusCode
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
private void setMockClientReturnStatusCode(int [] returnStatusCodes) throws Exception {
List<ListenableFuture> futures = new ArrayList<>();
for (int returnStatusCode: returnStatusCodes) {
com.ning.http.client.Response response = mock(com.ning.http.client.Response.class);
when(response.getStatusCode()).thenReturn(returnStatusCode);
ListenableFuture future = mock(ListenableFuture.class);
when(future.get()).thenReturn(response);
futures.add(future);
}
when(mockClient.executeRequest(request.getNingRequest()))
.thenAnswer(AdditionalAnswers.returnsElementsOf(futures));
}
示例12: setUp
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
@BeforeMethod
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
mockResponse = mock(com.ning.http.client.Response.class);
mockFuture = mock(ListenableFuture.class);
mockClient = mock(AsyncHttpClient.class);
}
示例13: testJobCreation_ShouldRunJobsAsPerSchedule
import com.ning.http.client.ListenableFuture; //导入依赖的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");
}
示例14: testOneTimeJobCreation_ShouldRunJobAsPerSchedule
import com.ning.http.client.ListenableFuture; //导入依赖的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
}
示例15: AsyncHttpUrlConnection
import com.ning.http.client.ListenableFuture; //导入依赖的package包/类
public AsyncHttpUrlConnection(HttpURLConnection urlConnection, Request request, AsyncHandler<T> asyncHandler, ListenableFuture<T> future) {
this.urlConnection = urlConnection;
this.request = request;
this.asyncHandler = asyncHandler;
this.future = future;
this.request = request;
}