Search in sources :

Example 66 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-framework by spring-projects.

the class StatusAssertions method assertStatusAndReturn.

private WebTestClient.ResponseSpec assertStatusAndReturn(HttpStatus expected) {
    HttpStatus actual = this.exchangeResult.getStatus();
    this.exchangeResult.assertWithDiagnostics(() -> AssertionErrors.assertEquals("Status", expected, actual));
    return this.responseSpec;
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 67 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-framework by spring-projects.

the class StatusResultMatchers method getHttpStatusSeries.

private HttpStatus.Series getHttpStatusSeries(MvcResult result) {
    int statusValue = result.getResponse().getStatus();
    HttpStatus status = HttpStatus.valueOf(statusValue);
    return status.series();
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 68 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-framework by spring-projects.

the class StatusResultMatchersTests method testHttpStatusCodeResultMatchers.

@Test
public void testHttpStatusCodeResultMatchers() throws Exception {
    List<AssertionError> failures = new ArrayList<>();
    for (HttpStatus status : HttpStatus.values()) {
        MockHttpServletResponse response = new MockHttpServletResponse();
        response.setStatus(status.value());
        MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response);
        try {
            Method method = getMethodForHttpStatus(status);
            ResultMatcher matcher = (ResultMatcher) ReflectionUtils.invokeMethod(method, this.matchers);
            try {
                matcher.match(mvcResult);
            } catch (AssertionError error) {
                failures.add(error);
            }
        } catch (Exception ex) {
            throw new Exception("Failed to obtain ResultMatcher for status " + status, ex);
        }
    }
    if (!failures.isEmpty()) {
        fail("Failed status codes: " + failures);
    }
}
Also used : StubMvcResult(org.springframework.test.web.servlet.StubMvcResult) HttpStatus(org.springframework.http.HttpStatus) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) StubMvcResult(org.springframework.test.web.servlet.StubMvcResult) MvcResult(org.springframework.test.web.servlet.MvcResult) ResultMatcher(org.springframework.test.web.servlet.ResultMatcher) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 69 with HttpStatus

use of org.springframework.http.HttpStatus in project cas by apereo.

the class OidcLogoutEndpointController method handleRequestInternal.

/**
 * Handle request.
 *
 * @param postLogoutRedirectUrl the post logout redirect url
 * @param state                 the state
 * @param idToken               the id token
 * @param request               the request
 * @param response              the response
 * @return the response entity
 * @throws Exception the exception
 */
