Example usage for org.springframework.http HttpMethod OPTIONS

List of usage examples for org.springframework.http HttpMethod OPTIONS

Introduction

In this page you can find the example usage for org.springframework.http HttpMethod OPTIONS.

Prototype

HttpMethod OPTIONS

To view the source code for org.springframework.http HttpMethod OPTIONS.

Click Source Link

Usage

From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundrySecurityInterceptor.java

SecurityResponse preHandle(HttpServletRequest request, String endpointId) {
    if (CorsUtils.isPreFlightRequest(request)) {
        return SecurityResponse.success();
    }//from   ww w  . j a v  a2  s .  co m
    try {
        if (!StringUtils.hasText(this.applicationId)) {
            throw new CloudFoundryAuthorizationException(
                    CloudFoundryAuthorizationException.Reason.SERVICE_UNAVAILABLE,
                    "Application id is not available");
        }
        if (this.cloudFoundrySecurityService == null) {
            throw new CloudFoundryAuthorizationException(
                    CloudFoundryAuthorizationException.Reason.SERVICE_UNAVAILABLE,
                    "Cloud controller URL is not available");
        }
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return SUCCESS;
        }
        check(request, endpointId);
    } catch (Exception ex) {
        logger.error(ex);
        if (ex instanceof CloudFoundryAuthorizationException) {
            CloudFoundryAuthorizationException cfException = (CloudFoundryAuthorizationException) ex;
            return new SecurityResponse(cfException.getStatusCode(),
                    "{\"security_error\":\"" + cfException.getMessage() + "\"}");
        }
        return new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    return SecurityResponse.success();
}

From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet.CloudFoundrySecurityInterceptor.java

SecurityResponse preHandle(HttpServletRequest request, String endpointId) {
    if (CorsUtils.isPreFlightRequest(request)) {
        return SecurityResponse.success();
    }//ww  w .  j av a2  s.com
    try {
        if (!StringUtils.hasText(this.applicationId)) {
            throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
                    "Application id is not available");
        }
        if (this.cloudFoundrySecurityService == null) {
            throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
                    "Cloud controller URL is not available");
        }
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return SUCCESS;
        }
        check(request, endpointId);
    } catch (Exception ex) {
        logger.error(ex);
        if (ex instanceof CloudFoundryAuthorizationException) {
            CloudFoundryAuthorizationException cfException = (CloudFoundryAuthorizationException) ex;
            return new SecurityResponse(cfException.getStatusCode(),
                    "{\"security_error\":\"" + cfException.getMessage() + "\"}");
        }
        return new SecurityResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
    }
    return SecurityResponse.success();
}

From source file:org.springframework.boot.actuate.endpoint.mvc.MvcEndpointSecurityInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if (CorsUtils.isPreFlightRequest(request) || !this.secure) {
        return true;
    }/*  www . ja  va 2  s .  c o m*/
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    if (HttpMethod.OPTIONS.matches(request.getMethod()) && !(handlerMethod.getBean() instanceof MvcEndpoint)) {
        return true;
    }
    MvcEndpoint mvcEndpoint = (MvcEndpoint) handlerMethod.getBean();
    if (!mvcEndpoint.isSensitive()) {
        return true;
    }
    if (isUserAllowedAccess(request)) {
        return true;
    }
    sendFailureResponse(request, response);
    return false;
}

From source file:org.springframework.web.client.RestTemplate.java

public Set<HttpMethod> optionsForAllow(String url, Object... urlVariables) throws RestClientException {
    HttpHeaders headers = execute(url, HttpMethod.OPTIONS, null, this.headersExtractor, urlVariables);
    return headers.getAllow();
}

From source file:org.springframework.web.client.RestTemplate.java

public Set<HttpMethod> optionsForAllow(String url, Map<String, ?> urlVariables) throws RestClientException {
    HttpHeaders headers = execute(url, HttpMethod.OPTIONS, null, this.headersExtractor, urlVariables);
    return headers.getAllow();
}

From source file:org.springframework.web.client.RestTemplate.java

public Set<HttpMethod> optionsForAllow(URI url) throws RestClientException {
    HttpHeaders headers = execute(url, HttpMethod.OPTIONS, null, this.headersExtractor);
    return headers.getAllow();
}

From source file:org.springframework.web.client.RestTemplateIntegrationTests.java

@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);
}

From source file:org.springframework.web.reactive.function.server.RequestPredicates.java

/**
 * Return a {@code RequestPredicate} that matches if request's HTTP method is {@code OPTIONS}
 * and the given {@code pattern} matches against the request path.
 * @param pattern the path pattern to match against
 * @return a predicate that matches if the request method is OPTIONS and if the given pattern
 * matches against the request path/*from   w ww .  ja va  2s.  c o  m*/
 */
public static RequestPredicate OPTIONS(String pattern) {
    return method(HttpMethod.OPTIONS).and(path(pattern));
}

From source file:org.springframework.web.reactive.resource.ResourceWebHandler.java

/**
 * Processes a resource request.//from   ww  w.  j av  a  2s.  com
 * <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.trace("No matching resource found - returning 404");
        return Mono.error(NOT_FOUND_EXCEPTION);
    })).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("Resource not modified - returning 304");
                return Mono.empty();
            }

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

            // Check the media type for the resource
            MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(null);
            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");
                }
            }

            // Content phase
            if (HttpMethod.HEAD.matches(exchange.getRequest().getMethodValue())) {
                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);
            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(), Collections.emptyMap());
        } catch (IOException ex) {
            return Mono.error(ex);
        }
    });
}

From source file:org.springframework.web.servlet.resource.ResourceHttpRequestHandler.java

/**
 * Processes a resource request./*  w  w  w  .j  a  v  a  2 s.c om*/
 * <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 void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // For very general mappings (e.g. "/") we need to check 404 first
    Resource resource = getResource(request);
    if (resource == null) {
        logger.trace("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (HttpMethod.OPTIONS.matches(request.getMethod())) {
        response.setHeader("Allow", getAllowHeader());
        return;
    }

    // Supported methods and required session
    checkRequest(request);

    // Header phase
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.trace("Resource not modified - returning 304");
        return;
    }

    // Apply cache settings, if any
    prepareResponse(response);

    // Check the media type for the resource
    MediaType mediaType = getMediaType(request, 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");
        }
    }

    // Content phase
    if (METHOD_HEAD.equals(request.getMethod())) {
        setHeaders(response, resource, mediaType);
        logger.trace("HEAD request - skipping content");
        return;
    }

    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
    if (request.getHeader(HttpHeaders.RANGE) == null) {
        Assert.state(this.resourceHttpMessageConverter != null, "Not initialized");
        setHeaders(response, resource, mediaType);
        this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage);
    } else {
        Assert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized");
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
        try {
            List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            this.resourceRegionHttpMessageConverter.write(HttpRange.toResourceRegions(httpRanges, resource),
                    mediaType, outputMessage);
        } catch (IllegalArgumentException ex) {
            response.setHeader("Content-Range", "bytes */" + resource.contentLength());
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        }
    }
}