Search in sources :

Example 1 with MethodNotAllowedException

use of org.springframework.web.server.MethodNotAllowedException in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMapping method handleNoMatch.

/**
	 * Iterate all RequestMappingInfos once again, look if any match by URL at
	 * least and raise exceptions accordingly.
	 * @throws MethodNotAllowedException for matches by URL but not by HTTP method
	 * @throws UnsupportedMediaTypeStatusException if there are matches by URL
	 * and HTTP method but not by consumable media types
	 * @throws NotAcceptableStatusException if there are matches by URL and HTTP
	 * method but not by producible media types
	 * @throws ServerWebInputException if there are matches by URL and HTTP
	 * method but not by query parameter conditions
	 */
@Override
protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos, String lookupPath, ServerWebExchange exchange) throws Exception {
    PartialMatchHelper helper = new PartialMatchHelper(infos, exchange);
    if (helper.isEmpty()) {
        return null;
    }
    ServerHttpRequest request = exchange.getRequest();
    if (helper.hasMethodsMismatch()) {
        HttpMethod httpMethod = request.getMethod();
        Set<String> methods = helper.getAllowedMethods();
        if (HttpMethod.OPTIONS.matches(httpMethod.name())) {
            HttpOptionsHandler handler = new HttpOptionsHandler(methods);
            return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
        }
        throw new MethodNotAllowedException(httpMethod.name(), methods);
    }
    if (helper.hasConsumesMismatch()) {
        Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
        MediaType contentType;
        try {
            contentType = request.getHeaders().getContentType();
        } catch (InvalidMediaTypeException ex) {
            throw new UnsupportedMediaTypeStatusException(ex.getMessage());
        }
        throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes));
    }
    if (helper.hasProducesMismatch()) {
        Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
        throw new NotAcceptableStatusException(new ArrayList<>(mediaTypes));
    }
    if (helper.hasParamsMismatch()) {
        throw new ServerWebInputException("Unsatisfied query parameter conditions: " + helper.getParamConditions() + ", actual parameters: " + request.getQueryParams());
    }
    return null;
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ServerWebInputException(org.springframework.web.server.ServerWebInputException) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 2 with MethodNotAllowedException

use of org.springframework.web.server.MethodNotAllowedException in project spring-framework by spring-projects.

the class HandshakeWebSocketService method handleRequest.

@Override
public Mono<Void> handleRequest(ServerWebExchange exchange, WebSocketHandler handler) {
    ServerHttpRequest request = exchange.getRequest();
    HttpMethod method = request.getMethod();
    HttpHeaders headers = request.getHeaders();
    if (logger.isDebugEnabled()) {
        logger.debug("Handling " + request.getURI() + " with headers: " + headers);
    }
    if (HttpMethod.GET != method) {
        return Mono.error(new MethodNotAllowedException(method.name(), Collections.singleton("GET")));
    }
    if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
        return handleBadRequest("Invalid 'Upgrade' header: " + headers);
    }
    List<String> connectionValue = headers.getConnection();
    if (!connectionValue.contains("Upgrade") && !connectionValue.contains("upgrade")) {
        return handleBadRequest("Invalid 'Connection' header: " + headers);
    }
    String key = headers.getFirst(SEC_WEBSOCKET_KEY);
    if (key == null) {
        return handleBadRequest("Missing \"Sec-WebSocket-Key\" header");
    }
    Optional<String> protocol = selectProtocol(headers, handler);
    return this.upgradeStrategy.upgrade(exchange, handler, protocol);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HttpMethod(org.springframework.http.HttpMethod)

Example 3 with MethodNotAllowedException

use of org.springframework.web.server.MethodNotAllowedException in project spring-framework by spring-projects.

the class ResourceWebHandler method handle.

/**
	 * Processes a resource request.
	 * <p>Checks for the existence of the requested resource in the configured list of locations.
	 * If the resource does not exist, a {@code 404} response will be returned to the client.
	 * If the resource exists, the request will be checked for the presence of the
	 * {@code Last-Modified} header, and its value will be compared against the last-modified
	 * timestamp of the given resource, returning a {@code 304} status code if the
	 * {@code Last-Modified} value  is greater. If the resource is newer than the
	 * {@code Last-Modified} value, or the header is not present, the content resource
	 * of the resource will be written to the response with caching headers
	 * set to expire one year in the future.
	 */
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
    return getResource(exchange).otherwiseIfEmpty(Mono.defer(() -> {
        logger.trace("No matching resource found - returning 404");
        exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
        return Mono.empty();
    })).then(resource -> {
        try {
            if (HttpMethod.OPTIONS.equals(exchange.getRequest().getMethod())) {
                exchange.getResponse().getHeaders().add("Allow", "GET,HEAD,OPTIONS");
                return Mono.empty();
            }
            String httpMehtod = exchange.getRequest().getMethod().name();
            if (!SUPPORTED_METHODS.contains(httpMehtod)) {
                return Mono.error(new MethodNotAllowedException(httpMehtod, SUPPORTED_METHODS));
            }
            if (exchange.checkNotModified(Instant.ofEpochMilli(resource.lastModified()))) {
                logger.trace("Resource not modified - returning 304");
                return Mono.empty();
            }
            if (getCacheControl() != null) {
                String value = getCacheControl().getHeaderValue();
                if (value != null) {
                    exchange.getResponse().getHeaders().setCacheControl(value);
                }
            }
            MediaType mediaType = getMediaType(exchange, resource);
            if (mediaType != null) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Determined media type '" + mediaType + "' for " + resource);
                }
            } else {
                if (logger.isTraceEnabled()) {
                    logger.trace("No media type found " + "for " + resource + " - not sending a content-type header");
                }
            }
            if (HttpMethod.HEAD.equals(exchange.getRequest().getMethod())) {
                setHeaders(exchange, resource, mediaType);
                exchange.getResponse().getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
                logger.trace("HEAD request - skipping content");
                return Mono.empty();
            }
            setHeaders(exchange, resource, mediaType);
            return this.resourceHttpMessageWriter.write(Mono.just(resource), null, ResolvableType.forClass(Resource.class), mediaType, exchange.getRequest(), exchange.getResponse(), Collections.emptyMap());
        } catch (IOException ex) {
            return Mono.error(ex);
        }
    });
}
Also used : MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) Resource(org.springframework.core.io.Resource) MediaType(org.springframework.http.MediaType) IOException(java.io.IOException)

Aggregations

MethodNotAllowedException (org.springframework.web.server.MethodNotAllowedException)3 HttpMethod (org.springframework.http.HttpMethod)2 MediaType (org.springframework.http.MediaType)2 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)2 IOException (java.io.IOException)1 Resource (org.springframework.core.io.Resource)1 HttpHeaders (org.springframework.http.HttpHeaders)1 InvalidMediaTypeException (org.springframework.http.InvalidMediaTypeException)1 HandlerMethod (org.springframework.web.method.HandlerMethod)1 NotAcceptableStatusException (org.springframework.web.server.NotAcceptableStatusException)1 ServerWebInputException (org.springframework.web.server.ServerWebInputException)1 UnsupportedMediaTypeStatusException (org.springframework.web.server.UnsupportedMediaTypeStatusException)1