001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, 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.util;
015
016import java.util.List;
017import java.util.Map;
018import java.util.Map.Entry;
019import java.util.Properties;
020
021import ch.qos.logback.core.Context;
022import ch.qos.logback.core.CoreConstants;
023import ch.qos.logback.core.hook.ShutdownHook;
024import ch.qos.logback.core.rolling.helper.FileNamePattern;
025import ch.qos.logback.core.spi.ContextAwareBase;
026
027public class ContextUtil extends ContextAwareBase {
028
029    static final String GROOVY_RUNTIME_PACKAGE = "org.codehaus.groovy.runtime";
030    // static final String SYSTEM_LOGGER_FQCN = "java.lang.System$Logger";
031
032    public ContextUtil(Context context) {
033        setContext(context);
034    }
035
036    public void addProperties(Properties props) {
037        if (props == null) {
038            return;
039        }
040
041        for (Entry<Object, Object> e : props.entrySet()) {
042            String key = (String) e.getKey();
043            context.putProperty(key, (String) e.getValue());
044        }
045
046    }
047
048    public void addGroovyPackages(List<String> frameworkPackages) {
049        addFrameworkPackage(frameworkPackages, GROOVY_RUNTIME_PACKAGE);
050    }
051
052    public void addFrameworkPackage(List<String> frameworkPackages, String packageName) {
053        if (!frameworkPackages.contains(packageName)) {
054            frameworkPackages.add(packageName);
055        }
056    }
057
058    /**
059     * Add a shutdown hook thread with the JVM runtime.
060     *
061     * If a previous shutdown hook thread was registered, it is replaced.
062     * @param hook
063     * @since 1.5.7
064     */
065    public void addOrReplaceShutdownHook(ShutdownHook hook) {
066        Runtime runtime = Runtime.getRuntime();
067
068        Thread oldShutdownHookThread = (Thread) context.getObject(CoreConstants.SHUTDOWN_HOOK_THREAD);
069        if(oldShutdownHookThread != null) {
070            addInfo("Removing old shutdown hook from JVM runtime");
071            runtime.removeShutdownHook(oldShutdownHookThread);
072        }
073
074        Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
075        addInfo("Registering shutdown hook with JVM runtime.");
076        context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread);
077        runtime.addShutdownHook(hookThread);
078
079    }
080
081}