Example usage for org.springframework.http MediaTypeFactory getMediaType

List of usage examples for org.springframework.http MediaTypeFactory getMediaType

Introduction

In this page you can find the example usage for org.springframework.http MediaTypeFactory getMediaType.

Prototype

public static Optional<MediaType> getMediaType(@Nullable String filename) 

Source Link

Document

Determine a media type for the given file name, if possible.

Usage

From source file:org.springframework.http.codec.ResourceHttpMessageWriter.java

private static MediaType getResourceMediaType(@Nullable MediaType mediaType, Resource resource,
        Map<String, Object> hints) {

    if (mediaType != null && mediaType.isConcrete() && !mediaType.equals(MediaType.APPLICATION_OCTET_STREAM)) {
        return mediaType;
    }/*ww  w  .ja va  2  s. c  o m*/
    mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
    if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
        logger.debug(Hints.getLogPrefix(hints) + "Resource associated with '" + mediaType + "'");
    }
    return mediaType;
}

From source file:org.springframework.mock.web.MockServletContext.java

@Override
@Nullable//from w  w w .  j ava2 s  .c  om
public String getMimeType(String filePath) {
    String extension = StringUtils.getFilenameExtension(filePath);
    if (this.mimeTypes.containsKey(extension)) {
        return this.mimeTypes.get(extension).toString();
    } else {
        return MediaTypeFactory.getMediaType(filePath).map(MimeType::toString).orElse(null);
    }
}

From source file:org.springframework.mock.web.test.MockServletContext.java

@Override
public String getMimeType(String filePath) {
    String extension = StringUtils.getFilenameExtension(filePath);
    if (this.mimeTypes.containsKey(extension)) {
        return this.mimeTypes.get(extension).toString();
    } else {/*from   www.  j  a va2  s .co m*/
        return MediaTypeFactory.getMediaType(filePath).map(MimeType::toString).orElse(null);
    }
}

From source file:org.springframework.web.accept.AbstractMappingContentNegotiationStrategy.java

/**
 * Override to provide handling when a key is not resolved via.
 * {@link #lookupMediaType}. Sub-classes can take further steps to
 * determine the media type(s). If a MediaType is returned from
 * this method it will be added to the cache in the base class.
 *//*from   ww  w  . jav a  2  s. com*/
@Nullable
protected MediaType handleNoMatch(NativeWebRequest request, String key)
        throws HttpMediaTypeNotAcceptableException {

    if (!isUseRegisteredExtensionsOnly()) {
        Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("file." + key);
        if (mediaType.isPresent()) {
            return mediaType.get();
        }
    }
    if (isIgnoreUnknownExtensions()) {
        return null;
    }
    throw new HttpMediaTypeNotAcceptableException(getAllMediaTypes());
}

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

/**
 * Processes a resource request.//from  ww  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 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);
        }
    });
}