Example usage for org.springframework.http MediaType APPLICATION_OCTET_STREAM

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

Introduction

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

Prototype

MediaType APPLICATION_OCTET_STREAM

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

Click Source Link

Document

Public constant media type for application/octet-stream .

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;
    }//from  w w w  .  j  a  v  a 2 s. co  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.http.converter.AbstractHttpMessageConverter.java

/**
 * Add default headers to the output message.
 * <p>This implementation delegates to {@link #getDefaultContentType(Object)} if a
 * content type was not provided, set if necessary the default character set, calls
 * {@link #getContentLength}, and sets the corresponding headers.
 * @since 4.2/*from   w w  w.j ava2  s. co  m*/
 */
protected void addDefaultHeaders(HttpHeaders headers, T t, @Nullable MediaType contentType) throws IOException {
    if (headers.getContentType() == null) {
        MediaType contentTypeToUse = contentType;
        if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
            contentTypeToUse = getDefaultContentType(t);
        } else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
            MediaType mediaType = getDefaultContentType(t);
            contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse);
        }
        if (contentTypeToUse != null) {
            if (contentTypeToUse.getCharset() == null) {
                Charset defaultCharset = getDefaultCharset();
                if (defaultCharset != null) {
                    contentTypeToUse = new MediaType(contentTypeToUse, defaultCharset);
                }
            }
            headers.setContentType(contentTypeToUse);
        }
    }
    if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
        Long contentLength = getContentLength(t, headers.getContentType());
        if (contentLength != null) {
            headers.setContentLength(contentLength);
        }
    }
}

From source file:org.springframework.integration.x.channel.registry.ChannelRegistrySupport.java

protected final Message<?> transformOutboundIfNecessary(Message<?> message, MediaType to) {
    Message<?> messageToSend = message;
    Object originalPayload = message.getPayload();
    Object payload = null;//  w  w w.ja  v a  2  s .  c o m
    Object originalContentType = message.getHeaders().get(MessageHeaders.CONTENT_TYPE);
    String originalContentTypeString = null;
    if (originalContentType instanceof MediaType) {
        originalContentTypeString = originalContentType.toString();
    } else if (originalContentType instanceof String) {
        originalContentTypeString = (String) originalContentType;
    }
    String contentType = originalContentTypeString;
    if (to.equals(MediaType.ALL)) {
        return message;
    } else if (to.equals(MediaType.APPLICATION_OCTET_STREAM)) {
        if (originalPayload instanceof byte[]) {
            payload = originalPayload;
            contentType = XD_OCTET_STREAM_VALUE;
        } else if (originalPayload instanceof String) {
            try {
                payload = ((String) originalPayload).getBytes("UTF-8");
                contentType = XD_TEXT_PLAIN_UTF8_VALUE;
            } catch (UnsupportedEncodingException e) {
                logger.error("Could not convert String to bytes", e);
            }
        } else {
            payload = this.jsonMapper.toBytes(originalPayload);
            contentType = XD_JSON_OCTET_STREAM_VALUE;
        }
    } else {
        throw new IllegalArgumentException("'to' can only be 'ALL' or 'APPLICATION_OCTET_STREAM'");
    }
    if (payload != null) {
        MessageBuilder<Object> messageBuilder = MessageBuilder.withPayload(payload)
                .copyHeaders(message.getHeaders()).setHeader(MessageHeaders.CONTENT_TYPE, contentType);
        if (originalContentTypeString != null) {
            messageBuilder.setHeader(ORIGINAL_CONTENT_TYPE_HEADER, originalContentTypeString);
        }
        messageToSend = messageBuilder.build();
    }
    return messageToSend;
}

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

@Override
protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension)
        throws HttpMediaTypeNotAcceptableException {

    if (this.useJaf) {
        MediaType jafMediaType = JafMediaTypeFactory.getMediaType("file." + extension);
        if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) {
            return jafMediaType;
        }//www  .j a va2s . com
    }
    if (!this.ignoreUnknownExtensions) {
        throw new HttpMediaTypeNotAcceptableException(getAllMediaTypes());
    }
    return null;
}

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

private MediaType getContentType(ClientHttpResponse response) {
    MediaType contentType = response.getHeaders().getContentType();
    if (contentType == null) {
        if (logger.isTraceEnabled()) {
            logger.trace("No Content-Type header found, defaulting to application/octet-stream");
        }//from   ww w  .  j  a  v a2 s. c  o  m
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }
    return contentType;
}

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

/**
 * Return a {@code RequestPredicate} that tests if the request's
 * {@linkplain ServerRequest.Headers#contentType() content type} is
 * {@linkplain MediaType#includes(MediaType) included} by any of the given media types.
 * @param mediaTypes the media types to match the request's content type against
 * @return a predicate that tests the request's content type against the given media types
 *//*from   ww w  .j  a  v a  2s . c o m*/
public static RequestPredicate contentType(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) {
            MediaType contentType = headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
            boolean match = mediaTypeSet.stream().anyMatch(mediaType -> mediaType.includes(contentType));
            traceMatch("Content-Type", mediaTypeSet, contentType, match);
            return match;
        }

        @Override
        public String toString() {
            return String.format("Content-Type: %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 w  w . ja  v  a 2s.  c  o m*/
 * @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.AbstractMessageConverterMethodArgumentResolver.java

/**
 * Create the method argument value of the expected parameter type by reading
 * from the given HttpInputMessage./*  w  w w .  j a v  a  2s  .  co m*/
 * @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
 * @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")
@Nullable
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.getContainingClass();
    Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
    if (targetClass == null) {
        ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
        targetClass = (Class<T>) resolvableType.resolve();
    }

    HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod()
            : null);
    Object body = NO_VALUE;

    EmptyBodyCheckingHttpInputMessage message;
    try {
        message = new EmptyBodyCheckingHttpInputMessage(inputMessage);

        for (HttpMessageConverter<?> converter : this.messageConverters) {
            Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter
                    .getClass();
            GenericHttpMessageConverter<?> genericConverter = (converter instanceof GenericHttpMessageConverter
                    ? (GenericHttpMessageConverter<?>) converter
                    : null);
            if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType)
                    : (targetClass != null && converter.canRead(targetClass, contentType))) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                }
                if (message.hasBody()) {
                    HttpInputMessage msgToUse = getAdvice().beforeBodyRead(message, parameter, targetType,
                            converterType);
                    body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse)
                            : ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
                    body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
                } else {
                    body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
                }
                break;
            }
        }
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
    }

    if (body == NO_VALUE) {
        if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod)
                || (noContentType && !message.hasBody())) {
            return null;
        }
        throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
    }

    return body;
}

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

/**
 * Creates the method argument value of the expected parameter type by reading from the given HttpInputMessage. 
 * //from   w w  w  .  j a v a2 s .  c o  m
 * @param <T> the expected type of the argument value to be created 
 * @param inputMessage the HTTP input message representing the current request
 * @param methodParam the method argument
 * @param paramType the type of the argument value to be created
 * @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 methodParam,
        Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    if (contentType == null) {
        contentType = MediaType.APPLICATION_OCTET_STREAM;
    }

    for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
        if (messageConverter.canRead(paramType, contentType)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using ["
                        + messageConverter + "]");
            }
            return ((HttpMessageConverter<T>) messageConverter).read(paramType, inputMessage);
        }
    }

    throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
}

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.");
    }//  w ww. j  ava  2 s .  co 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());
    }
}