org.springframework.web.server.MethodNotAllowedException Java Examples

The following examples show how to use org.springframework.web.server.MethodNotAllowedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MethodNotAllowedAdviceTrait.java    From problem-spring-web with MIT License 6 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default Mono<ResponseEntity<Problem>> handleRequestMethodNotSupportedException(
        final MethodNotAllowedException exception,
        final ServerWebExchange request) {

    final Set<HttpMethod> methods = exception.getSupportedMethods();

    if (methods.isEmpty()) {
        return create(Status.METHOD_NOT_ALLOWED, exception, request);
    }

    final HttpHeaders headers = new HttpHeaders();
    headers.setAllow(methods);

    return create(Status.METHOD_NOT_ALLOWED, exception, request, headers);
}
 
Example #2
Source File: HandshakeWebSocketService.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handleRequest(ServerWebExchange exchange, WebSocketHandler handler) {
	ServerHttpRequest request = exchange.getRequest();
	HttpMethod method = request.getMethod();
	HttpHeaders headers = request.getHeaders();

	if (HttpMethod.GET != method) {
		return Mono.error(new MethodNotAllowedException(
				request.getMethodValue(), Collections.singleton(HttpMethod.GET)));
	}

	if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
		return handleBadRequest(exchange, "Invalid 'Upgrade' header: " + headers);
	}

	List<String> connectionValue = headers.getConnection();
	if (!connectionValue.contains("Upgrade") && !connectionValue.contains("upgrade")) {
		return handleBadRequest(exchange, "Invalid 'Connection' header: " + headers);
	}

	String key = headers.getFirst(SEC_WEBSOCKET_KEY);
	if (key == null) {
		return handleBadRequest(exchange, "Missing \"Sec-WebSocket-Key\" header");
	}

	String protocol = selectProtocol(headers, handler);

	return initAttributes(exchange).flatMap(attributes ->
			this.upgradeStrategy.upgrade(exchange, handler, protocol,
					() -> createHandshakeInfo(exchange, request, protocol, attributes))
	);
}
 
Example #3
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getHandlerRequestMethodNotAllowed() {
	ServerWebExchange exchange = MockServerWebExchange.from(post("/bar"));
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, MethodNotAllowedException.class,
			ex -> assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD), ex.getSupportedMethods()));
}
 
Example #4
Source File: HandshakeWebSocketService.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handleRequest(ServerWebExchange exchange, WebSocketHandler handler) {
	ServerHttpRequest request = exchange.getRequest();
	HttpMethod method = request.getMethod();
	HttpHeaders headers = request.getHeaders();

	if (HttpMethod.GET != method) {
		return Mono.error(new MethodNotAllowedException(
				request.getMethodValue(), Collections.singleton(HttpMethod.GET)));
	}

	if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
		return handleBadRequest(exchange, "Invalid 'Upgrade' header: " + headers);
	}

	List<String> connectionValue = headers.getConnection();
	if (!connectionValue.contains("Upgrade") && !connectionValue.contains("upgrade")) {
		return handleBadRequest(exchange, "Invalid 'Connection' header: " + headers);
	}

	String key = headers.getFirst(SEC_WEBSOCKET_KEY);
	if (key == null) {
		return handleBadRequest(exchange, "Missing \"Sec-WebSocket-Key\" header");
	}

	String protocol = selectProtocol(headers, handler);

	return initAttributes(exchange).flatMap(attributes ->
			this.upgradeStrategy.upgrade(exchange, handler, protocol,
					() -> createHandshakeInfo(exchange, request, protocol, attributes))
	);
}
 
Example #5
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getHandlerRequestMethodNotAllowed() {
	ServerWebExchange exchange = MockServerWebExchange.from(post("/bar"));
	Mono<Object> mono = this.handlerMapping.getHandler(exchange);

	assertError(mono, MethodNotAllowedException.class,
			ex -> assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD), ex.getSupportedMethods()));
}
 
Example #6
Source File: MethodNotAllowedAdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void noAllowIfNullAllowed() {
    final MethodNotAllowedAdviceTrait unit = new MethodNotAllowedAdviceTrait() {
    };

    final ResponseEntity<Problem> entity = unit.handleRequestMethodNotSupportedException(
            new MethodNotAllowedException("non allowed", null),
            MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();

    assertThat(entity.getHeaders(), not(hasKey("Allow")));
}
 
Example #7
Source File: MethodNotAllowedAdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void noAllowIfNoneAllowed() {
    final MethodNotAllowedAdviceTrait unit = new MethodNotAllowedAdviceTrait() {
    };
    final ResponseEntity<Problem> entity = unit.handleRequestMethodNotSupportedException(
            new MethodNotAllowedException("non allowed", Collections.emptyList()),
            MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();

    assertThat(entity.getHeaders(), not(hasKey("Allow")));
}
 
Example #8
Source File: ResourceWebHandler.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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)
			.switchIfEmpty(Mono.defer(() -> {
				logger.debug(exchange.getLogPrefix() + "Resource not found");
				return Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND));
			}))
			.flatMap(resource -> {
				try {
					if (HttpMethod.OPTIONS.matches(exchange.getRequest().getMethodValue())) {
						exchange.getResponse().getHeaders().add("Allow", "GET,HEAD,OPTIONS");
						return Mono.empty();
					}

					// Supported methods and required session
					HttpMethod httpMethod = exchange.getRequest().getMethod();
					if (!SUPPORTED_METHODS.contains(httpMethod)) {
						return Mono.error(new MethodNotAllowedException(
								exchange.getRequest().getMethodValue(), SUPPORTED_METHODS));
					}

					// Header phase
					if (exchange.checkNotModified(Instant.ofEpochMilli(resource.lastModified()))) {
						logger.trace(exchange.getLogPrefix() + "Resource not modified");
						return Mono.empty();
					}

					// Apply cache settings, if any
					CacheControl cacheControl = getCacheControl();
					if (cacheControl != null) {
						exchange.getResponse().getHeaders().setCacheControl(cacheControl);
					}

					// Check the media type for the resource
					MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(null);

					// Content phase
					if (HttpMethod.HEAD.matches(exchange.getRequest().getMethodValue())) {
						setHeaders(exchange, resource, mediaType);
						exchange.getResponse().getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
						return Mono.empty();
					}

					setHeaders(exchange, resource, mediaType);
					ResourceHttpMessageWriter writer = getResourceHttpMessageWriter();
					Assert.state(writer != null, "No ResourceHttpMessageWriter");
					return writer.write(Mono.just(resource),
							null, ResolvableType.forClass(Resource.class), mediaType,
							exchange.getRequest(), exchange.getResponse(),
							Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix()));
				}
				catch (IOException ex) {
					return Mono.error(ex);
				}
			});
}
 
Example #9
Source File: ResourceWebHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test(expected = MethodNotAllowedException.class)
public void unsupportedHttpMethod() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(""));
	setPathWithinHandlerMapping(exchange, "foo.css");
	this.handler.handle(exchange).block(TIMEOUT);
}
 
Example #10
Source File: ResourceWebHandler.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * 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)
			.switchIfEmpty(Mono.defer(() -> {
				logger.debug(exchange.getLogPrefix() + "Resource not found");
				return Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND));
			}))
			.flatMap(resource -> {
				try {
					if (HttpMethod.OPTIONS.matches(exchange.getRequest().getMethodValue())) {
						exchange.getResponse().getHeaders().add("Allow", "GET,HEAD,OPTIONS");
						return Mono.empty();
					}

					// Supported methods and required session
					HttpMethod httpMethod = exchange.getRequest().getMethod();
					if (!SUPPORTED_METHODS.contains(httpMethod)) {
						return Mono.error(new MethodNotAllowedException(
								exchange.getRequest().getMethodValue(), SUPPORTED_METHODS));
					}

					// Header phase
					if (exchange.checkNotModified(Instant.ofEpochMilli(resource.lastModified()))) {
						logger.trace(exchange.getLogPrefix() + "Resource not modified");
						return Mono.empty();
					}

					// Apply cache settings, if any
					CacheControl cacheControl = getCacheControl();
					if (cacheControl != null) {
						exchange.getResponse().getHeaders().setCacheControl(cacheControl);
					}

					// Check the media type for the resource
					MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(null);

					// Content phase
					if (HttpMethod.HEAD.matches(exchange.getRequest().getMethodValue())) {
						setHeaders(exchange, resource, mediaType);
						exchange.getResponse().getHeaders().set(HttpHeaders.ACCEPT_RANGES, "bytes");
						return Mono.empty();
					}

					setHeaders(exchange, resource, mediaType);
					ResourceHttpMessageWriter writer = getResourceHttpMessageWriter();
					Assert.state(writer != null, "No ResourceHttpMessageWriter");
					return writer.write(Mono.just(resource),
							null, ResolvableType.forClass(Resource.class), mediaType,
							exchange.getRequest(), exchange.getResponse(),
							Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix()));
				}
				catch (IOException ex) {
					return Mono.error(ex);
				}
			});
}
 
Example #11
Source File: ResourceWebHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test(expected = MethodNotAllowedException.class)
public void unsupportedHttpMethod() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(""));
	setPathWithinHandlerMapping(exchange, "foo.css");
	this.handler.handle(exchange).block(TIMEOUT);
}
 
Example #12
Source File: OneOffSpringWebFluxFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void handleFluxExceptions_handles_MethodNotAllowedException_as_expected(
    boolean supportedMethodsIsEmpty
) {
    // given
    String actualMethod = UUID.randomUUID().toString();
    List<HttpMethod> supportedMethods =
        (supportedMethodsIsEmpty)
        ? Collections.emptyList()
        : Arrays.asList(
            HttpMethod.GET,
            HttpMethod.POST
        );

    MethodNotAllowedException ex = new MethodNotAllowedException(actualMethod, supportedMethods);

    List<Pair<String, String>> expectedExtraDetailsForLogging = new ArrayList<>();
    ApiExceptionHandlerUtils.DEFAULT_IMPL.addBaseExceptionMessageToExtraDetailsForLogging(
        ex, expectedExtraDetailsForLogging
    );

    // when
    ApiExceptionHandlerListenerResult result = listener.handleSpringMvcOrWebfluxSpecificFrameworkExceptions(ex);

    // then
    // They throw the supported methods into a plain HashSet so we can't rely on the ordering.
    //      Verify it another way.
    Optional<String> supportedMethodsLoggingDetailsValue = result.extraDetailsForLogging
        .stream()
        .filter(p -> p.getKey().equals("supported_methods"))
        .map(Pair::getValue)
        .findAny();
    assertThat(supportedMethodsLoggingDetailsValue).isPresent();
    List<HttpMethod> actualLoggingDetailsMethods = supportedMethodsLoggingDetailsValue
        .map(s -> {
            if (s.equals("")) {
                return Collections.<HttpMethod>emptyList();
            }
            return Arrays.stream(s.split(",")).map(HttpMethod::valueOf).collect(Collectors.toList());
        })
        .orElse(Collections.emptyList());

    assertThat(actualLoggingDetailsMethods).containsExactlyInAnyOrderElementsOf(supportedMethods);

    expectedExtraDetailsForLogging.add(Pair.of("supported_methods", supportedMethodsLoggingDetailsValue.get()));

    validateResponse(
        result,
        true,
        singleton(testProjectApiErrors.getMethodNotAllowedApiError()),
        expectedExtraDetailsForLogging
    );
}