Example usage for org.springframework.http MediaType ALL

List of usage examples for org.springframework.http MediaType ALL

Introduction

In this page you can find the example usage for org.springframework.http MediaType ALL.

Prototype

MediaType ALL

To view the source code for org.springframework.http MediaType ALL.

Click Source Link

Document

Public constant media type that includes all media ranges (i.e.

Usage

From source file:org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache.java

private static ServerWebExchangeMatcher createDefaultRequestMacher() {
    ServerWebExchangeMatcher get = ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/**");
    ServerWebExchangeMatcher notFavicon = new NegatedServerWebExchangeMatcher(
            ServerWebExchangeMatchers.pathMatchers("/favicon.*"));
    MediaTypeServerWebExchangeMatcher html = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
    html.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
    return new AndServerWebExchangeMatcher(get, notFavicon, html);
}

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

/**
 * Return a {@code RequestPredicate} that tests if the request's
 * {@linkplain ServerRequest.Headers#accept() accept} header is
 * {@linkplain MediaType#isCompatibleWith(MediaType) compatible} with any of the given media types.
 * @param mediaTypes the media types to match the request's accept header against
 * @return a predicate that tests the request's accept header against the given media types
 *///from  w  ww . j  av a  2s . c o  m
public static RequestPredicate accept(MediaType... mediaTypes) {
    Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
    Set<MediaType> mediaTypeSet = new HashSet<>(Arrays.asList(mediaTypes));

    return headers(new Predicate<ServerRequest.Headers>() {
        @Override
        public boolean test(ServerRequest.Headers headers) {
            List<MediaType> acceptedMediaTypes = headers.accept();
            if (acceptedMediaTypes.isEmpty()) {
                acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
            } else {
                MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
            }
            boolean match = acceptedMediaTypes.stream().anyMatch(
                    acceptedMediaType -> mediaTypeSet.stream().anyMatch(acceptedMediaType::isCompatibleWith));
            traceMatch("Accept", mediaTypeSet, acceptedMediaTypes, match);
            return match;
        }

        @Override
        public String toString() {
            return String.format("Accept: %s", mediaTypeSet);
        }
    });
}

From source file:org.springframework.web.reactive.result.HandlerResultHandlerSupport.java

/**
 * Select the best media type for the current request through a content
 * negotiation algorithm./*from   w  ww  .  j  a  v a  2s  . c  om*/
 * @param exchange the current request
 * @param producibleTypesSupplier the media types that can be produced for the current request
 * @return the selected media type or {@code null}
 */
@Nullable
protected MediaType selectMediaType(ServerWebExchange exchange,
        Supplier<List<MediaType>> producibleTypesSupplier) {

    MediaType contentType = exchange.getResponse().getHeaders().getContentType();
    if (contentType != null && contentType.isConcrete()) {
        if (logger.isDebugEnabled()) {
            logger.debug(exchange.getLogPrefix() + "Found 'Content-Type:" + contentType + "' in response");
        }
        return contentType;
    }

    List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
    List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);

    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
    for (MediaType acceptable : acceptableTypes) {
        for (MediaType producible : producibleTypes) {
            if (acceptable.isCompatibleWith(producible)) {
                compatibleMediaTypes.add(selectMoreSpecificMediaType(acceptable, producible));
            }
        }
    }

    List<MediaType> result = new ArrayList<>(compatibleMediaTypes);
    MediaType.sortBySpecificityAndQuality(result);

    MediaType selected = null;
    for (MediaType mediaType : result) {
        if (mediaType.isConcrete()) {
            selected = mediaType;
            break;
        } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION_ALL)) {
            selected = MediaType.APPLICATION_OCTET_STREAM;
            break;
        }
    }

    if (selected != null) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Using '" + selected + "' given " + acceptableTypes + " and supported " + producibleTypes);
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug(exchange.getLogPrefix() + "No match for " + acceptableTypes + ", supported: "
                + producibleTypes);
    }

    return selected;
}

From source file:org.springframework.web.servlet.mvc.method.annotation.support.AbstractMessageConverterMethodProcessor.java

private List<MediaType> getAcceptedMediaTypes(HttpInputMessage inputMessage) {
    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*w  w  w. j  a  v a 2 s  . c o m*/

    MediaType.sortByQualityValue(acceptedMediaTypes);
    return acceptedMediaTypes;
}

From source file:sg.ncl.DataController.java

@RequestMapping(value = "/public/{did}/resources/{rid}", method = RequestMethod.GET)
public void getPublicOpenResource(HttpSession session, @PathVariable String did, @PathVariable String rid,
        final HttpServletResponse httpResponse)
        throws UnsupportedEncodingException, WebServiceRuntimeException {
    if (session.getAttribute(PUBLIC_USER_ID) == null
            || session.getAttribute(PUBLIC_USER_ID).toString().isEmpty()) {
        throw new WebServiceRuntimeException("No public user id for downloading.");
    }//from   w ww.  ja  v a 2  s  . c  o  m
    try {
        String publicUserId = session.getAttribute(PUBLIC_USER_ID).toString();
        // Optional Accept header
        RequestCallback requestCallback = request -> {
            request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
            request.getHeaders().set("PublicUserId", publicUserId);
        };

        // Streams the response instead of loading it all in memory
        ResponseExtractor<Void> responseExtractor = getResponseExtractor(httpResponse);

        restTemplate.execute(properties.downloadPublicOpenResource(did, rid), HttpMethod.GET, requestCallback,
                responseExtractor);
    } catch (Exception e) {
        log.error("Error transferring download: {}", e.getMessage());
    }
}

From source file:sg.ncl.DataController.java

/**
 * References://from w  ww  .j a  va  2 s. c o  m
 * [1] http://stackoverflow.com/questions/25854077/calling-a-servlet-from-another-servlet-after-the-request-dispatcher-forward-meth
 * [2] http://stackoverflow.com/questions/29712554/how-to-download-a-file-using-a-java-rest-service-and-a-data-stream
 * [3] http://stackoverflow.com/questions/32988370/download-large-file-from-server-using-rest-template-java-spring-mvc
 */
@RequestMapping(value = "{datasetId}/resources/{resourceId}", method = RequestMethod.GET)
public void getResource(@PathVariable String datasetId, @PathVariable String resourceId, HttpSession session,
        final HttpServletResponse httpResponse)
        throws UnsupportedEncodingException, WebServiceRuntimeException {
    Dataset dataset = invokeAndExtractDataInfo(Long.valueOf(datasetId));
    if (!dataset.isDownloadable(session.getAttribute("id").toString())) {
        throw new WebServiceRuntimeException("Resource download denied!");
    }

    try {
        // Optional Accept header
        RequestCallback requestCallback = request -> {
            request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
            request.getHeaders().set("Authorization",
                    httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
        };

        // Streams the response instead of loading it all in memory
        ResponseExtractor<Void> responseExtractor = getResponseExtractor(httpResponse);

        restTemplate.execute(properties.downloadResource(datasetId, resourceId), HttpMethod.GET,
                requestCallback, responseExtractor);
    } catch (Exception e) {
        log.error("Error transferring download: {}", e.getMessage());
    }
}