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:io.spring.initializr.web.test.MockMvcClientHttpRequestFactory.java

@Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
    return new MockClientHttpRequest(httpMethod, uri) {
        @Override/*from w ww .j a v  a2  s.  c  om*/
        public ClientHttpResponse executeInternal() throws IOException {
            try {
                MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
                requestBuilder.content(getBodyAsBytes());
                requestBuilder.headers(getHeaders());
                MockHttpServletResponse servletResponse = actions(requestBuilder).andReturn().getResponse();
                HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
                if (status.value() >= 400) {
                    requestBuilder = request(HttpMethod.GET, "/error")
                            .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, status.value())
                            .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, uri.toString());
                    if (servletResponse.getErrorMessage() != null) {
                        requestBuilder.requestAttr(RequestDispatcher.ERROR_MESSAGE,
                                servletResponse.getErrorMessage());
                    }
                    // Overwrites the snippets from the first request
                    servletResponse = actions(requestBuilder).andReturn().getResponse();
                }
                byte[] body = servletResponse.getContentAsByteArray();
                HttpHeaders headers = getResponseHeaders(servletResponse);
                MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
                clientResponse.getHeaders().putAll(headers);
                return clientResponse;
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }

    };
}

From source file:org.devefx.httpmapper.http.ResponseEntity.java

/**
 * Return the HTTP status code of the response.
 * @return the HTTP status as an HttpStatus enum entry
 *///  ww w. j ava  2 s .c o m
public HttpStatus getStatusCode() {
    if (this.statusCode instanceof HttpStatus) {
        return (HttpStatus) this.statusCode;
    } else {
        return HttpStatus.valueOf((Integer) this.statusCode);
    }
}

From source file:com.example.spring.controller.AppErrorController.java

private HttpStatus getStatus(HttpServletRequest request) {
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    if (statusCode != null) {
        try {//from w w  w.j  av  a2 s . c o m
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
        }
    }
    return HttpStatus.INTERNAL_SERVER_ERROR;
}

From source file:com.monarchapis.driver.spring.rest.ApiErrorResponseEntityExceptionHandler.java

@ExceptionHandler(ApiErrorException.class)
public ResponseEntity<ApiError> handleApiErrorException(HttpServletRequest req, ApiErrorException ex) {
    ApiError error = ex.getError();//from w  w  w . jav a  2  s.  c o  m
    HttpStatus status = HttpStatus.valueOf(error.getStatus());

    return new ResponseEntity<ApiError>(setErrorHolder(error), status);
}

From source file:it.tidalwave.northernwind.frontend.springmvc.SpringMvcResponseBuilder.java

@Override
@Nonnull
protected ResponseEntity<?> doBuild() {
    return new ResponseEntity<>(body, headers, HttpStatus.valueOf(httpStatus));
}

From source file:com.monarchapis.driver.spring.rest.ApiErrorResponseEntityExceptionHandler.java

@ExceptionHandler(com.monarchapis.api.exception.ApiErrorException.class)
public ResponseEntity<ApiError> handleApiErrorException(HttpServletRequest req,
        com.monarchapis.api.exception.ApiErrorException ex) {
    com.monarchapis.api.exception.ApiError error = ex.getError();
    HttpStatus status = HttpStatus.valueOf(error.getCode());

    ApiError e = new ApiError(error.getCode(), error.getReason(), error.getMessage(),
            error.getDeveloperMessage(), error.getErrorCode(), error.getMoreInfo());

    return new ResponseEntity<ApiError>(setErrorHolder(e), status);
}

From source file:de.whs.poodle.PoodleErrorAttributes.java

