001package io.jstach.opt.spring.webflux;
002
003import java.nio.charset.Charset;
004import java.nio.charset.StandardCharsets;
005import java.util.Map;
006
007import org.eclipse.jdt.annotation.Nullable;
008import org.springframework.core.ResolvableType;
009import org.springframework.core.codec.AbstractSingleValueEncoder;
010import org.springframework.core.codec.Hints;
011import org.springframework.core.io.buffer.DataBuffer;
012import org.springframework.core.io.buffer.DataBufferFactory;
013import org.springframework.http.MediaType;
014import org.springframework.util.MimeType;
015
016import io.jstach.jstachio.JStachio;
017import reactor.core.publisher.Flux;
018
019/**
020 * Encodes a JStachio model into a bytes to be used as output from a webflux reactive
021 * controller.
022 *
023 * @author agentgt
024 * @author dsyer
025 */
026public class JStachioEncoder extends AbstractSingleValueEncoder<Object> {
027
028        private final JStachio jstachio;
029
030        /**
031         * Create the encoder from a JStachio
032         * @param jstachio not <code>null</code>.
033         */
034        public JStachioEncoder(JStachio jstachio) {
035                super(MediaType.TEXT_HTML);
036                this.jstachio = jstachio;
037        }
038
039        @Override
040        public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
041                Class<?> clazz = elementType.toClass();
042                return clazz != Object.class && !CharSequence.class.isAssignableFrom(clazz) && jstachio.supportsType(clazz);
043        }
044
045        @Override
046        protected Flux<DataBuffer> encode(Object event, DataBufferFactory bufferFactory, ResolvableType type,
047                        @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
048                return Flux.just(encodeValue(event, bufferFactory, type, mimeType, hints));
049        }
050
051        @Override
052        public DataBuffer encodeValue(Object event, DataBufferFactory bufferFactory, ResolvableType valueType,
053                        MimeType mimeType, Map<String, Object> hints) {
054                if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
055                        String logPrefix = Hints.getLogPrefix(hints);
056                        logger.debug(logPrefix + "Writing [" + event + "]");
057                }
058
059                Charset charset = StandardCharsets.UTF_8;
060                return bufferFactory.wrap(jstachio.execute(event).getBytes(charset));
061        }
062
063}