Example usage for org.springframework.http HttpStatus valueOf

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

Introduction

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

Prototype

public static HttpStatus valueOf(int statusCode) 

Source Link

Document

Return the enum constant of this type with the specified numeric value.

Usage

From source file:org.springframework.boot.autoconfigure.web.BasicErrorController.java

private HttpStatus getStatus(Integer value) {
    try {//from w w w .  j av  a 2  s.co  m
        return HttpStatus.valueOf(value);
    } catch (Exception ex) {
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

From source file:org.springframework.boot.autoconfigure.web.BasicErrorController.java

@Override
public Map<String, Object> extract(RequestAttributes attributes, boolean trace, boolean log) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {//from   www .j  a  v a  2 s  .c  o m
        Throwable error = (Throwable) attributes.getAttribute(ErrorController.class.getName(),
                RequestAttributes.SCOPE_REQUEST);
        Object obj = attributes.getAttribute("javax.servlet.error.status_code",
                RequestAttributes.SCOPE_REQUEST);
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
            map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
        } else {
            map.put(ERROR_KEY, "None");
        }
        map.put("status", status);
        if (error == null) {
            error = (Throwable) attributes.getAttribute("javax.servlet.error.exception",
                    RequestAttributes.SCOPE_REQUEST);
        }
        if (error != null) {
            while (error instanceof ServletException && error.getCause() != null) {
                error = ((ServletException) error).getCause();
            }
            map.put("exception", error.getClass().getName());
            addMessage(map, error);
            if (trace) {
                StringWriter stackTrace = new StringWriter();
                error.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                map.put("trace", stackTrace.toString());
            }
            if (log) {
                this.logger.error(error);
            }
        } else {
            Object message = attributes.getAttribute("javax.servlet.error.message",
                    RequestAttributes.SCOPE_REQUEST);
            map.put("message", message == null ? "No message available" : message);
        }
        String path = (String) attributes.getAttribute("javax.servlet.error.request_uri",
                RequestAttributes.SCOPE_REQUEST);
        map.put("path", path == null ? "No path available" : path);
        return map;
    } catch (Exception ex) {
        map.put(ERROR_KEY, ex.getClass().getName());
        map.put("message", ex.getMessage());
        if (log) {
            this.logger.error(ex);
        }
        return map;
    }
}

From source file:org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler.java

/**
 * Get the HTTP error status information from the error map.
 * @param errorAttributes the current error information
 * @return the error HTTP status// ww  w .  ja  va 2  s .c o  m
 */
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
    int statusCode = (int) errorAttributes.get("status");
    return HttpStatus.valueOf(statusCode);
}

From source file:org.springframework.boot.ops.web.BasicErrorController.java

@RequestMapping(value = "${error.path:/error}")
@ResponseBody/*from  w  w  w .  j  av  a2 s .c  o m*/
public Map<String, Object> error(HttpServletRequest request) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {
        Throwable error = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Object obj = request.getAttribute("javax.servlet.error.status_code");
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
            map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
        } else {
            map.put(ERROR_KEY, "None");
        }
        map.put("status", status);
        if (error != null) {
            while (error instanceof ServletException) {
                error = ((ServletException) error).getCause();
            }
            map.put("exception", error.getClass().getName());
            map.put("message", error.getMessage());
            String trace = request.getParameter("trace");
            if (trace != null && !"false".equals(trace.toLowerCase())) {
                StringWriter stackTrace = new StringWriter();
                error.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                map.put("trace", stackTrace.toString());
            }
            this.logger.error(error);
        } else {
            Object message = request.getAttribute("javax.servlet.error.message");
            map.put("message", message == null ? "No message available" : message);
        }
        return map;
    } catch (Exception ex) {
        map.put(ERROR_KEY, ex.getClass().getName());
        map.put("message", ex.getMessage());
        this.logger.error(ex);
        return map;
    }
}

From source file:org.springframework.cloud.gateway.support.ServerWebExchangeUtils.java

public static HttpStatus parse(String statusString) {
    HttpStatus httpStatus;/*w  ww .j a  v a2 s .  c  o m*/

    try {
        int status = Integer.parseInt(statusString);
        httpStatus = HttpStatus.valueOf(status);
    } catch (NumberFormatException e) {
        // try the enum string
        httpStatus = HttpStatus.valueOf(statusString.toUpperCase());
    }
    return httpStatus;
}

