Example usage for org.springframework.http HttpStatus BAD_GATEWAY

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

Introduction

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

Prototype

HttpStatus BAD_GATEWAY

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

Click Source Link

Document

502 Bad Gateway .

Usage

From source file:org.openwms.core.http.AbstractWebController.java

/**
 * All general exceptions thrown by services are caught here and translated into http conform responses with a status code {@code 500
 * Internal Server Error}./* w  ww . j a  v a 2s .  c om*/
 *
 * @param ex The exception occurred
 * @return A response object wraps the server result
 */
@ExceptionHandler(Exception.class)
public ResponseEntity<Response<Serializable>> handleException(Exception ex) {
    EXC_LOGGER.error("[P] Presentation Layer Exception: " + ex.getLocalizedMessage(), ex);
    if (ex instanceof BehaviorAwareException) {
        BehaviorAwareException bae = (BehaviorAwareException) ex;
        return bae.toResponse(bae.getData());
    }
    if (ex instanceof BusinessRuntimeException) {
        BusinessRuntimeException bre = (BusinessRuntimeException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), bre.getMsgKey(),
                HttpStatus.INTERNAL_SERVER_ERROR.toString(), new String[] { bre.getMsgKey() }),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
    if (ex instanceof HttpBusinessException) {
        HttpBusinessException e = (HttpBusinessException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), e.getHttpStatus().toString()),
                e.getHttpStatus());
    }
    if (ex instanceof ValidationException) {
        return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.BAD_REQUEST.toString()),
                HttpStatus.BAD_REQUEST);
    }
    if (ex instanceof TechnicalRuntimeException) {
        TechnicalRuntimeException be = (TechnicalRuntimeException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.BAD_GATEWAY.toString()),
                HttpStatus.BAD_GATEWAY);
    }
    return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.toString()),
            HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.FilesDownloaderTest.java

@Test
public void download_serverResponseErrorOtherThan401And404_excpetionWithProperMessageThrown()
        throws IOException {
    // given/*from   ww  w .ja  v a 2s  . c  o  m*/
    FilesDownloader downloader = new FilesDownloader(testCredentials, restTemplateMock);
    HttpStatus expectedErrorStatus = HttpStatus.BAD_GATEWAY;
    String expectedExceptionMessage = "Server response status: " + expectedErrorStatus;

    // when
    when(restTemplateMock.exchange(testCredentials.getHost() + testResource, HttpMethod.GET,
            HttpCommunication.basicAuthRequest(testCredentials.getBasicAuthToken()), byte[].class))
                    .thenThrow(new HttpClientErrorException(expectedErrorStatus));

    // then
    thrown.expect(IOException.class);
    thrown.expectMessage(expectedExceptionMessage);
    downloader.download(testResource, testPath);
}

From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java

@SuppressWarnings("deprecation")
private RestTemplate setErrorHandler(final RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        private final Set<HttpStatus> errorStatuses = new HashSet<>();

        /* non-static */ {
            errorStatuses.add(HttpStatus.BAD_REQUEST);
            errorStatuses.add(HttpStatus.UNAUTHORIZED);
            errorStatuses.add(HttpStatus.FORBIDDEN);
            errorStatuses.add(HttpStatus.NOT_FOUND);
            errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED);
            errorStatuses.add(HttpStatus.NOT_ACCEPTABLE);
            errorStatuses.add(HttpStatus.REQUEST_TIMEOUT);
            errorStatuses.add(HttpStatus.CONFLICT);
            errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
            errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG);
            errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS);
            errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR);
            errorStatuses.add(HttpStatus.NOT_IMPLEMENTED);
            errorStatuses.add(HttpStatus.BAD_GATEWAY);
            errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE);
        }/*from w  ww.  j  a  v a  2s. c  om*/

        @Override
        public boolean hasError(final ClientHttpResponse response) throws IOException {
            return errorStatuses.contains(response.getStatusCode());
        }

        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText());
            System.err.println(readBody(response));
        }

        private String readBody(final ClientHttpResponse response) throws IOException {
            BufferedReader responseBodyReader = null;

            try {
                responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody()));

                StringBuilder buffer = new StringBuilder();
                String line;

                while ((line = responseBodyReader.readLine()) != null) {
                    buffer.append(line).append(System.getProperty("line.separator"));
                }

                return buffer.toString().trim();
            } finally {
                FileSystemUtils.close(responseBodyReader);
            }
        }
    });

    return restTemplate;
}

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

/**
 * <pre>/*from  www  .j av a 2s  . c o  m*/
 * 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:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationWithRealCfClientTest.java

protected void createService(CloudService cloudService) {
    try {//from   ww w.j  a  va2  s  .c  o m
        logger.info("Creating service {} from {} with plan {} ", cloudService.getName(),
                cloudService.getLabel(), cloudService.getPlan());
        cfClientToPopulate.createService(cloudService);
        if (!this.isFinishedCreatingService(cloudService)) {
            fail("Cannot create service '" + cloudService.getName() + "'");
        }
    } catch (HttpServerErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.BAD_GATEWAY)) {
            throw e;
        } else {
            String skipMessage = "Bad gateway error, skipping test";
            this.reportIntegration.setSkipped(true);
            this.reportIntegration.setSkippedReason(skipMessage);
            assumeTrue(skipMessage, false);
        }
    }

}

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  a  v a  2  s  .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.springframework.social.twitter.api.impl.TwitterErrorHandler.java

private void handleServerErrors(HttpStatus statusCode) throws IOException {
    if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("twitter",
                "Something is broken at Twitter. Please see http://dev.twitter.com/pages/support to report the issue.");
    } else if (statusCode == HttpStatus.BAD_GATEWAY) {
        throw new ServerDownException("twitter", "Twitter is down or is being upgraded.");
    } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerOverloadedException("twitter", "Twitter is overloaded with requests. Try again later.");
    }//from   ww  w.  ja  v a  2s.  c o  m
}

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 w w  .ja v  a  2s.c om
                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  av  a 2  s  .  co  m
                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()));
    }
}