001/*
002 * Copyright 2002-2020 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.core.io.buffer.DataBufferUtils;
028import org.springframework.core.io.buffer.PooledDataBuffer;
029import org.springframework.lang.Nullable;
030import org.springframework.util.MimeType;
031
032/**
033 * Abstract base class for {@link org.springframework.core.codec.Encoder}
034 * classes that can only deal with a single value.
035 *
036 * @author Arjen Poutsma
037 * @since 5.0
038 * @param <T> the element type
039 */
040public abstract class AbstractSingleValueEncoder<T> extends AbstractEncoder<T> {
041
042
043        public AbstractSingleValueEncoder(MimeType... supportedMimeTypes) {
044                super(supportedMimeTypes);
045        }
046
047
048        @Override
049        public final Flux<DataBuffer> encode(Publisher<? extends T> inputStream, DataBufferFactory bufferFactory,
050                        ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
051
052                return Flux.from(inputStream)
053                                .take(1)
054                                .concatMap(value -> encode(value, bufferFactory, elementType, mimeType, hints))
055                                .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
056        }
057
058        /**
059         * Encode {@code T} to an output {@link DataBuffer} stream.
060         * @param t the value to process
061         * @param dataBufferFactory a buffer factory used to create the output
062         * @param type the stream element type to process
063         * @param mimeType the mime type to process
064         * @param hints additional information about how to do decode, optional
065         * @return the output stream
066         */
067        protected abstract Flux<DataBuffer> encode(T t, DataBufferFactory dataBufferFactory,
068                        ResolvableType type, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints);
069
070}