Example usage for org.springframework.http HttpStatus GATEWAY_TIMEOUT

List of usage examples for org.springframework.http HttpStatus GATEWAY_TIMEOUT

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus GATEWAY_TIMEOUT.

Prototype

HttpStatus GATEWAY_TIMEOUT

To view the source code for org.springframework.http HttpStatus GATEWAY_TIMEOUT.

Click Source Link

Document

504 Gateway Timeout .

Usage

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java

/**
 * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body is in an unsupported
 * media type, e.g. an HTML error page returned by an intermediate web proxy.
 * //from   w w w  .  java  2  s.  com
 * @throws Exception If an unexpected error occurs.
 */
@Test
public void testHandleErrorWhenResponseBodyInUnsupportedMediaType() throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.TEXT_HTML);
    String body = "<html><head>Error</head><body>Woz error</body>";
    ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders,
            body);
    EasyMock.replay(response);

    try {
        this.errorHandler.handleError(response);
        fail("Expected exception to be thrown for error response.");
    } catch (ApiErrorResponseException e) {
        ApiError apiError = null;
        ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(),
                null, httpHeaders, null, body.getBytes(), apiError);
        assertApiErrorResponseException(expectedException, e);
    }
}

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java

/**
 * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body contains an 
 * unexpected entity in a supported media type.
 * //w ww . ja v a2 s. c o  m
 * @throws Exception If an unexpected error occurs.
 */
@Test
public void testHandleErrorWhenResponseBodyContainsUnexpectedEntity() throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_XML);
    String body = "<?xml version='1.0' encoding='UTF-8'?><notAnApiError><foo>1</foo></notAnApiError>";
    ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders,
            body);
    EasyMock.replay(response);

    try {
        this.errorHandler.handleError(response);
        fail("Expected exception to be thrown for error response.");
    } catch (ApiErrorResponseException e) {
        ApiError apiError = null;
        ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(),
                null, httpHeaders, null, body.getBytes(), apiError);
        assertApiErrorResponseException(expectedException, e);
    }
}

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java

/**
 * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body is empty, e.g. because
 * it is returned by an intermediate web proxy.
 * /* w  ww. j a v  a2 s .com*/
 * @throws Exception If an unexpected error occurs.
 */
@Test
public void testHandleErrorWhenResponseBodyEmpty() throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentLength(0);
    String body = null;
    ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders,
            body);
    EasyMock.replay(response);

    try {
        this.errorHandler.handleError(response);
        fail("Expected exception to be thrown for error response.");
    } catch (ApiErrorResponseException e) {
        ApiError apiError = null;
        ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(),
                null, httpHeaders, null, new byte[0], apiError);
        assertApiErrorResponseException(expectedException, e);
    }
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>/*from  w  w w . ja  va2  s.com*/
 * RHEV Manager  API   .
 * </pre>
 * @param api RHEV Manager API (/api, /api/vms )
 * @param body xml contents
 * @param clazz ? Target Object Class
 * @return
 * @throws RestClientException
 * @throws Exception
 */
public synchronized <T> T submit(String api, HttpMethod method, Object body, String rootElementName,
        Class<T> clazz) throws RestClientException, Exception {
    Assert.isTrue(StringUtils.isNotEmpty(api), "api must not be null");
    Assert.notNull(clazz, "clazz must not be null.");

    // Multi RHEV Manager        ? ?? HostnameVerifier ??,
    // ??    ? ?.(java.io.IOException: HTTPS hostname wrong:  should be <{host}>)
    //init();

    try {
        RestTemplate rt = new RestTemplate();

        ResponseEntity<?> response = rt.exchange(new URI(getUrl(api)), method,
                setHTTPEntity(body, rootElementName), clazz);

        logger.debug("[Request URL] : {}", getUrl(api));
        logger.debug("[Response] : {}", response);

        if (response.getStatusCode().equals(HttpStatus.BAD_REQUEST)
                || response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || response.getStatusCode().equals(HttpStatus.PAYMENT_REQUIRED)
                || response.getStatusCode().equals(HttpStatus.FORBIDDEN)
                || response.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED)
                || response.getStatusCode().equals(HttpStatus.NOT_ACCEPTABLE)
                || response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)
                || response.getStatusCode().equals(HttpStatus.NOT_IMPLEMENTED)
                || response.getStatusCode().equals(HttpStatus.BAD_GATEWAY)
                || response.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE)
                || response.getStatusCode().equals(HttpStatus.GATEWAY_TIMEOUT)) {
            throw new Exception(response.getStatusCode().value() + " " + response.getStatusCode().toString());
        }

        return clazz.cast(response.getBody());
    } catch (RestClientException e) {
        logger.error("RestClientException has occurred.", e);
        throw e;
    } catch (Exception e) {
        logger.error("Unhandled Exception has occurred.", e);
        throw e;
    }
}

From source file:org.apache.fineract.restwebservice.PlatformRestClient.java

