当前位置: 首页>>代码示例>>Java>>正文


Java ListenableFuture类代码示例

本文整理汇总了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);
}
 
开发者ID:flipkart-incubator,项目名称:simpleJobScheduler,代码行数:24,代码来源:JobControllerIntegrationTest.java

示例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

}
 
开发者ID:flipkart-incubator,项目名称:simpleJobScheduler,代码行数:21,代码来源:JobControllerIntegrationTest.java

示例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));
  }
 
开发者ID:paulwellnerbou,项目名称:chronicreplay,代码行数:24,代码来源:LineReplayer.java

示例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;
	}
 
开发者ID:sumeetchhetri,项目名称:gatf,代码行数:21,代码来源:SingleTestCaseExecutor.java

示例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;
}
 
开发者ID:signal,项目名称:agathon,代码行数:18,代码来源:ZergConnectorImplTest.java

示例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;
}
 
开发者ID:hylje,项目名称:rreader,代码行数:26,代码来源:Post.java

示例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);
    }
}
 
开发者ID:hylje,项目名称:rreader,代码行数:20,代码来源:PostHandler.java

示例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);
    }
}
 
开发者ID:orgsync,项目名称:orgsync-api-java,代码行数:32,代码来源:ApiClientImpl.java

示例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;
}
 
开发者ID:adamcin,项目名称:net.adamcin.granite.client,代码行数:26,代码来源:AsyncPackageManagerClient.java

示例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())));
  }
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:28,代码来源:LoadBalancerClientImpl.java

示例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));
}
 
开发者ID:yahoo,项目名称:parsec-libraries,代码行数:15,代码来源:ParsecHttpRequestRetryCallableTest.java

示例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);
}
 
开发者ID:yahoo,项目名称:parsec-libraries,代码行数:8,代码来源:ParsecHttpRequestRetryCallableTest.java

示例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");
}
 
开发者ID:flipkart-incubator,项目名称:simpleJobScheduler,代码行数:13,代码来源:JobControllerIntegrationTest.java

示例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
}
 
开发者ID:flipkart-incubator,项目名称:simpleJobScheduler,代码行数:13,代码来源:JobControllerIntegrationTest.java

示例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;
}
 
开发者ID:yongbeam,项目名称:Android-kakaologin-gradle-sample,代码行数:8,代码来源:SimpleAsyncHttpProvider.java


注:本文中的com.ning.http.client.ListenableFuture类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。