001/*
002 * Copyright 2002-2019 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.core.codec;
018
019import java.util.Map;
020
021import org.reactivestreams.Publisher;
022import reactor.core.publisher.Flux;
023
024import org.springframework.core.ResolvableType;
025import org.springframework.core.io.buffer.DataBuffer;
026import org.springframework.core.io.buffer.DataBufferFactory;
027import org.springframework.lang.Nullable;
028import org.springframework.util.MimeType;
029import org.springframework.util.MimeTypeUtils;
030
031/**
032 * Encoder for {@code byte} arrays.
033 *
034 * @author Arjen Poutsma
035 * @since 5.0
036 */
037public class ByteArrayEncoder extends AbstractEncoder<byte[]> {
038
039        public ByteArrayEncoder() {
040                super(MimeTypeUtils.ALL);
041        }
042
043
044        @Override
045        public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
046                Class<?> clazz = elementType.toClass();
047                return super.canEncode(elementType, mimeType) && byte[].class.isAssignableFrom(clazz);
048        }
049
050        @Override
051        public Flux<DataBuffer> encode(Publisher<? extends byte[]> inputStream,
052                        DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
053                        @Nullable Map<String, Object> hints) {
054
055                // Use (byte[] bytes) for Eclipse
056                return Flux.from(inputStream).map((byte[] bytes) ->
057                                encodeValue(bytes, bufferFactory, elementType, mimeType, hints));
058        }
059
060        @Override
061        public DataBuffer encodeValue(byte[] bytes, DataBufferFactory bufferFactory,
062                        ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
063
064                DataBuffer dataBuffer = bufferFactory.wrap(bytes);
065                if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
066                        String logPrefix = Hints.getLogPrefix(hints);
067                        logger.debug(logPrefix + "Writing " + dataBuffer.readableByteCount() + " bytes");
068                }
069                return dataBuffer;
070        }
071
072}