001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2022, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.model.processor;
015
016import ch.qos.logback.core.Context;
017import ch.qos.logback.core.CoreConstants;
018import ch.qos.logback.core.hook.DefaultShutdownHook;
019import ch.qos.logback.core.hook.ShutdownHookBase;
020import ch.qos.logback.core.model.Model;
021import ch.qos.logback.core.model.ShutdownHookModel;
022import ch.qos.logback.core.util.DynamicClassLoadingException;
023import ch.qos.logback.core.util.IncompatibleClassException;
024import ch.qos.logback.core.util.OptionHelper;
025
026public class ShutdownHookModelHandler extends ModelHandlerBase {
027
028    public ShutdownHookModelHandler(Context context) {
029        super(context);
030    }
031
032    static public ModelHandlerBase makeInstance(Context context, ModelInterpretationContext ic) {
033        return new ShutdownHookModelHandler(context);
034    }
035
036    @Override
037    protected Class<ShutdownHookModel> getSupportedModelClass() {
038        return ShutdownHookModel.class;
039    }
040
041    @Override
042    public void handle(ModelInterpretationContext interpretationContext, Model model) {
043
044        ShutdownHookModel shutdownHookModel = (ShutdownHookModel) model;
045
046        String className = shutdownHookModel.getClassName();
047        if (OptionHelper.isNullOrEmpty(className)) {
048            className = DefaultShutdownHook.class.getName();
049            addInfo("Assuming className [" + className + "]");
050        } else {
051            className = interpretationContext.getImport(className);
052        }
053
054        addInfo("About to instantiate shutdown hook of type [" + className + "]");
055        ShutdownHookBase hook = null;
056        try {
057            hook = (ShutdownHookBase) OptionHelper.instantiateByClassName(className, ShutdownHookBase.class, context);
058            hook.setContext(context);
059        } catch (IncompatibleClassException | DynamicClassLoadingException e) {
060            addError("Could not create a shutdown hook of type [" + className + "].", e);
061        }
062
063        if (hook == null)
064            return;
065
066        Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
067        addInfo("Registeting shuthown hook with JVM runtime.");
068        context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread);
069        Runtime.getRuntime().addShutdownHook(hookThread);
070
071    }
072
073}