001/*
002 * Copyright 2002-2016 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.http.converter;
018
019import java.io.ByteArrayOutputStream;
020import java.io.IOException;
021
022import org.springframework.http.HttpInputMessage;
023import org.springframework.http.HttpOutputMessage;
024import org.springframework.http.MediaType;
025import org.springframework.util.StreamUtils;
026
027/**
028 * Implementation of {@link HttpMessageConverter} that can read and write byte arrays.
029 *
030 * <p>By default, this converter supports all media types ({@code &#42;&#47;&#42;}), and
031 * writes with a {@code Content-Type} of {@code application/octet-stream}. This can be
032 * overridden by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
033 *
034 * @author Arjen Poutsma
035 * @author Juergen Hoeller
036 * @since 3.0
037 */
038public class ByteArrayHttpMessageConverter extends AbstractHttpMessageConverter<byte[]> {
039
040        /**
041         * Create a new instance of the {@code ByteArrayHttpMessageConverter}.
042         */
043        public ByteArrayHttpMessageConverter() {
044                super(new MediaType("application", "octet-stream"), MediaType.ALL);
045        }
046
047
048        @Override
049        public boolean supports(Class<?> clazz) {
050                return byte[].class == clazz;
051        }
052
053        @Override
054        public byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException {
055                long contentLength = inputMessage.getHeaders().getContentLength();
056                ByteArrayOutputStream bos =
057                                new ByteArrayOutputStream(contentLength >= 0 ? (int) contentLength : StreamUtils.BUFFER_SIZE);
058                StreamUtils.copy(inputMessage.getBody(), bos);
059                return bos.toByteArray();
060        }
061
062        @Override
063        protected Long getContentLength(byte[] bytes, MediaType contentType) {
064                return (long) bytes.length;
065        }
066
067        @Override
068        protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException {
069                StreamUtils.copy(bytes, outputMessage.getBody());
070        }
071
072}