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; 030 031/** 032 * Defines a ShutdownHook for a class which has a cleanup method. 033 */ 034public class CleanupHook extends Thread { 035 036 /** The application, which this CleanupHook, should help to cleanup. */ 037 private CleanupIF app; 038 039 /** The name of the application, which this CleanupHook, should help to cleanup. */ 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 CleanupHook(CleanupIF app) { 048 ArgumentNotValid.checkNotNull(app, "CleanupIF 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("Cleaning up {}", appName); 062 } catch (Throwable e) { 063 // Ignore 064 } 065 try { 066 app.cleanup(); 067 } catch (Throwable e) { 068 System.out.println("Error while cleaning up " + appName); 069 e.printStackTrace(); 070 } 071 try { 072 // FIXME: No println in unit tests. 073 System.out.println("Cleaned up " + appName); 074 log.info("Cleaned up {}", appName); 075 } catch (Throwable e) { 076 System.out.println("Cleaned up " + appName + " but failed to log afterwards"); 077 e.printStackTrace(); 078 } 079 } 080 081}