Example usage for org.springframework.http.client ClientHttpResponse getRawStatusCode

List of usage examples for org.springframework.http.client ClientHttpResponse getRawStatusCode

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpResponse getRawStatusCode.

Prototype

int getRawStatusCode() throws IOException;

Source Link

Document

Return the HTTP status code (potentially non-standard and not resolvable through the HttpStatus enum) as an integer.

Usage

From source file:io.github.microcks.util.test.HttpTestRunner.java

/**
 * This is a hook for allowing sub-classes to redefine the extraction of success or failure message.
 * This implementation just extract raw http code.
 * @param service The service under test
 * @param operation The tested operation
 * @param request The tested reference request
 * @param httpResponse The received response from endpoint
 * @return The test result message. // w  w w  .  j  a va  2  s .com
 */
protected String extractTestReturnMessage(Service service, Operation operation, Request request,
        ClientHttpResponse httpResponse) {
    String message = null;
    // Set code to failure if http code out of correct ranges (20x and 30x).
    try {
        message = String.valueOf(httpResponse.getRawStatusCode());
    } catch (IOException ioe) {
        log.debug("IOException while getting raw status code in response", ioe);
        message = "IOException while getting raw status code in response";
    }
    return message;
}

From source file:io.github.microcks.util.test.HttpTestRunner.java

/**
 * This is a hook for allowing sub-classes to redefine the criteria for
 * telling a response is a success or a failure. This implementation check raw http code
 * (success if in 20x range, failure if not).
 * @param service The service under test
 * @param operation The tested operation
 * @param request The tested reference request
 * @param httpResponse The received response from endpoint
 * @param responseContent The response body content if any (may be null)
 * @return The test result code, wether TestReturn.SUCCESS_CODE or TestReturn.FAILURE_CODE 
 *//*from  w ww. j a  va  2s . c  o  m*/
protected int extractTestReturnCode(Service service, Operation operation, Request request,
        ClientHttpResponse httpResponse, String responseContent) {
    int code = TestReturn.SUCCESS_CODE;
    // Set code to failure if http code out of correct ranges (20x and 30x).
    try {
        if (httpResponse.getRawStatusCode() > 299) {
            log.debug("Http status code is " + httpResponse.getRawStatusCode() + ", marking test as failed.");
            code = TestReturn.FAILURE_CODE;
        }
    } catch (IOException ioe) {
        log.debug("IOException while getting raw status code in response", ioe);
        code = TestReturn.FAILURE_CODE;
    }
    return code;
}

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

