@Override public Optional<String> getContentType() { return from.getContentType(); }
private void writeEvent(OutputEvent evt, HttpResponse response) { evt.getHeaders().asMap() .entrySet() .stream() .filter(e -> !stripOutputHeaders.contains(e.getKey())) .flatMap(e -> e.getValue().stream().map((v) -> new BasicHeader(e.getKey(), v))) .forEachOrdered(response::addHeader); ContentType contentType = evt.getContentType().map(c -> { try { return ContentType.parse(c); } catch (ParseException e) { return ContentType.DEFAULT_BINARY; } }).orElse(ContentType.DEFAULT_BINARY); response.setHeader("Content-Type", contentType.toString()); response.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_1, evt.getStatus().getCode(), evt.getStatus().name())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); // TODO remove output buffering here - possibly change OutputEvent contract to support providing an InputStream? try { evt.writeToOutput(bos); } catch (IOException e) { throw new FunctionOutputHandlingException("Error writing output", e); } byte[] data = bos.toByteArray(); response.setEntity(new ByteArrayEntity(data, contentType)); }
@Test public void testResponseWriter_WithContentHeader_ShouldUseContentHeaderGiven() throws IOException { Map<String, List<String>> headers = new HashMap<>(); headers.put("Content-Type", Collections.singletonList(MediaType.TEXT_HTML)); SimpleRequestHandler.SimpleResponseWriter<FnRequestHandler.WrappedOutput> responseWriter = requestHandler.createResponseWriter(null); responseWriter.writeResponse(Response.Status.OK, headers, new ByteArrayOutputStream()); Assert.assertTrue(responseWriter.getResponse().getOutputEvent().getContentType().get().equals(MediaType.TEXT_HTML)); }
@Test public void testResponseWriter_WithoutContentHeader_ShouldDefaultToApplicationJson() throws IOException { Map<String, List<String>> headers = new HashMap<>(); SimpleRequestHandler.SimpleResponseWriter<FnRequestHandler.WrappedOutput> responseWriter = requestHandler.createResponseWriter(null); responseWriter.writeResponse(Response.Status.OK, headers, new ByteArrayOutputStream()); Assert.assertTrue(responseWriter.getResponse().getOutputEvent().getContentType().get().equals(MediaType.APPLICATION_JSON)); }
evt.getContentType().ifPresent((ct) -> response.setHeader(CONTENT_TYPE_HEADER, ct)); response.setHeader("Content-length", String.valueOf(data.length));