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


Java Response类代码示例

本文整理汇总了Java中com.ning.http.client.Response的典型用法代码示例。如果您正苦于以下问题:Java Response类的具体用法?Java Response怎么用?Java Response使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Response类属于com.ning.http.client包,在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testJobSidelining_ShouldSidelineJobsAfter404s

import com.ning.http.client.Response; //导入依赖的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: browse

import com.ning.http.client.Response; //导入依赖的package包/类
public Collection<MesosFileObject> browse(String slaveHostname, String fullPath) throws SlaveNotFoundException {
  try {
    Response response = asyncHttpClient.prepareGet(String.format("http://%s:5051/files/browse.json", slaveHostname))
        .addQueryParameter("path", fullPath)
        .execute().get();

    if (response.getStatusCode() == 404) {
      return Collections.emptyList();
    }

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

    return objectMapper.readValue(response.getResponseBodyAsStream(), MESOS_FILE_OBJECTS);
  } catch (ConnectException ce) {
    throw new SlaveNotFoundException(ce);
  } catch (Exception e) {
    if (e.getCause().getClass() == ConnectException.class) {
      throw new SlaveNotFoundException(e);
    } else {
      throw Throwables.propagate(e);
    }
  }
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:26,代码来源:SandboxManager.java

示例3: testAutoRetryForHttpStatus500

import com.ning.http.client.Response; //导入依赖的package包/类
@Test
public void testAutoRetryForHttpStatus500() throws Exception {
    request = new ParsecAsyncHttpRequest.Builder()
        .addRetryStatusCode(500)
        .build();
    setMockClientReturnStatusCode(500);

    ParsecHttpRequestRetryCallable<Response> parsecHttpRequestRetryCallable =
        new ParsecHttpRequestRetryCallable<>(mockClient, request);
    Response response = parsecHttpRequestRetryCallable.call();
    List<Response> responses = parsecHttpRequestRetryCallable.getResponses();

    // Default max retries is 3
    assertEquals(responses.size(), 4);
    assertEquals(response.getStatusCode(), 500);
}
 
开发者ID:yahoo,项目名称:parsec-libraries,代码行数:17,代码来源:ParsecHttpRequestRetryCallableTest.java

示例4: testCustomMaxRetries

import com.ning.http.client.Response; //导入依赖的package包/类
@Test
public void testCustomMaxRetries() throws Exception {
    request = new ParsecAsyncHttpRequest.Builder()
        .addRetryStatusCode(500)
        .setMaxRetries(1)
        .build();
    setMockClientReturnStatusCode(500);

    ParsecHttpRequestRetryCallable<Response> parsecHttpRequestRetryCallable =
        new ParsecHttpRequestRetryCallable<>(mockClient, request);
    Response response = parsecHttpRequestRetryCallable.call();
    List<Response> responses = parsecHttpRequestRetryCallable.getResponses();

    assertEquals(responses.size(), 2);
    assertEquals(response.getStatusCode(), 500);
}
 
开发者ID:yahoo,项目名称:parsec-libraries,代码行数:17,代码来源:ParsecHttpRequestRetryCallableTest.java

示例5: testRetryAndSuccessBeforeReachMaxRetries

import com.ning.http.client.Response; //导入依赖的package包/类
@Test
public void testRetryAndSuccessBeforeReachMaxRetries() throws Exception {
    request = new ParsecAsyncHttpRequest.Builder()
        .addRetryStatusCode(408)
        .setMaxRetries(3)
        .build();
    int [] returnStatusCodes = {408, 408, 200};
    setMockClientReturnStatusCode(returnStatusCodes);

    ParsecHttpRequestRetryCallable<Response> parsecHttpRequestRetryCallable =
        new ParsecHttpRequestRetryCallable<>(mockClient, request);
    Response response = parsecHttpRequestRetryCallable.call();
    List<Response> responses = parsecHttpRequestRetryCallable.getResponses();

    assertEquals(responses.size(), 3);
    assertEquals(responses.get(0).getStatusCode(), 408);
    assertEquals(responses.get(1).getStatusCode(), 408);
    assertEquals(responses.get(2).getStatusCode(), 200);
    assertEquals(response.getStatusCode(), 200);
}
 
开发者ID:yahoo,项目名称:parsec-libraries,代码行数:21,代码来源:ParsecHttpRequestRetryCallableTest.java

示例6: getCircuitBreaker

import com.ning.http.client.Response; //导入依赖的package包/类
protected Optional<CircuitBreaker<Response>> getCircuitBreaker(RequestBuilderWrapper requestBuilderWrapper) {
    if (requestBuilderWrapper.disableCircuitBreaker)
        return Optional.empty();

    // Circuit breaking is enabled for this call. So we return the custom one specified or use the default one if a
    //      custom one is not specified.
    if (requestBuilderWrapper.customCircuitBreaker.isPresent())
        return requestBuilderWrapper.customCircuitBreaker;

    // No custom circuit breaker. Use the default for the given request's host.
    Uri uri = Uri.create(requestBuilderWrapper.url);
    String host = uri.getHost();
    EventLoop nettyEventLoop = requestBuilderWrapper.getCtx() == null
                               ? null
                               : requestBuilderWrapper.getCtx().channel().eventLoop();
    CircuitBreaker<Integer> defaultStatusCodeCircuitBreaker = getDefaultHttpStatusCodeCircuitBreakerForKey(
        host, Optional.ofNullable(nettyEventLoop), Optional.ofNullable(nettyEventLoop)
    );
    return Optional.of(
        new CircuitBreakerDelegate<>(
            defaultStatusCodeCircuitBreaker, response -> (response == null ? null : response.getStatusCode())
        )
    );
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:25,代码来源:AsyncHttpClientHelper.java

示例7: getAwsInstanceId

import com.ning.http.client.Response; //导入依赖的package包/类
/**
 * @param asyncHttpClientHelper The async HTTP client you want this method to use to make the AWS metadata call.
 *
 * @return A {@link CompletableFuture} that will contain the AWS instance ID this app is running on (assuming it
 * completes successfully). If an error occurs retrieving the instance ID from AWS then the error will be logged and
 * {@link AppInfo#UNKNOWN_VALUE} returned as the value.
 */
public static CompletableFuture<String> getAwsInstanceId(AsyncHttpClientHelper asyncHttpClientHelper) {
    return asyncHttpClientHelper.executeAsyncHttpRequest(
        asyncHttpClientHelper.getRequestBuilder(AMAZON_METADATA_INSTANCE_ID_URL, HttpMethod.GET),
        Response::getResponseBody
    ).handle((instanceId, error) -> {
        if (error != null) {
            logger.error("Unable to get instance ID info from AWS metadata service.", error);
            return AppInfo.UNKNOWN_VALUE;
        }

        if (instanceId == null) {
            logger.error("AWS metadata service returned null for instance ID. Using 'unknown' as fallback.");
            return AppInfo.UNKNOWN_VALUE;
        }

        return instanceId;
    });
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:26,代码来源:AwsUtil.java

示例8: beforeMethod

import com.ning.http.client.Response; //导入依赖的package包/类
@Before
public void beforeMethod() throws Throwable {
    resetTracingAndMdc();

    completableFutureResponse = new CompletableFuture<>();
    responseHandlerFunctionMock = mock(AsyncResponseHandler.class);
    downstreamMethod = "method-" + UUID.randomUUID().toString();
    downstreamUrl = "url-" + UUID.randomUUID().toString();
    circuitBreakerManualTaskMock = mock(ManualModeTask.class);

    responseMock = mock(Response.class);
    responseHandlerResult = "result-" + UUID.randomUUID().toString();
    doReturn(responseHandlerResult).when(responseHandlerFunctionMock).handleResponse(responseMock);

    Tracer.getInstance().startRequestWithRootSpan("overallReqSpan");
    initialSpanStack = Tracer.getInstance().getCurrentSpanStackCopy();
    initialMdcInfo = MDC.getCopyOfContextMap();

    handlerSpy = spy(new AsyncCompletionHandlerWithTracingAndMdcSupport<>(
        completableFutureResponse, responseHandlerFunctionMock, true, downstreamMethod, downstreamUrl,
        Optional.of(circuitBreakerManualTaskMock), initialSpanStack, initialMdcInfo
    ));

    resetTracingAndMdc();
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:26,代码来源:AsyncCompletionHandlerWithTracingAndMdcSupportTest.java

示例9: mock

import com.ning.http.client.Response; //导入依赖的package包/类
@Test
public void onCompleted_handles_circuit_breaker_but_does_nothing_else_if_completableFutureResponse_is_already_completed()
    throws Throwable {
    // given
    CompletableFuture<String> cfMock = mock(CompletableFuture.class);
    Whitebox.setInternalState(handlerSpy, "completableFutureResponse", cfMock);
    doReturn(true).when(cfMock).isDone();

    // when
    Response ignoredResult = handlerSpy.onCompleted(responseMock);

    // then
    verify(circuitBreakerManualTaskMock).handleEvent(responseMock);

    verify(cfMock).isDone();
    verifyNoMoreInteractions(cfMock);

    assertThat(ignoredResult).isEqualTo(responseMock);
    verifyZeroInteractions(responseMock);
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:21,代码来源:AsyncCompletionHandlerWithTracingAndMdcSupportTest.java

示例10: get_set_CustomCircuitBreaker_works_as_expected

import com.ning.http.client.Response; //导入依赖的package包/类
@Test
public void get_set_CustomCircuitBreaker_works_as_expected() {
    // given
    requestBuilderWrapper = new RequestBuilderWrapper(
            url,
            httpMethod,
            requestBuilder,
            customCircuitBreaker,
            disableCircuitBreaker);

    Optional<CircuitBreaker<Response>> alteredCircuitBreaker = Optional.of(new CircuitBreakerImpl<>());

    // when
    requestBuilderWrapper.setCustomCircuitBreaker(alteredCircuitBreaker);

    // then
    assertThat(requestBuilderWrapper.getCustomCircuitBreaker()).isEqualTo(alteredCircuitBreaker);
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:19,代码来源:RequestBuilderWrapperTest.java

示例11: main

import com.ning.http.client.Response; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
	initHttpClientPool();
	for (int i = 0; i < 100; i++) {
		try {
			String url = "https://log.rfxlab.com/ping";
			AsyncHttpClient ramdomAsyncHttpClient = getRamdomAsyncHttpClient();
			String ua = ramdomAsyncHttpClient.getConfig().getUserAgent();
			
			Future<Response> f = ramdomAsyncHttpClient.prepareGet(url).execute();
			Response r = f.get();
			System.out.println(ua + " => " +r.getResponseBody());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	System.out.println("done");
	shutdownAllHttpClientPools();
}
 
开发者ID:rfxlab,项目名称:vidsell-data-simulator,代码行数:20,代码来源:BotHttpClientUtil.java

示例12: sendHelper

import com.ning.http.client.Response; //导入依赖的package包/类
private void sendHelper(Set<OpenTsdbMetric> metrics) {
    if (!metrics.isEmpty()) {
        try {
            requestBuilder
                    .setBody(mapper.writeValueAsString(metrics))
                    .execute(new AsyncCompletionHandler<Void>() {
                        @Override
                        public Void onCompleted(Response response) throws Exception {
                            if (response.getStatusCode() != 204) {
                                logger.error("send to opentsdb endpoint failed: ("
                                        + response.getStatusCode() + ") "
                                        + response.getResponseBody());
                            }
                            return null;
                        }
                    });
        } catch (Throwable ex) {
            logger.error("send to opentsdb endpoint failed", ex);
        }
    }
}
 
开发者ID:jetlore,项目名称:spark-opentsdb-sink,代码行数:22,代码来源:OpenTsdb.java

示例13: testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule

import com.ning.http.client.Response; //导入依赖的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

示例14: get

import com.ning.http.client.Response; //导入依赖的package包/类
@Override
public <T> T get(String url, final Class<T> objectClass, String... params) {
    Future<T> f;
    try {
        f = asyncHttpClient.prepareGet(expandUrl(url, params)).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return mapper.readValue(response.getResponseBody(), objectClass);
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
开发者ID:eamonfoy,项目名称:trello-to-markdown,代码行数:23,代码来源:AsyncTrelloHttpClient.java

示例15: postForObject

import com.ning.http.client.Response; //导入依赖的package包/类
@Override
public <T> T postForObject(String url, T object, final Class<T> objectClass, String... params) {
    Future<T> f;
    try {
        byte[] body = this.mapper.writeValueAsBytes(object);
        f = asyncHttpClient.preparePost(expandUrl(url, params)).setBody(body).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return mapper.readValue(response.getResponseBody(), objectClass);
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
开发者ID:eamonfoy,项目名称:trello-to-markdown,代码行数:24,代码来源:AsyncTrelloHttpClient.java


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