當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。