package _VisualDVM.Repository.Server;
import org.apache.commons.io.FileUtils;
import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.io.File;
import java.util.Date;
public class DiagnosticSignalHandler implements SignalHandler {
    private SignalHandler oldHandler;
    private SignalHandler handler;
    public DiagnosticSignalHandler() {
    }
    // Static method to install the signal handler
    public static void install(String signalName, SignalHandler handler) {
        Signal signal = new Signal(signalName);
        DiagnosticSignalHandler diagnosticSignalHandler = new DiagnosticSignalHandler();
        SignalHandler oldHandler = Signal.handle(signal, diagnosticSignalHandler);
        diagnosticSignalHandler.setHandler(handler);
        diagnosticSignalHandler.setOldHandler(oldHandler);
    }
    private void setOldHandler(SignalHandler oldHandler) {
        this.oldHandler = oldHandler;
    }
    private void setHandler(SignalHandler handler) {
        this.handler = handler;
    }
    // Signal handler method
    // Signal handler method
    @Override
    public void handle(Signal sig) {
        System.out.println("Diagnostic Signal handler called for signal " + sig);
        try {
            FileUtils.writeStringToFile(new File("got SIG" + sig.getName() + " " + new Date().toString().replace(':', '_')), "");
            handler.handle(sig);
// Chain back to previous handler, if one exists
            if (oldHandler != SIG_DFL && oldHandler != SIG_IGN) {
                oldHandler.handle(sig);
            }
        } catch (Exception e) {
            System.out.println("Signal handler failed, reason " + e);
        }
    }
}