@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = new HashMap<>();

    Throwable error = getError(requestAttributes);

    String message = null;//w  ww  .j av a  2 s  .co m

    if (error != null) {
        /* RepositoryExceptions contain messageCodes for localization.
         * If the error was a RepositoryException, create the corresponding
         * text with the messageSource. We use this a lot with
         * BadRequestException to localize responses to the client. */
        if (error instanceof RepositoryException) {
            RepositoryException daoExc = (RepositoryException) error;
            if (daoExc.getMessageCode() != null) {
                Locale locale = LocaleContextHolder.getLocale();
                message = messageSource.getMessage(daoExc.getMessageCode(), daoExc.getMessageCodeArgs(),
                        locale);
            }
        }

        // show a more specific error on database connection failures
        if (error instanceof CannotGetJdbcConnectionException)
            message = "error connecting to database (" + error.getMessage() + ")";

        log.error("Error", error);
    }

    int status = (int) requestAttributes.getAttribute(RequestDispatcher.ERROR_STATUS_CODE,
            RequestAttributes.SCOPE_REQUEST);

    if (message == null)
        message = HttpStatus.valueOf(status).getReasonPhrase();

    errorAttributes.put("status", status);
    errorAttributes.put("message", message);

    return errorAttributes;
}

From source file:org.ng200.openolympus.controller.OlympusErrorController.java

@Override
public Map<String, Object> extract(final RequestAttributes attributes, final boolean b1, final boolean b2) {
    final Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {/* w  w w.  j a  va 2  s  .c om*/
        Throwable error = (Throwable) attributes.getAttribute("javax.servlet.error.exception",
                RequestAttributes.SCOPE_REQUEST);
        final Object obj = attributes.getAttribute("javax.servlet.error.status_code",
                RequestAttributes.SCOPE_REQUEST);
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
        } else {
        }
        map.put("status", status);
        map.put("statusPhrase", HttpStatus.valueOf(status).getReasonPhrase());
        final List<Throwable> exceptions = new ArrayList<Throwable>();
        while (error != null) {
            exceptions.add(error);
            error = error.getCause();
        }
        map.put("exceptions", exceptions);
        return map;
    } catch (final Exception ex) {
        map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        map.put("statusPhrase", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        map.put("exceptions", Lists.from(ex));
        return map;
    }
}

From source file:org.cloudfoundry.client.lib.oauth2.OauthClient.java

private OAuth2AccessToken createToken(String username, String password, String clientId, String clientSecret) {
    OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
    AccessTokenRequest request = createAccessTokenRequest(username, password);

    ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
    try {/*from  w w  w  .j av a2 s  . c  o  m*/
        return provider.obtainAccessToken(resource, request);
    } catch (OAuth2AccessDeniedException oauthEx) {
        HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
        CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage());
        cfEx.setDescription(oauthEx.getSummary());
        throw cfEx;
    }
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java

@RequestMapping("/accessToken")
public HttpEntity<String> token(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {

    try {//w w w.j  ava2  s  . com
        // OAuth
        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);

        // ??id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            return buildInvalidClientIdResponse();

        }

        // KEY?
        if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
            return buildInvalidClientSecretResponse();
        }

        String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
        // ??AUTHORIZATION_CODEPASSWORDREFRESH_TOKEN
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            if (!oAuthService.checkAuthCode(authCode)) {
                return buildBadAuthCodeResponse();
            }
            // TODO ??
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            if (!checkUserPassword(oauthRequest.getUsername(), oauthRequest.getPassword())) {
                return buildInvalidUserPassResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
            // https://github.com/zhouyongtao/homeinns-web
            if (!oAuthService.checkAuthCode(authCode)) {
                return buildInvalidRefreshTokenResponse();
            }
        }

        // ?Access Token
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        final String accessToken = oauthIssuerImpl.accessToken();
        oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
        final String refreshToken = oauthIssuerImpl.refreshToken();
        oAuthService.addAccessToken(refreshToken, oAuthService.getUsernameByAuthCode(authCode));

        // ?OAuth?
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken).setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
                .setTokenType(TokenType.BEARER.toString()).setRefreshToken(refreshToken).buildJSONMessage();

        // ?OAuthResponse?ResponseEntity
        return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));

    } catch (OAuthProblemException e) {
        // ?
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return new ResponseEntity<String>(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
    }
}