001package ch.qos.logback.classic.servlet;
002
003import static ch.qos.logback.core.CoreConstants.DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY;
004
005import java.util.Set;
006
007import jakarta.servlet.ServletContainerInitializer;
008import jakarta.servlet.ServletContext;
009import jakarta.servlet.ServletException;
010
011import ch.qos.logback.classic.util.StatusViaSLF4JLoggerFactory;
012import ch.qos.logback.core.util.OptionHelper;
013
014/**
015 * Attaches a new instance of {@link LogbackServletContextListener} to the
016 * current web-applications {@link ServletContext}.
017 * 
018 * @author Ceki Gulcu
019 * @since 1.1.10
020 */
021public class LogbackServletContainerInitializer implements ServletContainerInitializer {
022
023    @Override
024    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
025
026        if (isDisabledByConfiguration(ctx)) {
027            StatusViaSLF4JLoggerFactory.addInfo("Due to deployment instructions will NOT register an instance of "
028                    + LogbackServletContextListener.class + " to the current web-app", this);
029
030            return;
031        }
032
033        StatusViaSLF4JLoggerFactory.addInfo(
034                "Adding an instance of  " + LogbackServletContextListener.class + " to the current web-app", this);
035        LogbackServletContextListener lscl = new LogbackServletContextListener();
036        ctx.addListener(lscl);
037    }
038
039    /**
040     * Search for value of DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY in the web-app
041     * first, then as a system property and as an environment variable last.
042     *
043     * @param ctx
044     * @return True if value of DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY is
045     *         available and set to "true", false otherwise.
046     */
047    boolean isDisabledByConfiguration(ServletContext ctx) {
048        String disableAttributeStr = null;
049        Object disableAttribute = ctx.getInitParameter(DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY);
050        if (disableAttribute instanceof String) {
051            disableAttributeStr = (String) disableAttribute;
052        }
053
054        if (OptionHelper.isNullOrEmptyOrAllSpaces(disableAttributeStr)) {
055            disableAttributeStr = OptionHelper.getSystemProperty(DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY);
056        }
057
058        if (OptionHelper.isNullOrEmptyOrAllSpaces(disableAttributeStr)) {
059            disableAttributeStr = OptionHelper.getEnv(DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY);
060        }
061
062        return Boolean.parseBoolean(disableAttributeStr);
063    }
064
065}