From source file:org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpResponse.java

@Override
public boolean isSuccess() {
    return HttpStatus.valueOf(this.httpResponse.getStatusLine().getStatusCode()).is2xxSuccessful();
}

From source file:org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator.java

private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("OAuth error.", e);
    }//from   w  ww  .  j a  v a2  s. c  o m

    int status = e.getHttpErrorCode();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    if (status == HttpStatus.UNAUTHORIZED.value()) {
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
    }

    ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(e, headers,
            HttpStatus.valueOf(status));

    return response;

}

From source file:org.springframework.social.exfm.api.impl.ExFmErrorHandler.java

void handleExFmError(HttpStatus statusCode, Status status) {

    String message = status.getStatus_text();

    HttpStatus httpStatus = statusCode != HttpStatus.OK ? statusCode
            : HttpStatus.valueOf(Integer.parseInt(status.getStatus_code()));

    if (httpStatus == HttpStatus.OK) {
        // Should never happen
    } else if (httpStatus == HttpStatus.BAD_REQUEST) {
        throw new ResourceNotFoundException("exfm", message);

    } else if (httpStatus == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("exfm", message);

    } else if (httpStatus == HttpStatus.UNAUTHORIZED) {

        throw new NotAuthorizedException("exfm", message);
    } else if (httpStatus == HttpStatus.FORBIDDEN) {

        throw new OperationNotPermittedException("exfm", message);
    } else if (httpStatus == HttpStatus.INTERNAL_SERVER_ERROR) {
        throw new InternalServerErrorException("exfm", message);
    } else if (httpStatus == HttpStatus.SERVICE_UNAVAILABLE) {
        throw new ServerDownException("exfm", message);
    }//from w  w  w. j a  v  a  2  s  .c o m
}

From source file:org.springframework.social.twitter.api.impl.TwitterErrorHandler.java

private void handleClientErrors(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);

    String errorText = "";
    if (errorMap.containsKey("error")) {
        errorText = (String) errorMap.get("error");
    } else if (errorMap.containsKey("errors")) {
        Object errors = errorMap.get("errors");
        if (errors instanceof List) {
            @SuppressWarnings("unchecked")
            List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
            errorText = errorsList.get(0).get("message");
        } else if (errors instanceof String) {
            errorText = (String) errors;
        }/* ww  w.j  a v  a 2 s  . c o m*/
    }

    if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorText.contains("Rate limit exceeded.")) {
            throw new RateLimitExceededException("twitter");
        }
    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (errorText == null) {
            throw new NotAuthorizedException("twitter", response.getStatusText());
        } else if (errorText.equals("Could not authenticate you.")) {
            throw new MissingAuthorizationException("twitter");
        } else if (errorText.equals("Could not authenticate with OAuth.")) { // revoked token
            throw new RevokedAuthorizationException("twitter");
        } else if (errorText.equals("Invalid / expired Token")) { // Note that Twitter doesn't actually expire tokens
            throw new InvalidAuthorizationException("twitter", errorText);
        } else {
            throw new NotAuthorizedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.FORBIDDEN) {
        if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
            throw new DuplicateStatusException("twitter", errorText);
        } else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
            throw new MessageTooLongException(errorText);
        } else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
            throw new InvalidMessageRecipientException(errorText);
        } else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
            throw new RateLimitExceededException("twitter");
        } else {
            throw new OperationNotPermittedException("twitter", errorText);
        }
    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException("twitter", errorText);
    } else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM)
            || statusCode == HttpStatus.valueOf(TOO_MANY_REQUESTS)) {
        throw new RateLimitExceededException("twitter");
    }

}

From source file:org.springframework.test.web.servlet.htmlunit.MockWebResponseBuilder.java

private String statusMessage(int statusCode) {
    String errorMessage = this.response.getErrorMessage();
    if (StringUtils.hasText(errorMessage)) {
        return errorMessage;
    }/* w  ww .  j a v a 2 s  .c  om*/

    try {
        return HttpStatus.valueOf(statusCode).getReasonPhrase();
    } catch (IllegalArgumentException ex) {
        // ignore
    }

    return DEFAULT_STATUS_MESSAGE;
}