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.nio.ByteBuffer;
020import java.util.Map;
021
022import org.reactivestreams.Publisher;
023import reactor.core.publisher.Flux;
024
025import org.springframework.core.ResolvableType;
026import org.springframework.core.io.buffer.DataBuffer;
027import org.springframework.core.io.buffer.DataBufferFactory;
028import org.springframework.lang.Nullable;
029import org.springframework.util.MimeType;
030import org.springframework.util.MimeTypeUtils;
031
032/**
033 * Encoder for {@link ByteBuffer ByteBuffers}.
034 *
035 * @author Sebastien Deleuze
036 * @since 5.0
037 */
038public class ByteBufferEncoder extends AbstractEncoder<ByteBuffer> {
039
040        public ByteBufferEncoder() {
041                super(MimeTypeUtils.ALL);
042        }
043
044
045        @Override
046        public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
047                Class<?> clazz = elementType.toClass();
048                return super.canEncode(elementType, mimeType) && ByteBuffer.class.isAssignableFrom(clazz);
049        }
050
051        @Override
052        public Flux<DataBuffer> encode(Publisher<? extends ByteBuffer> inputStream,
053                        DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
054                        @Nullable Map<String, Object> hints) {
055
056                return Flux.from(inputStream).map(byteBuffer ->
057                                encodeValue(byteBuffer, bufferFactory, elementType, mimeType, hints));
058        }
059
060        @Override
061        public DataBuffer encodeValue(ByteBuffer byteBuffer, DataBufferFactory bufferFactory,
062                        ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
063
064                DataBuffer dataBuffer = bufferFactory.wrap(byteBuffer);
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}