class StreamResourceHandler implements Serializable {

    public void handleRequest(VaadinSession session, VaadinRequest request,
            VaadinResponse response, StreamResource streamResource)
            throws IOException {

        StreamResourceWriter writer;
        session.lock();
        try {
            ServletContext context = ((VaadinServletRequest) request)
                    .getServletContext();
            response.setContentType(streamResource.getContentTypeResolver()
                    .apply(streamResource, context));
            response.setCacheTime(streamResource.getCacheTime());
            writer = streamResource.getWriter();
            if (writer == null) {
                throw new IOException(
                        "Stream resource produces null input stream");
            }
        } catch (Exception exception) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw exception;

        } finally {
            session.unlock();
        }
        // don't use here "try resource" syntax sugar because in case there is
        // an exception the {@code outputStream} will be closed before "catch"
        // block which sets the status code and this code will not have any
        // effect being called after closing the stream (see #8740).
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            writer.accept(outputStream, session);
        } catch (Exception exception) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw exception;
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

}