Search in sources :

Example 46 with HttpStatus

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

the class AbstractMessageWriterResultHandler method writeBody.

/**
 * Write a given body to the response with {@link HttpMessageWriter}.
 * @param body the object to write
 * @param bodyParameter the {@link MethodParameter} of the body to write
 * @param actualParam the actual return type of the method that returned the value;
 * could be different from {@code bodyParameter} when processing {@code HttpEntity}
 * for example
 * @param exchange the current exchange
 * @return indicates completion or error
 * @since 5.0.2
 */
@SuppressWarnings({ "unchecked", "rawtypes", "ConstantConditions" })
protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParameter, @Nullable MethodParameter actualParam, ServerWebExchange exchange) {
    ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
    ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve(), body);
    Publisher<?> publisher;
    ResolvableType elementType;
    ResolvableType actualElementType;
    if (adapter != null) {
        publisher = adapter.toPublisher(body);
        boolean isUnwrapped = KotlinDetector.isSuspendingFunction(bodyParameter.getMethod()) && !COROUTINES_FLOW_CLASS_NAME.equals(bodyType.toClass().getName());
        ResolvableType genericType = isUnwrapped ? bodyType : bodyType.getGeneric();
        elementType = getElementType(adapter, genericType);
        actualElementType = elementType;
    } else {
        publisher = Mono.justOrEmpty(body);
        actualElementType = body != null ? ResolvableType.forInstance(body) : bodyType;
        elementType = (bodyType.toClass() == Object.class && body != null ? actualElementType : bodyType);
    }
    if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
        return Mono.from((Publisher<Void>) publisher);
    }
    MediaType bestMediaType;
    try {
        bestMediaType = selectMediaType(exchange, () -> getMediaTypesFor(elementType));
    } catch (NotAcceptableStatusException ex) {
        HttpStatus statusCode = exchange.getResponse().getStatusCode();
        if (statusCode != null && statusCode.isError()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Ignoring error response content (if any). " + ex.getReason());
            }
            return Mono.empty();
        }
        throw ex;
    }
    if (bestMediaType != null) {
        String logPrefix = exchange.getLogPrefix();
        if (logger.isDebugEnabled()) {
            logger.debug(logPrefix + (publisher instanceof Mono ? "0..1" : "0..N") + " [" + elementType + "]");
        }
        for (HttpMessageWriter<?> writer : getMessageWriters()) {
            if (writer.canWrite(actualElementType, bestMediaType)) {
                return writer.write((Publisher) publisher, actualType, elementType, bestMediaType, exchange.getRequest(), exchange.getResponse(), Hints.from(Hints.LOG_PREFIX_HINT, logPrefix));
            }
        }
    }
    MediaType contentType = exchange.getResponse().getHeaders().getContentType();
    boolean isPresentMediaType = (contentType != null && contentType.equals(bestMediaType));
    Set<MediaType> producibleTypes = exchange.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (isPresentMediaType || !CollectionUtils.isEmpty(producibleTypes)) {
        return Mono.error(new HttpMessageNotWritableException("No Encoder for [" + elementType + "] with preset Content-Type '" + contentType + "'"));
    }
    List<MediaType> mediaTypes = getMediaTypesFor(elementType);
    if (bestMediaType == null && mediaTypes.isEmpty()) {
        return Mono.error(new IllegalStateException("No HttpMessageWriter for " + elementType));
    }
    return Mono.error(new NotAcceptableStatusException(mediaTypes));
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) HttpStatus(org.springframework.http.HttpStatus) Mono(reactor.core.publisher.Mono) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 47 with HttpStatus

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

the class DefaultServerWebExchange method checkNotModified.

