All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.graylog2.rest.GraylogErrorPageGenerator Maven / Gradle / Ivy

There is a newer version: 6.1.4
Show newest version
/*
 * Copyright (C) 2020 Graylog, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Server Side Public License, version 1,
 * as published by MongoDB, Inc.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Server Side Public License for more details.
 *
 * You should have received a copy of the Server Side Public License
 * along with this program. If not, see
 * .
 */
package org.graylog2.rest;

import com.floreysoft.jmte.Engine;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import org.apache.commons.lang3.StringEscapeUtils;
import org.glassfish.grizzly.http.server.ErrorPageGenerator;
import org.glassfish.grizzly.http.server.Request;

import javax.inject.Inject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static java.util.Objects.requireNonNull;

public class GraylogErrorPageGenerator implements ErrorPageGenerator {
    private final String template;
    private final Engine engine;

    @Inject
    public GraylogErrorPageGenerator(Engine templateEngine) throws IOException {
        this(Resources.toString(Resources.getResource("error.html.template"), StandardCharsets.UTF_8), templateEngine);
    }

    private GraylogErrorPageGenerator(String template, Engine templateEngine) {
        this.template = requireNonNull(template, "template");
        this.engine = requireNonNull(templateEngine, "templateEngine");
    }

    @Override
    public String generate(Request request, int status, String reasonPhrase, String description, Throwable exception) {
        final ImmutableMap.Builder modelBuilder = ImmutableMap.builder();
        modelBuilder.put("reason", StringEscapeUtils.escapeHtml4(reasonPhrase));

        if (description != null) {
            modelBuilder.put("description", StringEscapeUtils.escapeHtml4(description));
        }

        if (exception != null) {
            String exceptionString = Objects.nonNull(exception.getMessage()) ? exception.getMessage() : "Null";
            modelBuilder.put("exception", StringEscapeUtils.escapeHtml4(exceptionString));
        }

        return engine.transform(template, modelBuilder.build());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy