Search in sources :

Example 16 with HttpMethod

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

the class RestTemplateIntegrationTests method optionsForAllow.

@Test
public void optionsForAllow() throws URISyntaxException {
    Set<HttpMethod> allowed = template.optionsForAllow(new URI(baseUrl + "/get"));
    assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE), allowed);
}
Also used : URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Example 17 with HttpMethod

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

the class RestTemplateTests method optionsForAllow.

@Test
public void optionsForAllow() throws Exception {
    given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.OPTIONS)).willReturn(request);
    given(request.execute()).willReturn(response);
    given(errorHandler.hasError(response)).willReturn(false);
    HttpHeaders responseHeaders = new HttpHeaders();
    EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST);
    responseHeaders.setAllow(expected);
    given(response.getHeaders()).willReturn(responseHeaders);
    HttpStatus status = HttpStatus.OK;
    given(response.getStatusCode()).willReturn(status);
    given(response.getStatusText()).willReturn(status.getReasonPhrase());
    Set<HttpMethod> result = template.optionsForAllow("http://example.com");
    assertEquals("Invalid OPTIONS result", expected, result);
    verify(response).close();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpStatus(org.springframework.http.HttpStatus) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Example 18 with HttpMethod

use of org.springframework.http.HttpMethod 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 19 with HttpMethod

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

the class AbstractMessageConverterMethodArgumentResolver method readWithMessageConverters.

/**
	 * Create the method argument value of the expected parameter type by reading
	 * from the given HttpInputMessage.
	 * @param <T> the expected type of the argument value to be created
	 * @param inputMessage the HTTP input message representing the current request
	 * @param parameter the method parameter descriptor (may be {@code null})
	 * @param targetType the target type, not necessarily the same as the method
	 * parameter type, e.g. for {@code HttpEntity<String>}.
	 * @return the created method argument value
	 * @throws IOException if the reading from the request fails
	 * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found
	 */
@SuppressWarnings("unchecked")
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
    MediaType contentType;
    boolean noContentType = false;
    try {
        contentType = inputMessage.getHeaders().getContentType();
    } catch (InvalidMediaTypeException ex) {
        throw new HttpMediaTypeNotSupportedException(ex.getMessage());
    }
    if (contentType == null) {
        noContentType = true;
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }
    Class<?> contextClass = (parameter != null ? parameter.getContainingClass() : null);
    Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
    if (targetClass == null) {
        ResolvableType resolvableType = (parameter != null ? ResolvableType.forMethodParameter(parameter) : ResolvableType.forType(targetType));
        targetClass = (Class<T>) resolvableType.resolve();
    }
    HttpMethod httpMethod = ((HttpRequest) inputMessage).getMethod();
    Object body = NO_VALUE;
    try {
        inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage);
        for (HttpMessageConverter<?> converter : this.messageConverters) {
            Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
            if (converter instanceof GenericHttpMessageConverter) {
                GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
                if (genericConverter.canRead(targetType, contextClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (inputMessage.getBody() != null) {
                        inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
                        body = genericConverter.read(targetType, contextClass, inputMessage);
                        body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
                    } else {
                        body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
                    }
                    break;
                }
            } else if (targetClass != null) {
                if (converter.canRead(targetClass, contentType)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (inputMessage.getBody() != null) {
                        inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
                        body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
                        body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
                    } else {
                        body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
                    }
                    break;
                }
            }
        }
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex);
    }
    if (body == NO_VALUE) {
        if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) || (noContentType && inputMessage.getBody() == null)) {
            return null;
        }
        throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
    }
    return body;
}
Also used : HttpRequest(org.springframework.http.HttpRequest) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) IOException(java.io.IOException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException) GenericHttpMessageConverter(org.springframework.http.converter.GenericHttpMessageConverter)

Example 20 with HttpMethod

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

the class TransportHandlingSockJsService method handleTransportRequest.

@Override
protected void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, String sessionId, String transport) throws SockJsException {
    TransportType transportType = TransportType.fromValue(transport);
    if (transportType == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Unknown transport type for " + request.getURI());
        }
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return;
    }
    TransportHandler transportHandler = this.handlers.get(transportType);
    if (transportHandler == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("No TransportHandler for " + request.getURI());
        }
        response.setStatusCode(HttpStatus.NOT_FOUND);
        return;
    }
    SockJsException failure = null;
    HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, handler);
    try {
        HttpMethod supportedMethod = transportType.getHttpMethod();
        if (supportedMethod != request.getMethod()) {
            if (HttpMethod.OPTIONS == request.getMethod() && transportType.supportsCors()) {
                if (checkOrigin(request, response, HttpMethod.OPTIONS, supportedMethod)) {
                    response.setStatusCode(HttpStatus.NO_CONTENT);
                    addCacheHeaders(response);
                }
            } else if (transportType.supportsCors()) {
                sendMethodNotAllowed(response, supportedMethod, HttpMethod.OPTIONS);
            } else {
                sendMethodNotAllowed(response, supportedMethod);
            }
            return;
        }
        SockJsSession session = this.sessions.get(sessionId);
        if (session == null) {
            if (transportHandler instanceof SockJsSessionFactory) {
                Map<String, Object> attributes = new HashMap<>();
                if (!chain.applyBeforeHandshake(request, response, attributes)) {
                    return;
                }
                SockJsSessionFactory sessionFactory = (SockJsSessionFactory) transportHandler;
                session = createSockJsSession(sessionId, sessionFactory, handler, attributes);
            } else {
                response.setStatusCode(HttpStatus.NOT_FOUND);
                if (logger.isDebugEnabled()) {
                    logger.debug("Session not found, sessionId=" + sessionId + ". The session may have been closed " + "(e.g. missed heart-beat) while a message was coming in.");
                }
                return;
            }
        } else {
            if (session.getPrincipal() != null) {
                if (!session.getPrincipal().equals(request.getPrincipal())) {
                    logger.debug("The user for the session does not match the user for the request.");
                    response.setStatusCode(HttpStatus.NOT_FOUND);
                    return;
                }
            }
            if (!transportHandler.checkSessionType(session)) {
                logger.debug("Session type does not match the transport type for the request.");
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return;
            }
        }
        if (transportType.sendsNoCacheInstruction()) {
            addNoCacheHeaders(response);
        }
        if (transportType.supportsCors()) {
            if (!checkOrigin(request, response)) {
                return;
            }
        }
        transportHandler.handleRequest(request, response, handler, session);
        chain.applyAfterHandshake(request, response, null);
    } catch (SockJsException ex) {
        failure = ex;
    } catch (Throwable ex) {
        failure = new SockJsException("Uncaught failure for request " + request.getURI(), sessionId, ex);
    } finally {
        if (failure != null) {
            chain.applyAfterHandshake(request, response, failure);
            throw failure;
        }
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SockJsException(org.springframework.web.socket.sockjs.SockJsException) HandshakeInterceptorChain(org.springframework.web.socket.server.support.HandshakeInterceptorChain) HttpMethod(org.springframework.http.HttpMethod)

Aggregations

HttpMethod (org.springframework.http.HttpMethod)35 Test (org.junit.Test)19 URI (java.net.URI)16 IOException (java.io.IOException)11 HttpHeaders (org.springframework.http.HttpHeaders)8 ClientHttpRequest (org.springframework.http.client.ClientHttpRequest)7 ClientHttpRequestFactory (org.springframework.http.client.ClientHttpRequestFactory)7 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)4 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)4 DefaultAccessTokenRequest (org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 HttpRequest (org.springframework.http.HttpRequest)3 EnumSet (java.util.EnumSet)2 HashMap (java.util.HashMap)2 Set (java.util.Set)2 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)2 ResolvableType (org.springframework.core.ResolvableType)2 InvalidMediaTypeException (org.springframework.http.InvalidMediaTypeException)2 MediaType (org.springframework.http.MediaType)2 HttpRequestWrapper (org.springframework.http.client.support.HttpRequestWrapper)2