001package io.jstach.opt.spring.webmvc;
002
003import java.io.IOException;
004
005import org.springframework.http.HttpOutputMessage;
006import org.springframework.http.MediaType;
007import org.springframework.http.server.ServletServerHttpResponse;
008
009import io.jstach.jstachio.JStachio;
010import io.jstach.jstachio.Output.CloseableEncodedOutput;
011import io.jstach.opt.spring.web.JStachioHttpMessageConverter;
012import jakarta.servlet.http.HttpServletResponse;
013
014/**
015 * A servlet server aware {@link JStachioHttpMessageConverter} that will leverage
016 * {@link HttpServletResponse#setBufferSize(int)} to reduce duplicate buffering.
017 *
018 * @author agentgt
019 *
020 */
021public class ServletJStachioHttpMessageConverter extends JStachioHttpMessageConverter {
022
023        /**
024         * See {@link JStachioHttpMessageConverter}
025         * @param jstachio not null.
026         * @param mediaType used for setContentType
027         * @param bufferLimit limit used if the response is not a
028         * {@link ServletServerHttpResponse}.
029         */
030        public ServletJStachioHttpMessageConverter(JStachio jstachio, @SuppressWarnings("exports") MediaType mediaType,
031                        int bufferLimit) {
032                super(jstachio, mediaType, bufferLimit);
033        }
034
035        @Override
036        protected CloseableEncodedOutput<IOException> createOutput(HttpOutputMessage message) {
037                if (message instanceof ServletServerHttpResponse sr) {
038                        return createOutput(sr.getServletResponse());
039                }
040                return super.createOutput(message);
041        }
042
043        /**
044         * Create the output from a servlet response.
045         * @param response servlet response
046         * @return closeable output.
047         */
048        protected CloseableEncodedOutput<IOException> createOutput(HttpServletResponse response) {
049                return new ServletThresholdEncodedOutput(getDefaultCharset(), response, bufferLimit);
050        }
051
052}