// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jdisc.http.server.jetty; import org.eclipse.jetty.util.ByteArrayISO8859Writer; import org.eclipse.jetty.util.StringUtil; import java.io.IOException; import java.util.Optional; /** * Creates HTML body having the status code, error message and request uri. * The body is constructed from a template that is inspired by the default Jetty template (see {@link org.eclipse.jetty.server.Response#sendError(int, String)}). * The content is written using the ISO-8859-1 charset. * * @author bjorncs */ public class ErrorResponseContentCreator { private final ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(2048); public byte[] createErrorContent(String requestUri, int statusCode, Optional message) { String sanitizedString = message.map(StringUtil::sanitizeXmlString).orElse(""); String statusCodeString = Integer.toString(statusCode); writer.resetWriter(); try { writer.write("\n\n\nError "); writer.write(statusCodeString); writer.write("\n\n\n

HTTP ERROR: "); writer.write(statusCodeString); writer.write("

\n

Problem accessing "); writer.write(StringUtil.sanitizeXmlString(requestUri)); writer.write(". Reason:\n

    ");
            writer.write(sanitizedString);
            writer.write("

\n
\n\n\n"); } catch (IOException e) { // IOException should not be thrown unless writer is constructed using byte[] parameter throw new RuntimeException(e); } return writer.getByteArray(); } }