use of com.vaadin.flow.server.StreamResourceWriter in project flow by vaadin.
the class StreamResourceHandlerTest method inputStreamResourceWriterThrows_responseStatusIs500.
@Test
public void inputStreamResourceWriterThrows_responseStatusIs500() throws IOException {
StreamResource res = new StreamResource("readme.md", (StreamResourceWriter) (stream, session) -> {
throw new RuntimeException("Simulated");
});
try {
handler.handleRequest(session, request, response, res);
} catch (RuntimeException ignore) {
// Ignore exception, it's expected. We need to check the status
}
Mockito.verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
use of com.vaadin.flow.server.StreamResourceWriter in project flow by vaadin.
the class StreamResourceHandler method handleRequest.
/**
* Handle sending for a stream resource request.
*
* @param session
* session for the request
* @param request
* request to handle
* @param response
* response object to which a response can be written.
* @param streamResource
* stream resource that handles data writer
*
* @throws IOException
* if an IO error occurred
*/
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());
streamResource.getHeaders().forEach((name, value) -> response.setHeader(name, value));
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();
}
}
}
Aggregations