001/*
002 * #%L
003 * Netarchivesuite - common
004 * %%
005 * Copyright (C) 2005 - 2014 The Royal Danish Library, the Danish State and University Library,
006 *             the National Library of France and the Austrian National Library.
007 * %%
008 * This program is free software: you can redistribute it and/or modify
009 * it under the terms of the GNU Lesser General Public License as
010 * published by the Free Software Foundation, either version 2.1 of the
011 * License, or (at your option) any later version.
012 * 
013 * This program is distributed in the hope that it will be useful,
014 * but WITHOUT ANY WARRANTY; without even the implied warranty of
015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016 * GNU General Lesser Public License for more details.
017 * 
018 * You should have received a copy of the GNU General Lesser Public
019 * License along with this program.  If not, see
020 * <http://www.gnu.org/licenses/lgpl-2.1.html>.
021 * #L%
022 */
023
024package dk.netarkivet.common.utils;
025
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029import dk.netarkivet.common.exceptions.ArgumentNotValid;
030import dk.netarkivet.common.lifecycle.LifeCycleComponent;
031
032/**
033 * Defines a ShutdownHook for a class which has a cleanup method.
034 */
035public class ShutdownHook extends Thread {
036
037    /** The component to hook up to. */
038    private LifeCycleComponent app;
039    /** The name of the hooked application. */
040    private String appName;
041
042    /**
043     * Returns a ShutdownHook thread for an object with a cleanup() method.
044     *
045     * @param app the Object to be cleaned up
046     */
047    public ShutdownHook(LifeCycleComponent app) {
048        ArgumentNotValid.checkNotNull(app, "LifeCycleComponent app");
049        this.app = app;
050        appName = app.getClass().getName();
051    }
052
053    /**
054     * Called by the JVM to clean up the object before exiting. The method calls the cleanup() method Note:
055     * System.out.println is added in this method because logging may or may not be active at this time.
056     */
057    public void run() {
058        Logger log = null;
059        try {
060            log = LoggerFactory.getLogger(appName);
061            log.info("Shutting down {}", appName);
062        } catch (Throwable e) {
063            // Ignore
064        }
065        try {
066            app.shutdown();
067        } catch (Throwable e) {
068            System.out.println("Error while  shutting down " + appName);
069            e.printStackTrace();
070        }
071        try {
072            System.out.println("Shutting down " + appName);
073            log.info("Shutting down {}", appName);
074        } catch (Throwable e) {
075            System.out.println("Shutting down " + appName + " but failed to log afterwards");
076            e.printStackTrace();
077        }
078    }
079
080}