@GetMapping(value = { '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.LOGOUT_URL, '/' + OidcConstants.BASE_OIDC_URL + "/logout", "/**/" + OidcConstants.LOGOUT_URL })
public ResponseEntity<HttpStatus> handleRequestInternal(@RequestParam(value = "post_logout_redirect_uri", required = false) final String postLogoutRedirectUrl, @RequestParam(value = "state", required = false) final String state, @RequestParam(value = "id_token_hint", required = false) final String idToken, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    val webContext = new JEEContext(request, response);
    if (!getConfigurationContext().getOidcRequestSupport().isValidIssuerForEndpoint(webContext, OidcConstants.LOGOUT_URL)) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    String clientId = null;
    if (StringUtils.isNotBlank(idToken)) {
        LOGGER.trace("Decoding logout id token [{}]", idToken);
        val configContext = getConfigurationContext();
        val claims = configContext.getIdTokenSigningAndEncryptionService().decode(idToken, Optional.empty());
        clientId = claims.getStringClaimValue(OAuth20Constants.CLIENT_ID);
        LOGGER.debug("Client id retrieved from id token is [{}]", clientId);
        val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(configContext.getServicesManager(), clientId);
        LOGGER.debug("Located registered service [{}]", registeredService);
        val service = configContext.getWebApplicationServiceServiceFactory().createService(clientId);
        val audit = AuditableContext.builder().service(service).registeredService(registeredService).build();
        val accessResult = configContext.getRegisteredServiceAccessStrategyEnforcer().execute(audit);
        accessResult.throwExceptionIfNeeded();
        WebUtils.putRegisteredService(request, Objects.requireNonNull(registeredService));
        val urls = configContext.getSingleLogoutServiceLogoutUrlBuilder().determineLogoutUrl(registeredService, service, Optional.of(request)).stream().map(SingleLogoutUrl::getUrl).collect(Collectors.toList());
        LOGGER.debug("Logout urls assigned to registered service are [{}]", urls);
        if (StringUtils.isNotBlank(postLogoutRedirectUrl) && registeredService.getMatchingStrategy() != null) {
            val matchResult = registeredService.matches(postLogoutRedirectUrl) || urls.stream().anyMatch(url -> postLogoutRedirectUrlMatcher.matches(postLogoutRedirectUrl, url));
            if (matchResult) {
                LOGGER.debug("Requested logout URL [{}] is authorized for redirects", postLogoutRedirectUrl);
                return new ResponseEntity<>(executeLogoutRedirect(Optional.ofNullable(StringUtils.trimToNull(state)), Optional.of(postLogoutRedirectUrl), Optional.of(clientId), request, response));
            }
        }
        val validURL = urls.stream().filter(urlValidator::isValid).findFirst();
        if (validURL.isPresent()) {
            return new ResponseEntity<>(executeLogoutRedirect(Optional.ofNullable(StringUtils.trimToNull(state)), validURL, Optional.of(clientId), request, response));
        }
        LOGGER.debug("No logout urls could be determined for registered service [{}]", registeredService.getName());
    }
    return new ResponseEntity<>(executeLogoutRedirect(Optional.ofNullable(StringUtils.trimToNull(state)), Optional.empty(), Optional.ofNullable(clientId), request, response));
}
Also used : lombok.val(lombok.val) CasProtocolConstants(org.apereo.cas.CasProtocolConstants) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) RequestParam(org.springframework.web.bind.annotation.RequestParam) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) AuditableContext(org.apereo.cas.audit.AuditableContext) OidcConstants(org.apereo.cas.oidc.OidcConstants) SingleLogoutUrl(org.apereo.cas.logout.slo.SingleLogoutUrl) UrlValidator(org.apereo.cas.web.UrlValidator) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) OidcConfigurationContext(org.apereo.cas.oidc.OidcConfigurationContext) Objects(java.util.Objects) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseOidcController(org.apereo.cas.oidc.web.controllers.BaseOidcController) GetMapping(org.springframework.web.bind.annotation.GetMapping) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) WebUtils(org.apereo.cas.web.support.WebUtils) JEEContext(org.pac4j.core.context.JEEContext) ResponseEntity(org.springframework.http.ResponseEntity) JEEContext(org.pac4j.core.context.JEEContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 70 with HttpStatus

use of org.springframework.http.HttpStatus in project new-cloud by xie-summer.

the class RedisRateLimitZuulFilter method run.

@Override
public Object run() {
    try {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        if (!redisTemplate.hasKey(TIME_KEY)) {
            redisTemplate.opsForValue().set(TIME_KEY, 0, 1, TimeUnit.SECONDS);
        }
        if (redisTemplate.hasKey(TIME_KEY) && redisTemplate.opsForValue().increment(COUNTER_KEY, 1) > 400) {
            HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;
            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setStatus(httpStatus.value());
            response.getWriter().append(httpStatus.getReasonPhrase());
            currentContext.setSendZuulResponse(false);
            throw new RateLimiterException(httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase());
        }
    } catch (Throwable e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
Also used : HttpStatus(org.springframework.http.HttpStatus) HttpServletResponse(javax.servlet.http.HttpServletResponse) RateLimiterException(com.cloud.common.exception.RateLimiterException) RequestContext(com.netflix.zuul.context.RequestContext)

Aggregations

HttpStatus (org.springframework.http.HttpStatus)165 ResponseEntity (org.springframework.http.ResponseEntity)43 HttpHeaders (org.springframework.http.HttpHeaders)38 Test (org.junit.jupiter.api.Test)26 MediaType (org.springframework.http.MediaType)17 Mono (reactor.core.publisher.Mono)17 IOException (java.io.IOException)16 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)15 Collections (java.util.Collections)13 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)13 URI (java.net.URI)12 List (java.util.List)11 Optional (java.util.Optional)11 Test (org.junit.Test)11 Map (java.util.Map)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 Resource (org.springframework.core.io.Resource)9 HashMap (java.util.HashMap)8