/**
  * Executes a HTTP request using the spring framework RestTemplate
  * //from  ww  w .j  a  va  2s. c  o m
  * @param url the URL
  * @param method the HTTP method (GET, POST, etc)
  * @param requestEntity the entity (headers and/or body) to write to the request, may be null
  * @param responseType the type of the return value
  * @return the response as entity
  * @throws InterruptedException
  * @throws RestClientException
  */
public <T> ResponseEntity<T> executeHttpRequest(final URI url, final HttpMethod method,
        final HttpEntity<?> requestEntity, final Class<T> responseType) {
    final RestTemplate restTemplate = new RestTemplate();

    HttpStatus statusCode = null;
    ResponseEntity<T> responseEntity = null;

    // increment the number of request attempts by 1
    this.numberOfHttpRequestAttempts++;

    try {
        // execute the HTTP request
        responseEntity = restTemplate.exchange(url, method, requestEntity, responseType);
        statusCode = responseEntity.getStatusCode();

        // catch all server HTTP error exceptions
    } catch (HttpServerErrorException exception) {
        statusCode = exception.getStatusCode();

        // if HTTP status is 503 or 504, sleep for 5 seconds and retry
        if ((statusCode.equals(HttpStatus.SERVICE_UNAVAILABLE) || statusCode.equals(HttpStatus.GATEWAY_TIMEOUT))
                && (this.numberOfHttpRequestAttempts < this.numberOfHttpRequestRetries)) {

            logger.info("Server returned an error response with status: " + statusCode
                    + ", retrying again in 5 seconds");
            logger.info("Number of attempts: " + this.numberOfHttpRequestAttempts);

            try {
                // sleep for 5 seconds and try again
                Thread.sleep(5000);

            } catch (InterruptedException interruptedException) {
                logger.error(interruptedException.getMessage(), interruptedException);
            }

            // execute HTTP request again
            this.executeHttpRequest(url, method, requestEntity, responseType);

        } else {
            // in other cases, throw back the exception
            throw exception;
        }
    }

    return responseEntity;
}

From source file:org.springframework.cloud.dataflow.shell.command.HttpCommands.java

private RestTemplate createRestTemplate(final StringBuilder buffer) {
    RestTemplate restTemplate = new RestTemplate();

    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        @Override//w  w w .j ava 2s .  c  o  m
        public boolean hasError(ClientHttpResponse response) throws IOException {
            HttpStatus status = response.getStatusCode();
            return (status == HttpStatus.BAD_GATEWAY || status == HttpStatus.GATEWAY_TIMEOUT
                    || status == HttpStatus.INTERNAL_SERVER_ERROR);
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            outputError(response.getStatusCode(), buffer);
        }
    });

    return restTemplate;
}

From source file:org.venice.beachfront.bfapi.services.OAuthServiceTests.java

@Test
public void testRequestAccessTokenServerError() {
    String mockAuthCode = "mock-auth-code-123";

    Mockito.when(this.restTemplate.exchange(Mockito.eq(this.oauthTokenUrl), Mockito.eq(HttpMethod.POST),
            Mockito.any(), Mockito.eq(AccessTokenResponseBody.class)))
            .then(new Answer<ResponseEntity<AccessTokenResponseBody>>() {
                @Override/*from   w ww  .  jav a  2s .  com*/
                public ResponseEntity<AccessTokenResponseBody> answer(InvocationOnMock invocation) {
                    throw new HttpServerErrorException(HttpStatus.GATEWAY_TIMEOUT);
                }
            });

    try {
        oauthService.requestAccessToken(mockAuthCode);
        fail("request should not have succeeded");
    } catch (UserException ex) {
        assertEquals(HttpStatus.BAD_GATEWAY, ex.getRecommendedStatusCode());
        assertTrue(ex.getMessage().contains("" + HttpStatus.GATEWAY_TIMEOUT.value()));
    }
}

From source file:org.venice.beachfront.bfapi.services.OAuthServiceTests.java

@Test
public void testRequestOAuthProfileServerError() {
    String mockAccessToken = "mock-access-token-321";

    Mockito.when(this.restTemplate.exchange(Mockito.eq(this.oauthProfileUrl), Mockito.eq(HttpMethod.GET),
            Mockito.any(), Mockito.eq(String.class))).then(new Answer<ResponseEntity<String>>() {
                @Override/*from   w  ww  .j a  va 2 s.  c  om*/
                public ResponseEntity<String> answer(InvocationOnMock invocation) {
                    throw new HttpServerErrorException(HttpStatus.GATEWAY_TIMEOUT);
                }
            });

    try {
        oauthService.requestOAuthProfile(mockAccessToken);
        fail("request should not have succeeded");
    } catch (UserException ex) {
        assertEquals(HttpStatus.BAD_GATEWAY, ex.getRecommendedStatusCode());
        assertTrue(ex.getMessage().contains("" + HttpStatus.GATEWAY_TIMEOUT.value()));
    }
}