/**
 * Creates a mock implementation of {@link ClientHttpResponse} and configures it to return supplied data.
 * <p>/*from ww  w .  j a v a 2  s  .  co m*/
 * ClientHttpResponse needs mocking for test fixtures which rely on setting response headers as for some reason Spring
 * 4.0's MockClientHttpResponse doesn't support setting response headers.
 * 
 * @param httpStatus The {@link HttpStatus} which the mock should be configured to return for invocations of
 * {@link ClientHttpResponse#getStatusCode()}.
 * @param headers The {@link HttpHeaders} which the mock should be configured to return for invocations of
 * {@link ClientHttpResponse#getHeaders()}.
 * @param body A string representation of the data which the mock should be configured to return for invocations of
 * {@link ClientHttpResponse#getBody()}.
 * @return The created {@link ClientHttpResponse}.
 */
private ClientHttpResponse createMockClientHttpResponse(HttpStatus httpStatus, HttpHeaders headers,
        final String body) {
    ClientHttpResponse mockClientHttpResponse = EasyMock.createNiceMock(ClientHttpResponse.class);
    try {
        EasyMock.expect(mockClientHttpResponse.getStatusCode()).andReturn(httpStatus).anyTimes();
        EasyMock.expect(mockClientHttpResponse.getRawStatusCode()).andReturn(httpStatus.value()).anyTimes();
        EasyMock.expect(mockClientHttpResponse.getHeaders()).andReturn(headers).anyTimes();
        // Return a new InputStream for each call to ClientHttpResponse.getBody() rather than an exhausted one  
        IAnswer<InputStream> iAnswer = new IAnswer<InputStream>() {
            public InputStream answer() {
                return body != null ? new ByteArrayInputStream(body.getBytes()) : null;
            }
        };
        EasyMock.expect(mockClientHttpResponse.getBody()).andAnswer(iAnswer).anyTimes();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return mockClientHttpResponse;
}

From source file:org.bremersee.common.web.client.ResponseErrorHandlerImpl.java

@Override
public void handleError(final ClientHttpResponse response) throws IOException {

    final Throwable t = findThrowable(response);

    if (t instanceof RuntimeException) {
        throw (RuntimeException) t;
    } else {//from   ww w .  j  ava  2s. c  om
        HttpErrorException e = new HttpErrorException(t.getMessage(), t.getCause());
        e.setHttpStatusCode(response.getRawStatusCode());
        throw e;
    }
}

From source file:org.bremersee.common.web.client.ResponseErrorHandlerImpl.java

@Override
public boolean hasError(final ClientHttpResponse response) throws IOException {
    boolean hasError;
    try {/*  w w w.  j  a v  a  2 s .c om*/
        HttpStatus statusCode = response.getStatusCode();
        hasError = statusCode.series() == HttpStatus.Series.CLIENT_ERROR
                || statusCode.series() == HttpStatus.Series.SERVER_ERROR;

    } catch (Throwable t) { // NOSONAR
        hasError = response.getRawStatusCode() >= 400;
    }
    if (log.isTraceEnabled()) {
        log.trace("Response is error? " + hasError);
    }
    return hasError;
}

From source file:com.pepaproch.gtswsdl.LoginRequestInterceptor.java

private ClientHttpResponse logResponse(ClientHttpResponse response) throws IOException {

    ClientHttpResponse result = new ClientHttpResponse() {

        InputStream in;//from   w  ww.ja v a2s .c om
        InputStream oldIn = response.getBody();
        String jsonResponse;

        @Override
        public HttpStatus getStatusCode() throws IOException {
            return response.getStatusCode();
        }

        @Override
        public int getRawStatusCode() throws IOException {
            return response.getRawStatusCode();
        }

        @Override
        public String getStatusText() throws IOException {
            return response.getStatusText();
        }

        @Override
        public void close() {
            try {
                Logger.getLogger(LoginRequestInterceptor.class).log(Level.DEBUG, jsonResponse);
                in.close();
                oldIn.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(LoginRequestInterceptor.class.getName())
                        .log(java.util.logging.Level.SEVERE, null, ex);
            }
        }

        @Override
        public InputStream getBody() throws IOException {
            if (in == null) {
                try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                    byte[] readBuffer = new byte[4 * 1024];
                    int lenght;
                    while ((lenght = oldIn.read(readBuffer)) != -1) {
                        baos.write(readBuffer, 0, lenght);
                    }
                    baos.flush();
                    jsonResponse = baos.toString();
                    in = new ByteArrayInputStream(baos.toByteArray());
                }

            }
            return in;
        }

        @Override
        public HttpHeaders getHeaders() {
            return response.getHeaders();
        }
    };

    return result;
}

From source file:com.sitewhere.rest.service.SiteWhereErrorHandler.java

public void handleError(ClientHttpResponse response) throws IOException {
    String errorCode = null;/*from w w w. j  a v a  2  s  . c  om*/
    List<String> codeList = response.getHeaders().get(ISiteWhereWebConstants.HEADER_SITEWHERE_ERROR_CODE);
    if ((codeList != null) && (codeList.size() > 0)) {
        errorCode = codeList.get(0);
    }
    try {
        errorHandler.handleError(response);
    } catch (RestClientException e) {
        if (errorCode != null) {
            ErrorCode code = ErrorCode.valueOf(errorCode);
            throw new SiteWhereSystemException(code, ErrorLevel.ERROR, response.getRawStatusCode());
        } else {
            throw new SiteWhereSystemException(ErrorCode.Unknown, ErrorLevel.ERROR,
                    response.getRawStatusCode());
        }
    }
}

From source file:org.fao.geonet.util.XslUtil.java

/**
 * Returns the HTTP code  or error message if error occurs during URL connection.
 *
 * @param url       The URL to ckeck./*w w w  .j  a  v  a2s . co  m*/
 * @param tryNumber the number of remaining tries.
 */
public static String getUrlStatus(String url, int tryNumber) {
    if (tryNumber < 1) {
        // protect against redirect loops
        return "ERR_TOO_MANY_REDIRECTS";
    }
    HttpHead head = new HttpHead(url);
    GeonetHttpRequestFactory requestFactory = ApplicationContextHolder.get()
            .getBean(GeonetHttpRequestFactory.class);
    ClientHttpResponse response = null;
    try {
        response = requestFactory.execute(head, new Function<HttpClientBuilder, Void>() {
            @Nullable
            @Override
            public Void apply(@Nullable HttpClientBuilder originalConfig) {
                RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout(1000)
                        .setConnectionRequestTimeout(3000).setSocketTimeout(5000);
                RequestConfig requestConfig = config.build();
                originalConfig.setDefaultRequestConfig(requestConfig);

                return null;
            }
        });
        //response = requestFactory.execute(head);
        if (response.getRawStatusCode() == HttpStatus.SC_BAD_REQUEST
                || response.getRawStatusCode() == HttpStatus.SC_METHOD_NOT_ALLOWED
                || response.getRawStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            // the website doesn't support HEAD requests. Need to do a GET...
            response.close();
            HttpGet get = new HttpGet(url);
            response = requestFactory.execute(get);
        }

        if (response.getStatusCode().is3xxRedirection() && response.getHeaders().containsKey("Location")) {
            // follow the redirects
            return getUrlStatus(response.getHeaders().getFirst("Location"), tryNumber - 1);
        }

        return String.valueOf(response.getRawStatusCode());
    } catch (IOException e) {
        Log.error(Geonet.GEONETWORK, "IOException validating  " + url + " URL. " + e.getMessage(), e);
        return e.getMessage();
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

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

/**
 * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response is returned by the API
 * service and contains an API error entity.
 * //w  ww  . ja  v a2 s .c  o  m
 * @throws Exception If an unexpected error occurs.
 */
@Test
public void testHandleErrorWhenResponseBodyContainsApiError() throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_XML);
    String apiErrorCode = "InvalidChannelId";
    String apiErrorMessage = "Invalid channel id [foo].";
    String apiErrorXml = "<?xml version='1.0' encoding='UTF-8'?><error><code>" + apiErrorCode
            + "</code><message>" + apiErrorMessage + "</message></error>";
    ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.BAD_REQUEST, httpHeaders,
            apiErrorXml);
    EasyMock.replay(response);

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