@Override
public boolean checkNotModified(@Nullable String etag, Instant lastModified) {
    HttpStatus status = getResponse().getStatusCode();
    if (this.notModified || (status != null && !HttpStatus.OK.equals(status))) {
        return this.notModified;
    }
    if (validateIfUnmodifiedSince(lastModified)) {
        if (this.notModified) {
            getResponse().setStatusCode(HttpStatus.PRECONDITION_FAILED);
        }
        return this.notModified;
    }
    boolean validated = validateIfNoneMatch(etag);
    if (!validated) {
        validateIfModifiedSince(lastModified);
    }
    // Update response
    boolean isHttpGetOrHead = SAFE_METHODS.contains(getRequest().getMethod());
    if (this.notModified) {
        getResponse().setStatusCode(isHttpGetOrHead ? HttpStatus.NOT_MODIFIED : HttpStatus.PRECONDITION_FAILED);
    }
    if (isHttpGetOrHead) {
        if (lastModified.isAfter(Instant.EPOCH) && getResponseHeaders().getLastModified() == -1) {
            getResponseHeaders().setLastModified(lastModified.toEpochMilli());
        }
        if (StringUtils.hasLength(etag) && getResponseHeaders().getETag() == null) {
            getResponseHeaders().setETag(padEtagIfNecessary(etag));
        }
    }
    return this.notModified;
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 48 with HttpStatus

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

the class DefaultClientResponseTests method statusCode.

@Test
public void statusCode() {
    HttpStatus status = HttpStatus.CONTINUE;
    given(mockResponse.getStatusCode()).willReturn(status);
    assertThat(defaultClientResponse.statusCode()).isEqualTo(status);
}
Also used : HttpStatus(org.springframework.http.HttpStatus) Test(org.junit.jupiter.api.Test)

Example 49 with HttpStatus

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

the class ServletInvocableHandlerMethod method setResponseStatus.

/**
 * Set the response status according to the {@link ResponseStatus} annotation.
 */
private void setResponseStatus(ServletWebRequest webRequest) throws IOException {
    HttpStatus status = getResponseStatus();
    if (status == null) {
        return;
    }
    HttpServletResponse response = webRequest.getResponse();
    if (response != null) {
        String reason = getResponseStatusReason();
        if (StringUtils.hasText(reason)) {
            response.sendError(status.value(), reason);
        } else {
            response.setStatus(status.value());
        }
    }
    // To be picked up by RedirectView
    webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, status);
}
Also used : HttpStatus(org.springframework.http.HttpStatus) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Example 50 with HttpStatus

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

the class UndertowXhrTransport method executeRequest.

protected ResponseEntity<String> executeRequest(URI url, HttpString method, HttpHeaders headers, @Nullable String body) {
    CountDownLatch latch = new CountDownLatch(1);
    List<ClientResponse> responses = new CopyOnWriteArrayList<>();
    try {
        ClientConnection connection = this.httpClient.connect(url, this.worker, this.bufferPool, this.optionMap).get();
        try {
            ClientRequest request = new ClientRequest().setMethod(method).setPath(url.getPath());
            request.getRequestHeaders().add(HttpString.tryFromString(HttpHeaders.HOST), url.getHost());
            if (StringUtils.hasLength(body)) {
                HttpString headerName = HttpString.tryFromString(HttpHeaders.CONTENT_LENGTH);
                request.getRequestHeaders().add(headerName, body.length());
            }
            addHttpHeaders(request, headers);
            connection.sendRequest(request, createRequestCallback(body, responses, latch));
            latch.await();
            ClientResponse response = responses.iterator().next();
            HttpStatus status = HttpStatus.valueOf(response.getResponseCode());
            HttpHeaders responseHeaders = toHttpHeaders(response.getResponseHeaders());
            String responseBody = response.getAttachment(RESPONSE_BODY);
            return (responseBody != null ? new ResponseEntity<>(responseBody, responseHeaders, status) : new ResponseEntity<>(responseHeaders, status));
        } finally {
            IoUtils.safeClose(connection);
        }
    } catch (IOException ex) {
        throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new SockJsTransportFailureException("Interrupted while processing request to " + url, ex);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) HttpHeaders(org.springframework.http.HttpHeaders) HttpStatus(org.springframework.http.HttpStatus) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) SockJsTransportFailureException(org.springframework.web.socket.sockjs.SockJsTransportFailureException) ResponseEntity(org.springframework.http.ResponseEntity) ClientConnection(io.undertow.client.ClientConnection) ClientRequest(io.undertow.client.ClientRequest) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpString(io.undertow.util.HttpString)

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