/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.http.server;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Custom Jetty error handler. This allows overriding the factory-default error page to replace it with an
 * ESP-specific page, which includes the system banner.
 *
 * @author Alex Leigh
 */
public class ErrorHandler extends ErrorPageErrorHandler {
    private final String banner;

    public ErrorHandler(String banner) {
        this.banner = banner;
    }

    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("<html><head><meta charset=\"utf-8\"/><title>Error</title></head><body><h2>Error ");
        sb.append(String.valueOf(response.getStatus()));
        sb.append("</h2><i>");
        sb.append(banner);
        sb.append("</i></body></html>");

        response.getWriter().append(sb.toString());
    }
}
